code stringlengths 1 2.06M | language stringclasses 1 value |
|---|---|
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
using std::distance;
void Input(vector <int> *list) {
int count;
cin >> count;
list->reserve(count);
int element;
for (int i(0); i < count; ++i) {
cin >> element;
list->push_back(element);
}
}
template <typename iterator = vector <int>::iterator>
void Merge(iterator first_begin, iterator first_end,
iterator second_begin, iterator second_end,
iterator result_begin) {
iterator result_current = result_begin;
while (first_begin != first_end ||
second_begin != second_end) {
if (second_begin == second_end ||
(first_begin != first_end &&
*first_begin <= *second_begin)) {
*result_current = *first_begin;
++result_current;
++first_begin;
}
else if (first_begin == first_end ||
(second_begin != second_end &&
*first_begin > *second_begin)) {
*result_current = *second_begin;
++result_current;
++second_begin;
}
}
}
void Output(vector <int>::iterator iterator_begin,
vector <int>::iterator iterator_end) {
for (auto i = iterator_begin; i != iterator_end; ++i) {
cout << *i << " ";
}
}
template <typename iterator = vector <int>::iterator>
void Sort_merge(iterator iterator_begin, iterator iterator_end,
iterator help_begin) {
if (iterator_begin + 1 < iterator_end) {
auto iterator_middle = iterator_begin +
distance(iterator_begin, iterator_end) / 2;
Sort_merge(iterator_begin, iterator_middle, help_begin);
Sort_merge(iterator_middle, iterator_end, help_begin);
Merge(iterator_begin, iterator_middle,
iterator_middle, iterator_end, help_begin);
iterator help_begin_copy = help_begin;
for (auto iterator_main = iterator_begin;
iterator_main != iterator_end; ++iterator_main) {
*iterator_main = *help_begin_copy;
++help_begin_copy;
}
}
}
int main() {
vector <int> list, help;
Input(&list);
help.resize(list.size());
Sort_merge(list.begin(), list.end(), help.begin());
Output(list.begin(), list.end());
} | C++ |
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
using std::distance;
void Input(vector <int> *list) {
int count;
cin >> count;
list->reserve(count);
int element;
for (int i(0); i < count; ++i) {
cin >> element;
list->push_back(element);
}
}
template <typename iterator = vector <int>::iterator>
void Merge(iterator first_begin, iterator first_end,
iterator second_begin, iterator second_end,
iterator result_begin) {
iterator result_current = result_begin;
while (first_begin != first_end ||
second_begin != second_end) {
if (second_begin == second_end ||
(first_begin != first_end &&
*first_begin <= *second_begin)) {
*result_current = *first_begin;
++result_current;
++first_begin;
}
else
if (first_begin == first_end ||
(second_begin != second_end &&
*first_begin > *second_begin)) {
*result_current = *second_begin;
++result_current;
++second_begin;
}
}
}
void Output(vector <int> *list) {
for (auto i = list->begin(); i != list->end(); ++i) {
cout << *i << " ";
}
}
int main() {
vector <int> list1, list2, answer;
Input(&list1);
Input(&list2);
answer.resize(list1.size() + list2.size());
Merge(list1.begin(), list1.end(),
list2.begin(), list2.end(), answer.begin());
Output(&answer);
} | C++ |
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
void Input(vector <int> *list) {
int count;
cin >> count;
list->reserve(count);
int element;
for (int i(0); i < count; ++i) {
cin >> element;
list->push_back(element);
}
}
template <typename iterator = vector <int>::iterator>
void Swap_max(iterator iterator_begin, iterator iterator_end) {
if (iterator_begin != iterator_end) {
auto max_current = iterator_begin;
for (auto i = iterator_begin; i != iterator_end; ++i) {
if (*max_current < *i) {
max_current = i;
}
}
iter_swap(max_current, iterator_end - 1);
}
}
template <typename iterator = vector <int>::iterator>
void Sort_bubble(iterator iterator_begin, iterator iterator_end) {
while (iterator_begin != iterator_end) {
Swap_max(iterator_begin, iterator_end);
--iterator_end;
}
}
void Output(vector <int> *list) {
for (auto i = list->begin(); i != list->end(); ++i) {
cout << *i << " ";
}
}
int main() {
vector <int> list;
Input(&list);
Sort_bubble(list.begin(), list.end());
Output(&list);
} | C++ |
#include <iostream>
#include <algorithm>
#include <vector>
#include <ctime>
using std::cin;
using std::cout;
using std::vector;
using std::swap;
using std::distance;
using std::pair;
using std::make_pair;
void Input(vector <int> *list) {
int count;
cin >> count;
list->reserve(count);
int element;
for (int i(0); i < count; ++i) {
cin >> element;
list->push_back(element);
}
}
void Output(vector <int>::iterator iterator_begin,
vector <int>::iterator iterator_end) {
for (auto i = iterator_begin; i != iterator_end; ++i) {
cout << *i << " ";
}
}
template <typename type = int, typename iterator = vector <int>::iterator>
pair <iterator, iterator> Partition(iterator iterator_begin,
iterator iterator_end, type pivot) {
if (iterator_begin == iterator_end) {
return make_pair(iterator_begin, iterator_begin);
}
iterator iterator_first = iterator_begin;
iterator iterator_last = iterator_end;
auto iterator_current = iterator_begin;
while (iterator_current != iterator_last) {
if (*iterator_current < pivot) {
iter_swap(iterator_current, iterator_first);
++iterator_first;
++iterator_current;
}
else if (*iterator_current > pivot) {
--iterator_last;
iter_swap(iterator_current, iterator_last);
}
else {
++iterator_current;
}
}
iterator iterator_second = iterator_first;
iterator_current = iterator_first;
while (iterator_current != iterator_end) {
if (*iterator_current == pivot) {
iter_swap(iterator_current, iterator_second);
++iterator_second;
}
++iterator_current;
}
return make_pair (iterator_first, iterator_second);
}
template <typename iterator = vector <int>::iterator>
void Sort_quick(iterator iterator_begin, iterator iterator_end) {
if (distance(iterator_begin, iterator_end) > 1) {
int pivot = *(iterator_begin + ((long long)rand() * (long long)rand()) %
distance(iterator_begin, iterator_end));
auto iterator_pair = Partition(iterator_begin, iterator_end,
pivot);
Sort_quick(iterator_begin, iterator_pair.first);
Sort_quick(iterator_pair.second, iterator_end);
}
}
int main() {
srand(time(NULL));
vector <int> list;
Input(&list);
Sort_quick(list.begin(), list.end());
Output(list.begin(), list.end());
} | C++ |
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
#include <ctime>
using std::string;
using std::vector;
using std::min;
using std::cin;
using std::cout;
using std::endl;
class BullsAndCows {
struct Value {
vector <int> count_of_number;
vector <int> number;
Value() {
count_of_number.resize(10, 0);
number.resize(4, 0);
}
void create_new() {
for (int i = 0; i < 4; ++i) {
number[i] = rand() % 10;
++count_of_number[number[i]];
}
}
};
Value hidden;
Value string_to_value(string const &line) const {
Value result;
for (auto i = 0; i < 4; ++i) {
result.number[i] = (int)(line[i] - '0');
++result.count_of_number[(int)(line[i] - '0')];
}
return result;
}
void print_hidden() {
for (int i = 0; i < 4; ++i) {
cout << hidden.number[i];
}
cout << endl;
}
public:
struct Answer {
int cows;
int bulls;
bool win;
};
void start_game() {
hidden.create_new();
#ifdef _DEBUG
print_hidden();
#endif
}
Answer count_answer(string const &guess) const {
Answer answer;
int cows = 0;
int bulls = 0;
Value question = string_to_value(guess);
for (int i = 0; i < 10; ++i) {
cows += min(question.count_of_number[i],
hidden.count_of_number[i]);
}
for (int i = 0; i < 4; ++i) {
if (hidden.number[i] == question.number[i]) {
++bulls;
}
}
answer.bulls = bulls;
answer.cows = cows;
answer.win = (bulls == 4);
return answer;
}
};
void Game() {
srand(time(NULL));
BullsAndCows Game;
Game.start_game();
cout << "Game started!" << endl;
string question;
BullsAndCows::Answer answer;
bool is_bad_input;
do {
do {
cout << "Input number length 4: ";
cin >> question;
is_bad_input = 0;
for (int i = 0; i < question.size(); ++i) {
if (question[i] < '0' || question[i] > '9') {
is_bad_input = 1;
break;
}
}
if (is_bad_input == 1 || question.size() != 4) {
cout << "Bad input!" << endl;
}
} while (question.size() != 4 || is_bad_input);
answer = Game.count_answer(question);
cout << answer.cows << " " << answer.bulls << endl;
} while (answer.win == 0);
cout << "WIN" << endl;
}
int main() {
Game();
} | C++ |
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::set;
using std::pair;
using std::make_pair;
using std::min;
class Graph {
struct Vertex {
double x, y;
int number;
vector <Vertex*> edges;
Vertex(): x(0), y(0), number(0) {}
Vertex(double new_x, double new_y, Graph *graph) : x(new_x), y(new_y) {
edges.reserve(graph->count);
number = graph->vertices.size();
}
void add_edge(Vertex &a) {
edges.push_back(&a);
}
};
int count;
vector <Vertex> vertices;
double distance(Vertex &a, Vertex &b) const {
return (a.x - b.x) * (a.x - b.x)
+ (a.y - b.y) * (a.y - b.y);
}
void add_vertex(double x, double y) {
vertices.push_back(Vertex(x, y, this));
}
void dfs(int current_number, vector <bool> &used) {
used[current_number] = 1;
for (auto it = vertices[current_number].edges.begin();
it != vertices[current_number].edges.end(); ++it) {
if (used[(*it)->number] == 0) {
dfs((*it)->number, used);
}
}
}
public:
Graph(): count(0) {}
template <typename iter>
Graph(iter input_begin, iter input_end): count((input_end - input_begin) / 2) {
vertices.reserve((input_end - input_begin) / 2);
for (iter i = input_begin; i != input_end; i += 2) {
add_vertex(*i, *(i + 1));
}
}
void reserve(int n) {
vertices.reserve(n);
}
void make_edges(double k) {
for (int i = 0; i < count; ++i) {
for (int j = 0; j < count; ++j) {
if (i != j && distance(vertices[i], vertices[j]) <= k * k) {
vertices[i].add_edge(vertices[j]);
vertices[j].add_edge(vertices[i]);
}
}
}
}
bool is_connected() {
vector <bool> used(count, 0);
dfs(0, used);
for (int i = 0; i < count; ++i) {
if (used[i] == 0) {
return 0;
}
}
return 1;
}
};
int main () {
int n;
double k;
vector <double> in;
cin >> n >> k;
in.reserve(2 * n);
for (int i = 0; i < n; ++i) {
double x, y;
cin >> x >> y;
in.push_back(x);
in.push_back(y);
}
Graph graph(in.begin(), in.end());
graph.make_edges(k);
if (graph.is_connected()) {
cout << "YES";
} else {
cout << "NO";
}
}
| C++ |
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::set;
using std::pair;
using std::make_pair;
using std::min;
class Graph {
struct Vertex {
int interval_number;
bool type; // 0 - begin, 1 - end
vector <Vertex*> edges;
Vertex(): interval_number(0), type(0) {}
Vertex(int interval_number_in, bool type_in, Graph *graph) :
interval_number(interval_number_in), type(type_in){
}
void add_edge(Vertex &a) {
edges.push_back(&a);
}
};
int count;
vector <Vertex> vertices;
void add_vertex(int interval_number, bool type) {
vertices.push_back(Vertex(interval_number, type, this));
}
void dfs(int current_number, vector <int> &used, vector <Vertex*> &path, bool &is_cycled) {
if (is_cycled) {
return;
}
used[current_number] = 1;
for (auto it = vertices[current_number].edges.begin();
it != vertices[current_number].edges.end(); ++it) {
int vertex_number = get_vertex_number((*it)->interval_number, (*it)->type);
if (used[vertex_number] == 0) {
dfs(vertex_number, used, path, is_cycled);
} else if (used[vertex_number] == 1) {
is_cycled = true;
}
}
used[current_number] = 2;
path.push_back(&vertices[current_number]);
}
public:
Graph(): count(0) {}
Graph(int n): count(n * 2) {
vertices.reserve(n * 2);
for (int i = 0; i < n; ++i) {
vertices.push_back(Vertex(i + 1, 0, this));
vertices.push_back(Vertex(i + 1, 1, this));
add_edge(i * 2, i * 2 + 1);
}
}
void reserve(int n) {
vertices.reserve(n * 2);
}
static int get_vertex_number(int interval_number, bool type) {
return (interval_number - 1) * 2 + type;
}
void add_edge (int from, int to) {
vertices[from].add_edge(vertices[to]);
}
void add_following(int left, int right) {
add_edge(get_vertex_number(left, 0), get_vertex_number(right, 0));
add_edge(get_vertex_number(left, 0), get_vertex_number(right, 1));
add_edge(get_vertex_number(left, 1), get_vertex_number(right, 0));
add_edge(get_vertex_number(left, 1), get_vertex_number(right, 1));
}
void add_intersection(int left, int right) {
add_edge(get_vertex_number(left, 0), get_vertex_number(right, 1));
add_edge(get_vertex_number(right, 0), get_vertex_number(left, 1));
}
vector < pair<int, int> > find_interval_location(bool &is_impossible) {
vector < pair<int, int> > location(count / 2, make_pair(0, 0));
vector <int> used(count, false);
vector <Vertex*> path;
path.reserve(count);
bool is_cycled;
for (int i = 0; i < count; ++i) {
if (used[i] == 0) {
dfs(i, used, path, is_cycled);
}
}
reverse(path.begin(), path.end());
if (is_cycled) {
is_impossible = false;
} else {
int number = 0;
for (auto ¤t : path) {
if (current->type == 0) {
location[current->interval_number - 1].first = number;
} else {
location[current->interval_number - 1].second = number;
}
++number;
}
}
return location;
};
};
int main () {
int n, a, b;
cin >> n >> a >> b;
Graph graph(n);
for (int i = 0; i < a; ++i) {
int left, right;
cin >> left >> right;
graph.add_following(left, right);
}
for (int i = 0; i < b; ++i) {
int left, right;
cin >> left >> right;
graph.add_intersection(left, right);
}
bool is_impossible = true;
vector < pair<int, int> > location = graph.find_interval_location(is_impossible);
if (is_impossible) {
for (auto it : location) {
cout << it.first << " " << it.second << std::endl;
}
} else {
cout << "Impossible";
}
}
| C++ |
#include <iostream>
#include <vector>
#include <set>
#include <algorithm>
using std::abs;
using std::vector;
using std::cin;
using std::cout;
using std::set;
using std::pair;
using std::make_pair;
using std::min;
const int INF = 1000000001;
class Field {
struct Point {
int x, y, weight;
Point() : x(0), y(0), weight(0){}
Point(int new_x, int new_y, int new_weight) :
x(new_x), y(new_y), weight(new_weight) {}
bool operator<(Point other) const {
if (x == other.x) {
return y < other.y;
}
return x < other.x;
}
bool operator==(Point other) const {
return weight == other.weight && x == other.x && y == other.y;
}
bool operator!=(Point other) const {
return weight != other.weight || x != other.x || y != other.y;
}
};
int height;
int width;
vector < vector <Point> > field;
void make_neighbour_list(Point &point, vector <Point*> &list) {
int shift_x[4] = {-1, 0, 1, 0};
int shift_y[4] = {0, 1, 0, -1};
for (int i = 0; i < 4; ++i) {
if (point.x + shift_x[i] >= 0
&& point.x + shift_x[i] < height
&& point.y + shift_y[i] >= 0
&& point.y + shift_y[i] < width) {
list.push_back(&field[point.x + shift_x[i]][point.y + shift_y[i]]);
}
}
}
public:
Field(int new_height, int new_weight) {
height = new_height;
width = new_weight;
vector <Point> line(width);
field.assign(height, line);
for (int line = 0; line != height; ++line) {
for (int col = 0; col != width; ++col) {
int weight;
cin >> weight;
field[line][col] = Point(line, col, weight);
}
}
}
vector<Point> operator[](int &line) {
return field[line];
}
// Algorithm - A*
int find_step_count(int begin_x, int begin_y, int end_x, int end_y) {
Point begin = field[begin_x - 1][begin_y - 1];
Point end = field[end_x - 1][end_y - 1];
vector < vector <int> > step_count;
vector <int> line(width, INF);
step_count.assign(height, line);
step_count[begin.x][begin.y] = 0;
set < pair <int, Point*> > reachable_points;
reachable_points.insert(make_pair (abs(begin.x - end.x) + abs(begin.y - end.y), &begin));
while (!reachable_points.empty()) {
bool finded = 0;
Point current = *(reachable_points.begin()->second);
reachable_points.erase(reachable_points.begin());
vector <Point*> neighbours;
make_neighbour_list(current, neighbours);
for (auto it : neighbours) {
if (it->weight == 0 && step_count[it->x][it->y] > step_count[current.x][current.y] + 1) {
step_count[it->x][it->y] = step_count[current.x][current.y] + 1;
reachable_points.insert(make_pair(step_count[it->x][it->y]
+ abs(it->x - end.x) + abs(it->y - end.y), &(*it)));
if (*it == end) {
finded = 1;
break;
}
}
}
if (finded == 1) {
break;
}
}
return step_count[end.x][end.y];
}
};
int main() {
int n, m;
int begin_x, begin_y, end_x, end_y;
cin >> n >> m;
cin >> begin_x >> begin_y >> end_x >> end_y;
Field field(n, m);
int answer = field.find_step_count(begin_x, begin_y, end_x, end_y);
if (answer == INF) {
cout << "NO";
} else {
cout << answer;
}
}
| C++ |
#include <iostream>
#include <vector>`
#include <set>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::set;
using std::pair;
using std::make_pair;
using std::min;
class Field {
struct Point {
int x, y, weight;
Point(): x(0), y(0), weight(0){}
Point(int new_x, int new_y, int new_weight):
x(new_x), y(new_y), weight(new_weight) {}
bool operator<(Point other) const {
return weight < other.weight;
}
};
int height;
int width;
vector < vector <Point> > field;
void make_neighbour_list(Point &point, vector <Point> &list) {
if (point.x < height - 1) {
list.push_back(field[point.x + 1][point.y]);
}
if (point.y < width - 1) {
list.push_back(field[point.x][point.y + 1]);
}
}
public:
Field(int new_height, int new_weight) {
height = new_height;
width = new_weight;
vector <Point> line(width);
field.assign(height, line);
for (int line = 0; line != height; ++line) {
for (int col = 0; col != width; ++col) {
int weight;
cin >> weight;
field[line][col] = Point(line, col, weight);
}
}
}
vector<Point> operator[](int &line) {
return field[line];
}
int find_path_width() {
Point begin = field[0][0];
vector < vector <int> > path_weight;
vector <int> line(width, 1000000001);
path_weight.assign(height, line);
path_weight[0][0] = begin.weight;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (!(i == 0 && j == 0)) {
int up = 1000000001;
int left = 1000000001;
if (i > 0) {
up = path_weight[i - 1][j];
}
if (j > 0) {
left = path_weight[i][j - 1];
}
path_weight[i][j] = field[i][j].weight + min(up, left);
}
}
}
return path_weight[height - 1][width - 1];
}
};
int main () {
int n, m;
cin >> n >> m;
Field field(n, m);
cout << field.find_path_width();
} | C++ |
#include <iostream>
#include <vector>`
#include <set>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::set;
using std::pair;
using std::make_pair;
using std::min;
class Field {
struct Point {
int x, y, weight;
Point(): x(0), y(0), weight(0){}
Point(int new_x, int new_y, int new_weight):
x(new_x), y(new_y), weight(new_weight) {}
bool operator<(Point other) const {
return weight < other.weight;
}
};
int height;
int width;
vector < vector <Point> > field;
void make_neighbour_list(Point &point, vector <Point> &list) {
if (point.x < height - 1) {
list.push_back(field[point.x + 1][point.y]);
}
if (point.y < width - 1) {
list.push_back(field[point.x][point.y + 1]);
}
}
public:
Field(int new_height, int new_weight) {
height = new_height;
width = new_weight;
vector <Point> line(width);
field.assign(height, line);
for (int line = 0; line != height; ++line) {
for (int col = 0; col != width; ++col) {
int weight;
cin >> weight;
field[line][col] = Point(line, col, weight);
}
}
}
vector<Point> operator[](int &line) {
return field[line];
}
int find_path_width() {
vector < vector <int> > path_weight;
vector <int> line(width, 0);
path_weight.assign(height, line);
path_weight[0][0] = field[0][0].weight;
for (int i = 0; i < height; ++i) {
for (int j = 0; j < width; ++j) {
if (!(i == 0 && j == 0)) {
int up = 0;
int left = 0;
if (i > 0) {
up = path_weight[i - 1][j];
}
if (j > 0) {
left = path_weight[i][j - 1];
}
if (field[i][j].weight == 1) {
path_weight[i][j] = (left + up) % 268435459;
}
}
}
}
return (path_weight[height - 1][width - 1]);
}
};
int main () {
int n, m;
cin >> n >> m;
Field field(n, m);
cout << field.find_path_width();
} | C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
template <typename InputIterator>
void iteration(InputIterator first, InputIterator last) {
if (first == last) {
return;
}
auto max_iterator = first, last_elem_iterator = last;
--last_elem_iterator;
for (auto index_iterator = first; index_iterator != last; ++index_iterator) {
if (*index_iterator > *max_iterator) {
max_iterator = index_iterator;
}
}
iter_swap(last_elem_iterator, max_iterator);
}
void input(int &n, vector <int> &lst) {
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
}
void output(const vector <int> &lst) {
for (size_t i = 0; i < lst.size(); i++) {
cout << lst[i] << ' ';
}
}
int main() {
vector <int> lst;
int n;
input(n, lst);
iteration(lst.begin(), lst.end());
output(lst);
return 0;
}
| C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
template <typename InputIterator, typename TKey>
InputIterator my_partition(InputIterator begin, InputIterator end, TKey key) {
auto iter = begin;
while (begin != end) {
if (*begin < key) {
iter_swap(iter, begin);
++iter;
}
++begin;
}
return iter;
}
void input(vector <int> &lst, int &x) {
int n;
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
cin >> x;
}
void output(int a, int b) {
cout << a << '\n' << b;
}
int main() {
int x;
vector <int> lst;
input(lst, x);
auto iter = my_partition(lst.begin(), lst.end(), x);
output(iter - lst.begin(), lst.end() - iter);
return 0;
}
| C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::copy;
using std::cout;
using std::vector;
template <typename InputIterator, typename OutputIterator>
void my_merge(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end, OutputIterator out_begin) {
while (first_begin != first_end && second_begin != second_end) {
if (*first_begin < *second_begin) {
*out_begin = *first_begin;
++first_begin;
} else {
*out_begin = *second_begin;
++second_begin;
}
++out_begin;
}
while (first_begin != first_end) {
*out_begin = *first_begin;
++first_begin, ++out_begin;
}
while (second_begin != second_end) {
*out_begin = *second_begin;
++second_begin, ++out_begin;
}
}
template <typename InputIterator>
void merge_sort(InputIterator begin, InputIterator end) {
int length = end - begin;
if (length <= 1) {
return;
}
InputIterator middle = begin + length / 2;
auto for_type = *begin;
vector <decltype(for_type)> out(length);
merge_sort(begin, middle);
merge_sort(middle, end);
my_merge(begin, middle, middle, end, out.begin());
copy(out.begin(), out.end(), begin);
}
void input(vector <int> &lst) {
int n;
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
}
void output(const vector <int> &lst) {
for (size_t i = 0; i < lst.size(); i++) {
cout << lst[i] << ' ';
}
}
int main() {
vector <int> lst;
input(lst);
merge_sort(lst.begin(), lst.end());
output(lst);
return 0;
}
| C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
template <typename InputIterator, typename OutputIterator>
void my_merge(InputIterator first_begin, InputIterator first_end,
InputIterator second_begin, InputIterator second_end, OutputIterator out_begin) {
while (first_begin != first_end && second_begin != second_end) {
if (*first_begin < *second_begin) {
*out_begin = *first_begin;
++first_begin;
} else {
*out_begin = *second_begin;
++second_begin;
}
++out_begin;
}
while (first_begin != first_end) {
*out_begin = *first_begin;
++first_begin, ++out_begin;
}
while (second_begin != second_end) {
*out_begin = *second_begin;
++second_begin, ++out_begin;
}
}
void input(vector <int> &lst) {
int n;
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
}
void output(const vector <int> &lst) {
for (size_t i = 0; i < lst.size(); i++) {
cout << lst[i] << ' ';
}
}
int main() {
vector <int> first_lst, second_lst, output_lst;
input(first_lst);
input(second_lst);
output_lst.resize(first_lst.size() + second_lst.size());
my_merge(first_lst.begin(), first_lst.end(), second_lst.begin(), second_lst.end(),
output_lst.begin());
output(output_lst);
return 0;
}
| C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
template <typename InputIterator>
void iteration(InputIterator first, InputIterator last) {
if (first == last) {
return;
}
auto max_iterator = first, last_elem_iterator = last;
--last_elem_iterator;
for (auto index_iterator = first; index_iterator != last; ++index_iterator) {
if (*index_iterator > *max_iterator) {
max_iterator = index_iterator;
}
}
iter_swap(last_elem_iterator, max_iterator);
}
template <typename InputIterator>
void my_sort(InputIterator first, InputIterator last) {
for (auto end = last; first != end; --end) {
iteration(first, end);
}
}
void input(int &n, vector <int> &lst) {
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
}
void output(const vector <int> &lst) {
for (size_t i = 0; i < lst.size(); i++) {
cout << lst[i] << ' ';
}
}
int main() {
vector <int> lst;
int n;
input(n, lst);
my_sort(lst.begin(), lst.end());
output(lst);
return 0;
}
| C++ |
#include <iostream>
#include <cstdio>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::min;
void input(vector <vector <int> > &cost, vector <vector <int> > &dp) {
int n, m;
cin >> n >> m;
cost.resize(n);
dp.resize(n);
for (int i = 0; i < n; i++) {
dp[i].resize(m);
cost[i].resize(m);
for (int j = 0; j < m; j++) {
cin >> cost[i][j];
}
}
}
void solution(const vector <vector <int> > &cost, vector <vector <int> > &dp) {
dp[0][0] = cost[0][0];
for (int i = 1; i < cost.size(); i++) {
dp[i][0] = dp[i - 1][0] + cost[i][0];
}
for (int i = 1; i < cost[0].size(); i++) {
dp[0][i] = dp[0][i - 1] + cost[0][i];
}
for (int i = 1; i < cost.size(); i++) {
for (int j = 1; j < cost[i].size(); j++) {
dp[i][j] = min(dp[i - 1][j], dp[i][j - 1]) + cost[i][j];
}
}
}
void output(const vector <vector <int> > &dp) {
cout << dp.back().back();
}
int main() {
vector <vector <int> > cost, dp;
input(cost, dp);
solution(cost, dp);
output(dp);
return 0;
}
| C++ |
#include <iostream>
#include <cstdio>
#include <vector>
#include <deque>
#include <algorithm>
using std::vector;
using std::cin;
using std::cout;
using std::min;
using std::pair;
using std::reverse;
void input(vector < vector <int> > &lst) {
int n, a, b;
cin >> n;
lst.resize(2 * n);
for (int i = 0; i < 2 * n; i += 2) {
lst[i].push_back(i + 1);
}
cin >> a >> b;
for (int i = 0; i < a; i++) {
int x, y;
cin >> x >> y;
lst[2 * x - 1].push_back(2 * y - 2);
}
for (int i = 0; i < b; i++) {
int x, y;
cin >> x >> y;
lst[2 * x - 2].push_back(2 * y - 1);
lst[2 * y - 2].push_back(2 * x - 1);
}
}
bool dfs(int s, const vector < vector <int> > &lst, vector <char> &used,
vector <int> &topsort) {
bool flag = true;
used[s] = 1;
for (int i = 0; i < lst[s].size(); i++) {
int to = lst[s][i];
if (used[to] == 1) {
return false;
}
if (!used[to]) {
flag &= dfs(to, lst, used, topsort);
}
}
used[s] = 2;
topsort.push_back(s);
return flag;
}
bool solution(const vector < vector <int> > &lst, vector <pair <int, int> > &segments) {
bool flag = true;
vector <int> topsort;
vector <char> used(lst.size(), 0);
for (int i = 0; i < lst.size(); i++) {
if (!used[i]) {
flag &= dfs(i, lst, used, topsort);
}
}
reverse(topsort.begin(), topsort.end());
if (flag) {
segments.resize(lst.size() / 2);
for (int i = 0; i < topsort.size(); i++) {
if(topsort[i] & 1) {
segments[topsort[i] / 2].second = i;
} else {
segments[topsort[i] / 2].first = i;
}
}
}
return flag;
}
void output(bool answer, const vector <pair <int, int> > &segments) {
if(!answer) {
cout << "Impossible";
return;
}
for (int i = 0; i < segments.size(); i++) {
cout << segments[i].first << ' ' << segments[i].second << '\n';
}
}
int main() {
vector <pair <int, int> > segments;
vector < vector <int> > lst;
bool answer;
input(lst);
answer = solution(lst, segments);
output(answer, segments);
return 0;
}
| C++ |
#include <iostream>
#include <cstdio>
#include <vector>
#include <deque>
using std::vector;
using std::cin;
using std::cout;
using std::min;
using std::pair;
using std::deque;
using std::make_pair;
int dx[] = {0, 0, -1, 1};
int dy[] = {1, -1, 0, 0};
void input(vector < vector <int> > &matrix, pair <int, int> &s, pair <int, int> &f) {
int m, n;
cin >> n >> m;
cin >> s.first >> s.second;
cin >> f.first >> f.second;
--s.first, --s.second, --f.first, --f.second;
matrix.resize(n);
for (int i = 0; i < n; i++) {
matrix[i].resize(m);
for (int j = 0; j < m; j++) {
cin >> matrix[i][j];
}
}
}
bool is_vertex(const pair <int, int> &a, int n, int m,
const vector < vector <int> > &matrix, const vector < vector <int> > &dist) {
return a.first >= 0 && a.second >= 0 && a.first < n && a.second < m &&
!matrix[a.first][a.second] && dist[a.first][a.second] == -1;
}
void bfs(const pair <int, int> &s, const vector < vector <int> > &matrix,
vector < vector <int> > &dist) {
int n = matrix.size(), m = matrix[0].size();
deque < pair <int, int> > Deque;
dist[s.first][s.second] = 0;
Deque.push_back(s);
while (!Deque.empty()) {
pair <int, int> k = Deque[0];
Deque.pop_front();
for (int i = 0; i < 4; i++) {
pair <int, int> to = make_pair(k.first + dx[i], k.second + dy[i]);
if(is_vertex(to, n, m, matrix, dist)) {
dist[to.first][to.second] = dist[k.first][k.second] + 1;
Deque.push_back(to);
}
}
}
}
int solution(const vector < vector <int> > &matrix, pair <int, int> &s, pair <int, int> &f) {
vector < vector <int> > dist;
dist.resize(matrix.size());
for (int i = 0; i < dist.size(); i++) {
dist[i].resize(matrix[i].size(), -1);
}
bfs(s, matrix, dist);
return dist[f.first][f.second];
}
void output(int answer) {
if (answer == -1) {
cout << "NO";
} else {
cout << answer;
}
}
int main() {
vector < vector <int> > matrix;
pair <int, int> s, f;
int answer;
input(matrix, s, f);
answer = solution(matrix, s, f);
output(answer);
return 0;
}
| C++ |
#include <iostream>
#include <cstdio>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::min;
struct Point {
int x, y;
Point(int x = 0, int y = 0) : x(x), y(y) {}
int dist(const Point &other) const {
return (x - other.x) * (x - other.x) + (y - other.y) * (y - other.y);
}
};
void input(vector <Point> &lst, int &k) {
int n;
cin >> n >> k;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i].x >> lst[i].y;
}
}
bool is_edge(Point a, Point b, int k) {
return a.dist(b) <= k * k;
}
int dfs(int s, const vector <Point> &lst, vector <bool> &used, int k) {
int cnt = 1;
used[s] = true;
for (int i = 0; i < lst.size(); i++) {
if(!used[i] && is_edge(lst[s], lst[i], k)) {
cnt += dfs(i, lst, used, k);
}
}
return cnt;
}
bool solution(const vector <Point> &lst, int k) {
vector <bool> used;
used.assign(lst.size(), false);
int cnt = dfs(0, lst, used, k);
return cnt == lst.size();
}
bool output(bool answer) {
if(answer) {
cout << "YES";
} else {
cout << "NO";
}
}
int main() {
vector <Point> lst;
int k;
bool answer;
input(lst, k);
answer = solution(lst, k);
output(answer);
return 0;
}
| C++ |
#include <iostream>
#include <cstdio>
#include <vector>
using std::vector;
using std::cin;
using std::cout;
using std::min;
const int MOD = 268435459;
void input(vector <vector <int> > &open, vector <vector <int> > &dp) {
int n, m;
cin >> n >> m;
open.resize(n);
dp.resize(n);
for (int i = 0; i < n; i++) {
dp[i].resize(m);
open[i].resize(m);
for (int j = 0; j < m; j++) {
cin >> open[i][j];
}
}
}
void solution(const vector <vector <int> > &open, vector <vector <int> > &dp) {
dp[0][0] = open[0][0];
for (int i = 1; i < open.size(); i++) {
dp[i][0] = dp[i - 1][0] * open[i][0];
}
for (int i = 1; i < open[0].size(); i++) {
dp[0][i] = dp[0][i - 1] * open[0][i];
}
for (int i = 1; i < open.size(); i++) {
for (int j = 1; j < open[i].size(); j++) {
dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) * open[i][j] % MOD;
}
}
}
void output(const vector <vector <int> > &dp) {
cout << dp.back().back();
}
int main() {
vector <vector <int> > open, dp;
input(open, dp);
solution(open, dp);
output(dp);
return 0;
}
| C++ |
#include <algorithm>
#include <cstdio>
#include <iostream>
#include <vector>
using std::cin;
using std::cout;
using std::vector;
using std::pair;
template <typename InputIterator, typename TKey>
pair <InputIterator, InputIterator> my_partition(InputIterator begin, InputIterator end,
TKey key) {
auto left = begin;
while (begin != end) {
if (*begin < key) {
iter_swap(left, begin);
++left;
}
++begin;
}
auto right = begin = left;
while (begin != end) {
if (*begin == key) {
iter_swap(right, begin);
++right;
}
++begin;
}
return make_pair(left, right);
}
template <typename InputIterator>
void qsort(InputIterator begin, InputIterator end) {
int length = end - begin;
if (length <= 1) {
return;
}
auto pair_middle = my_partition(begin, end, *(begin + rand() % length));
qsort(begin, pair_middle.first);
qsort(pair_middle.second, end);
}
void input(vector <int> &lst) {
int n;
cin >> n;
lst.resize(n);
for (int i = 0; i < n; i++) {
cin >> lst[i];
}
}
void output(const vector <int> &lst) {
for (size_t i = 0; i < lst.size(); i++) {
cout << lst[i] << ' ';
}
}
int main() {
vector <int> lst;
input(lst);
qsort(lst.begin(), lst.end());
output(lst);
return 0;
}
| C++ |
#include <iostream>
#include "Matrix.h"
using namespace std;
int main()
{
cout<<"Main"<<endl;
return 0;
} | C++ |
class Matrix {
int **matrix;
int size;
public:
Matrix();
Matrix(int);
void initialize(int[3][3]);
void set(int,int,int);
int get(int,int);
Matrix* operator + (Matrix&);
Matrix* operator - (Matrix&);
Matrix* operator * (Matrix&);
~Matrix();
}; | C++ |
#include <limits.h>
#include "Matrix.h"
#include "gtest/gtest.h"
TEST(Test1, Add_two_matrices) {
Matrix A(3), B(3), *C;
int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}};
int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}};
int output[3][3] = {{2,10,7},{5,10,9},{5,11,-1}};
A.initialize(input1);
B.initialize(input2);
C = A + B;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
EXPECT_EQ(C->get(i,j), output[i][j]);
}
TEST(Test2, Multiply_two_matrices) {
Matrix A(3), B(3), *C;
int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}};
int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}};
int output[3][3] = {{8,30,16},{13,55,27},{26,81,63}};
A.initialize(input1);
B.initialize(input2);
C = A * B;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
EXPECT_EQ(C->get(i,j), output[i][j]);
}
TEST(Test3, Multiply_and_Add) {
Matrix A(3), B(3), C(3), *D;
int input1[3][3] = {{1,3,2},{2,5,4},{6,7,1}};
int input2[3][3] = {{1,7,5},{3,5,5},{-1,4,-2}};
int input3[3][3] = {{-5,7,1},{9,-9,0},{3,2,-1}};
int output[3][3] = {{3,37,17},{22,46,27},{29,83,62}};
A.initialize(input1);
B.initialize(input2);
C.initialize(input3);
D = *(A * B) + C;
for(int i=0; i<3; i++)
for(int j=0; j<3; j++)
EXPECT_EQ(D->get(i,j), output[i][j]);
}
| C++ |
#include <iostream>
#include "Matrix.h"
using namespace std;
Matrix::Matrix()
{
}
Matrix::Matrix(int n)
{
size = n;
matrix = new int*[size];
for(int i=0; i<size; i++)
matrix[i] = new int[size];
}
void Matrix::initialize(int values[3][3])
{
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
matrix[i][j] = values[i][j];
}
void Matrix::set(int i, int j, int v)
{
matrix[i][j] = v;
}
int Matrix::get(int i, int j)
{
return matrix[i][j];
}
Matrix* Matrix::operator + (Matrix& m)
{
Matrix *result = new Matrix(size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
{
int temp = this->matrix[i][j] + m.get(i,j);
result->set(i,j,temp);
}
return result;
}
Matrix* Matrix::operator - (Matrix& m)
{
Matrix *result = new Matrix(size);
for(int i=0; i<size; i++)
for(int j=0; j<size; j++)
{
int temp = matrix[i][j] - m.get(i,j);
result->set(i,j,temp);
}
return result;
}
Matrix* Matrix::operator * (Matrix& m)
{
Matrix *result = new Matrix(size);
for(int i=0; i<size; i++)
{
for(int j=0; j<size; j++)
{
int temp = 0;
for(int k=0; k<size; k++)
temp += matrix[i][k]*m.get(k,j);
result->set(i,j,temp);
}
}
return result;
}
Matrix::~Matrix()
{
for(int i=0; i<size; i++)
delete [] matrix[i];
delete [] matrix;
} | C++ |
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "com_google_ase_Exec.h"
#include <errno.h>
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include "android/log.h"
#define LOG_TAG "Exec"
#define LOG(...) __android_log_print(ANDROID_LOG_ERROR, LOG_TAG, __VA_ARGS__)
void JNU_ThrowByName(JNIEnv* env, const char* name, const char* msg) {
jclass clazz = env->FindClass(name);
if (clazz != NULL) {
env->ThrowNew(clazz, msg);
}
env->DeleteLocalRef(clazz);
}
char* JNU_GetStringNativeChars(JNIEnv* env, jstring jstr) {
if (jstr == NULL) {
return NULL;
}
jbyteArray bytes = 0;
jthrowable exc;
char* result = 0;
if (env->EnsureLocalCapacity(2) < 0) {
return 0; /* out of memory error */
}
jclass Class_java_lang_String = env->FindClass("java/lang/String");
jmethodID MID_String_getBytes = env->GetMethodID(
Class_java_lang_String, "getBytes", "()[B");
bytes = (jbyteArray) env->CallObjectMethod(jstr, MID_String_getBytes);
exc = env->ExceptionOccurred();
if (!exc) {
jint len = env->GetArrayLength(bytes);
result = (char*) malloc(len + 1);
if (result == 0) {
JNU_ThrowByName(env, "java/lang/OutOfMemoryError", 0);
env->DeleteLocalRef(bytes);
return 0;
}
env->GetByteArrayRegion(bytes, 0, len, (jbyte*) result);
result[len] = 0; /* NULL-terminate */
} else {
env->DeleteLocalRef(exc);
}
env->DeleteLocalRef(bytes);
return result;
}
int jniGetFDFromFileDescriptor(JNIEnv* env, jobject fileDescriptor) {
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
return env->GetIntField(fileDescriptor, descriptor);
}
static int create_subprocess(
const char* cmd, const char* arg0, const char* arg1, int* pProcessId) {
char* devname;
int ptm;
pid_t pid;
ptm = open("/dev/ptmx", O_RDWR); // | O_NOCTTY);
if(ptm < 0){
LOG("[ cannot open /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
fcntl(ptm, F_SETFD, FD_CLOEXEC);
if(grantpt(ptm) || unlockpt(ptm) ||
((devname = (char*) ptsname(ptm)) == 0)){
LOG("[ trouble with /dev/ptmx - %s ]\n", strerror(errno));
return -1;
}
pid = fork();
if(pid < 0) {
LOG("- fork failed: %s -\n", strerror(errno));
return -1;
}
if(pid == 0){
int pts;
setsid();
pts = open(devname, O_RDWR);
if(pts < 0) exit(-1);
dup2(pts, 0);
dup2(pts, 1);
dup2(pts, 2);
close(ptm);
execl(cmd, cmd, arg0, arg1, NULL);
exit(-1);
} else {
*pProcessId = (int) pid;
return ptm;
}
}
JNIEXPORT jobject JNICALL Java_com_google_ase_Exec_createSubprocess(
JNIEnv* env, jclass clazz, jstring cmd, jstring arg0, jstring arg1,
jintArray processIdArray) {
char* cmd_8 = JNU_GetStringNativeChars(env, cmd);
char* arg0_8 = JNU_GetStringNativeChars(env, arg0);
char* arg1_8 = JNU_GetStringNativeChars(env, arg1);
int procId;
int ptm = create_subprocess(cmd_8, arg0_8, arg1_8, &procId);
if (processIdArray) {
int procIdLen = env->GetArrayLength(processIdArray);
if (procIdLen > 0) {
jboolean isCopy;
int* pProcId = (int*) env->GetPrimitiveArrayCritical(processIdArray, &isCopy);
if (pProcId) {
*pProcId = procId;
env->ReleasePrimitiveArrayCritical(processIdArray, pProcId, 0);
}
}
}
jclass Class_java_io_FileDescriptor = env->FindClass("java/io/FileDescriptor");
jmethodID init = env->GetMethodID(Class_java_io_FileDescriptor,
"<init>", "()V");
jobject result = env->NewObject(Class_java_io_FileDescriptor, init);
if (!result) {
LOG("Couldn't create a FileDescriptor.");
} else {
jfieldID descriptor = env->GetFieldID(Class_java_io_FileDescriptor,
"descriptor", "I");
env->SetIntField(result, descriptor, ptm);
}
return result;
}
JNIEXPORT void Java_com_google_ase_Exec_setPtyWindowSize(
JNIEnv* env, jclass clazz, jobject fileDescriptor, jint row, jint col,
jint xpixel, jint ypixel) {
int fd;
struct winsize sz;
fd = jniGetFDFromFileDescriptor(env, fileDescriptor);
if (env->ExceptionOccurred() != NULL) {
return;
}
sz.ws_row = row;
sz.ws_col = col;
sz.ws_xpixel = xpixel;
sz.ws_ypixel = ypixel;
ioctl(fd, TIOCSWINSZ, &sz);
}
JNIEXPORT jint Java_com_google_ase_Exec_waitFor(JNIEnv* env, jclass clazz,
jint procId) {
int status;
waitpid(procId, &status, 0);
int result = 0;
if (WIFEXITED(status)) {
result = WEXITSTATUS(status);
}
return result;
}
| C++ |
#include "LutController.h"
#include "MainWindow.h"
#include <QtDebug>
LutController *LutController::instance = 0;
LutController::LutController()
{
users = new UserList(this);
window = new MainWindow();
}
LutController* LutController::getInstance()
{
if(!instance)
instance = new LutController();
;
return instance;
}
void LutController::startApp()
{
window->initMainWindow();
window->show();
}
bool LutController::getShowTime()
{
return window->getShowTime();
}
int LutController::myId()
{
return window->myId();
}
QString LutController::getNameFromId(int id)
{
return users->getNameById(id);
}
void LutController::sendMsg(QString str)
{
window->sendMsg(str);
}
void LutController::sendPrivateMsg(int to, QString str)
{
window->sendPrivateMsg(to, str);
}
void LutController::onQuitReq()
{
emit quitMe();
}
UserList* LutController::getUsers()
{
return users;
}
| C++ |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork>
#include <QSystemTrayIcon>
#include <QSettings>
#include <QListWidgetItem>
#include "LutController.h"
#include "User.h"
class DiscussPane;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void sendMsg(QString str);
void sendPrivateMsg(int to, QString str);
int myId();
void initMainWindow();
bool getShowTime();
private:
Ui::MainWindow *ui;
QTcpSocket *sock;
QString nickname;
int id;
QSystemTrayIcon *trayIcon;
QIcon *icon;
QIcon *iconWarn;
bool event ( QEvent * event );
DiscussPane *findPaneById(int id);
void majUserList(QStringList list);
void majUser(QString data);
bool notifications;
bool showTime;
QSettings settings;
DiscussPane *mainPane;
QList<DiscussPane*> *privatePanes;
QString serverIP;
int serverPort;
QAction *exitAct;
QMenu *menuTray;
private slots:
void on_actionClear_triggered();
void on_actionShow_time_toggled(bool v);
void on_actionShow_time_triggered();
void on_actionClose_current_tab_triggered();
void on_actionNotifications_toggled(bool v);
void on_actionChange_server_triggered();
void on_actionChange_nickname_triggered();
void onExitAct();
void onTrayClicked(QSystemTrayIcon::ActivationReason r);
void errorReceived(QAbstractSocket::SocketError socketError);
void onConnected();
void dataHandler();
void onItemDoubleClicked(QModelIndex index);
void onTabChanged(int id);
void onToRead(DiscussPane *p);
};
#endif // MAINWINDOW_H
| C++ |
#ifndef USERLIST_H
#define USERLIST_H
#include <QAbstractListModel>
#include "User.h"
class UserList : public QAbstractListModel
{
Q_OBJECT
public:
explicit UserList(QObject *parent = 0);
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole);
bool insertRow(int row, const QModelIndex &parent);
bool removeRow(int row, const QModelIndex &parent);
// usermade :)
void addOrReplace(User *u);
QString getNameById(int id);
void removeRowById(int id);
void clear();
private:
QList<User *> *users;
signals:
public slots:
};
#endif // USERLIST_H
| C++ |
#include "User.h"
User::User(int id, QString name) :
id(id),
name(name)
{
}
User::User(QString data)
{
QStringList infos = data.split(" ");
id = infos.at(0).toInt();
name = infos.at(1);
}
int User::getId()
{
return id;
}
QString User::getName()
{
return name;
}
void User::setId(int val)
{
id = val;
}
void User::setName(QString n)
{
this->name = n;
}
| C++ |
#include <QtGui/QApplication>
#include "LutController.h"
int main(int argc, char *argv[])
{
QApplication *a = new QApplication(argc, argv);
a->setQuitOnLastWindowClosed(false);
LutController *ctrl = LutController::getInstance();
QApplication::connect(ctrl, SIGNAL(quitMe()), a, SLOT(quit()));
ctrl->startApp();
return a->exec();
}
| C++ |
#include "UserList.h"
#include "LutController.h"
UserList::UserList(QObject *parent) :
QAbstractListModel(parent)
{
users = new QList<User*>();
}
QVariant UserList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= users->size())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
return users->at(index.row())->getName();
if (role == Qt::UserRole)
return users->at(index.row())->getId();
if (role == Qt::ForegroundRole)
{
if(LutController::getInstance()->myId() == users->at(index.row())->getId())
return Qt::darkRed;
return Qt::darkBlue;
}
else
return QVariant();
}
int UserList::rowCount(const QModelIndex &) const
{
return users->size();
}
Qt::ItemFlags UserList::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
return QAbstractListModel::flags(index);
}
bool UserList::insertRow(int row, const QModelIndex &parent)
{
beginInsertRows(parent, row, row);
users->insert(row, new User(-1, ""));
endInsertRows();
return true;
}
bool UserList::removeRow(int row, const QModelIndex &parent)
{
beginRemoveRows(parent, row, row);
users->removeAt(row);
endRemoveRows();
return true;
}
bool UserList::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(index.isValid() && role == Qt::EditRole)
{
users->at(index.row())->setName(value.toString());
emit dataChanged(index, index);
return true;
}
else if(index.isValid() && role == Qt::UserRole)
{
users->at(index.row())->setId(value.toInt());
emit dataChanged(index, index);
return true;
}
else return false;
}
void UserList::addOrReplace(User *u)
{
User *existing = 0;
int i = 0;
while(i<users->size() && !existing)
{
if(users->at(i)->getId() == u->getId())
{
existing = users->at(i);
existing->setName(u->getName());
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
i++;
}
if(!existing)
{
insertRow(users->size(), QModelIndex());
setData(index(users->size()-1, 0), u->getId(), Qt::UserRole);
setData(index(users->size()-1, 0), u->getName(), Qt::EditRole);
}
}
void UserList::clear()
{
users->clear();
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
void UserList::removeRowById(int id)
{
int i = 0;
while(i<users->size())
{
if(users->at(i)->getId() == id)
{
users->removeAt(i);
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
i++;
}
}
QString UserList::getNameById(int id)
{
int i = 0;
while(i<users->size())
{
if(users->at(i)->getId() == id)
return users->at(i)->getName();
i++;
}
return "";
}
| C++ |
#include "DiscussPane.h"
#include "ui_DiscussPane.h"
#include "LutController.h"
DiscussPane::DiscussPane(int gid, QWidget *parent) :
QWidget(parent),
ui(new Ui::DiscussPane),
guyId(gid)
{
ui->setupUi(this);
ui->textBrowser->setOpenExternalLinks(true);
connect(ui->lineEdit, SIGNAL(returnPressed()), ui->pushButton, SIGNAL(clicked()));
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(sendMsg()));
}
DiscussPane::~DiscussPane()
{
delete ui;
}
void DiscussPane::displayInfo(QString str)
{
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->insertPlainText(str);
moveToBottom();
}
void DiscussPane::clearPane()
{
ui->textBrowser->clear();
moveToBottom();
}
void DiscussPane::displayError(QString str)
{
ui->textBrowser->setTextColor(Qt::red);
ui->textBrowser->insertPlainText(str);
moveToBottom();
}
void DiscussPane::displayMsg(int from, QString str)
{
moveToBottom();
if(LutController::getInstance()->getShowTime())
{
QTime ct = QTime::currentTime();
ui->textBrowser->setFontWeight(QFont::Normal);
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->insertPlainText("("+ QString((ct.hour()<10) ? "0":"") + QString::number(ct.hour())
+":"+ ((ct.minute()<10) ? "0":"") + QString::number(ct.minute())
+":"+ ((ct.second()<10) ? "0":"") +QString::number(ct.second())+") ");
}
ui->textBrowser->setFontWeight(QFont::Bold);
ui->textBrowser->setTextColor(Qt::darkBlue);
if(from == LutController::getInstance()->myId())
ui->textBrowser->setTextColor(Qt::darkRed);
ui->textBrowser->insertPlainText(LutController::getInstance()->getNameFromId(from) + ": ");
ui->textBrowser->setFontWeight(QFont::Normal);
str.replace(":)", "<img src=\":/img/sourire.gif\" alt='' title=\":)\" />");
str.replace(":(", "<img src=\":/img/triste.gif\" alt='' title=\":(\" />");
str.replace(":D", "<img src=\":/img/D.gif\" alt='' title=\":D\" />");
str.replace(":nerd:", "<img src=\":/img/nerd.gif\" alt='' title=\":nerd:\" />");
str.replace(";)", "<img src=\":/img/clin_oeil.gif\" alt='' title=\";)\" />");
str.replace(":p", "<img src=\":/img/p.gif\" alt='' title=\":p\" />");
str.replace(QRegExp("<(?!(img.*>))"), "<");
str.replace(QRegExp("(https?://[^ ]*)"), "<a href='\\1'>\\1</a> ");
str.replace("%E2%82%AC", QChar(8364));
str.replace("\n", "<br />");
ui->textBrowser->insertHtml(str);
ui->textBrowser->setTextColor(Qt::black);
ui->textBrowser->setFontUnderline(false);
ui->textBrowser->insertPlainText("\n");
moveToBottom();
emit toRead(this);
}
bool DiscussPane::isPrivate()
{
return (guyId >= 0);
}
void DiscussPane::sendMsg()
{
moveToBottom();
if(ui->lineEdit->text().size() > 0)
{
if(!isPrivate())
{
LutController::getInstance()->sendMsg(ui->lineEdit->text());
}
else
{
LutController::getInstance()->sendPrivateMsg(guyId,
ui->lineEdit->text());
}
displayMsg(LutController::getInstance()->myId(), ui->lineEdit->text());
}
ui->lineEdit->clear();
}
int DiscussPane::getGuyId()
{
return guyId;
}
void DiscussPane::setGuyId(int val)
{
guyId = val;
}
void DiscussPane::moveToBottom()
{
ui->textBrowser->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
}
| C++ |
#ifndef USER_H
#define USER_H
#include <QString>
#include <QStringList>
class User // : public QListWidgetItem
{
public:
User(int id, QString name);
User(QString data);
int getId();
QString getName();
void setId(int val);
void setName(QString n);
private:
int id;
QString name;
};
#endif // USER_H
| C++ |
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QInputDialog>
#include <QStringList>
#include <QUrl>
#include "DiscussPane.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
nickname("Anonymous"),
settings("01Lut", "01Lut")
{
setAttribute(Qt::WA_DeleteOnClose, false);
privatePanes = new QList<DiscussPane*>();
mainPane = new DiscussPane(-1, this);
connect(mainPane, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
icon = new QIcon(":/img/icon.png");
iconWarn = new QIcon(":/img/iconW.png");
trayIcon = new QSystemTrayIcon(*icon);
this->setWindowIcon(*icon);
trayIcon->show();
QDir home = QDir::home();
nickname = settings.value("nickname", home.dirName()).toString();
serverIP = settings.value("server", "127.0.0.1").toString();
serverPort = settings.value("port", 1888).toInt();
showTime = settings.value("time", true).toBool();
QString tmp = settings.value("server").toString();
if(tmp.size() < 1)
{
QString ipServer = QInputDialog::getText(this, "server address", "Server address :", QLineEdit::Normal, "127.0.0.1:1888");
QStringList serverInfos = ipServer.split(":");
if(serverInfos.size()>1)
serverPort = serverInfos.at(1).toInt();
settings.setValue("server", serverInfos.at(0));
settings.setValue("port", serverPort);
serverIP = serverInfos.at(0);
}
ui->setupUi(this);
exitAct = new QAction("Quit", this);
exitAct->setShortcut(QKeySequence::Quit);
connect(exitAct, SIGNAL(triggered()), this, SLOT(onExitAct()));
ui->menuTools->addAction(exitAct);
menuTray= new QMenu("01Lut");
menuTray->addAction(exitAct);
trayIcon->setContextMenu(menuTray);
sock = new QTcpSocket(this);
connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorReceived(QAbstractSocket::SocketError)));
connect(sock, SIGNAL(readyRead()), this, SLOT(dataHandler()));
connect(sock, SIGNAL(connected()), this, SLOT(onConnected()));
QString str = "Connecting to server at ";
str += serverIP + " on port " + QString::number(serverPort) + "\n";
mainPane->displayInfo(str);
sock->connectToHost(serverIP, serverPort);
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));
connect(ui->listWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onItemDoubleClicked(QModelIndex)));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onTrayClicked(QSystemTrayIcon::ActivationReason)));
notifications = settings.value("notifications", true).toBool();
ui->actionNotifications->setChecked(notifications);
ui->actionShow_time->setChecked(showTime);
QHBoxLayout *l = static_cast<QHBoxLayout*>(ui->mainTab->layout());
l->insertWidget(0, mainPane, 6);
l->setStretch(1, 1);
onTabChanged(0);
}
bool MainWindow::getShowTime()
{
return showTime;
}
void MainWindow::initMainWindow()
{
ui->listWidget->setModel(LutController::getInstance()->getUsers());
}
void MainWindow::onTabChanged(int id)
{
if(id>0)
{
ui->actionClose_current_tab->setEnabled(true);
}
else
{
ui->actionClose_current_tab->setEnabled(false);
}
ui->tabWidget->setTabIcon(id, QIcon());
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::errorReceived(QAbstractSocket::SocketError socketError)
{
QString str;
if(socketError == QAbstractSocket::ConnectionRefusedError)
{
str = "::Cannot connect to server... Aborting.\n";
}
else
{
str =":: Server error\n";
}
mainPane->displayError(str);
for(int i=0; i<privatePanes->size(); i++)
{
privatePanes->at(i)->displayError(str);
}
this->activateWindow();
}
void MainWindow::sendMsg(QString str)
{
if(str.size() > 0)
{
QByteArray data = "MSG ";
str.replace(QChar(8364), "%E2%82%AC");
data.append(str);
sock->write(data);
}
}
void MainWindow::sendPrivateMsg(int to, QString str)
{
if(str.size() > 0)
{
QByteArray data = "PMSG ";
data.append(QString::number(to)+" ");
str.replace(QChar(8364), "%E2%82%AC");
data.append(str);
sock->write(data);
}
}
void MainWindow::dataHandler()
{
while(sock->bytesAvailable()>0)
{
char c;
QByteArray data;
do {
sock->read(&c, 1);
data.append(c);
} while ( c != EOF );
data.remove(data.size()-1, 1);
if(data.indexOf("MSG ") == 0)
{
QString str(data.remove(0, 4));
QStringList parts = str.split(" ");
int pos = str.indexOf(" ");
str = str.remove(0, pos+1);
// TODO: displaymsg(str)
mainPane->displayMsg(parts.at(0).toInt(), str);
// ----------------------
// ---- Notifications ---
if(!isActiveWindow())
{
trayIcon->setIcon(*iconWarn);
if(notifications)
trayIcon->showMessage("New message from "+LutController::getInstance()->getNameFromId(parts.at(0).toInt()), str);
}
}
else if(data.indexOf("PMSG ") == 0)
{
QString str(data.remove(0, 5));
QStringList parts = str.split(" ");
int pos = str.indexOf(" ");
str = str.remove(0, pos+1);
DiscussPane *pane = findPaneById(parts.at(0).toInt());
if(!pane)
{
int gid = parts.at(0).toInt();
QString gname = LutController::getInstance()->getUsers()->getNameById(gid);
pane = new DiscussPane(gid, this);
privatePanes->append(pane);
ui->tabWidget->addTab(pane, gname);
connect(pane, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
}
pane->displayMsg(parts.at(0).toInt(), str);
// ----------------------
// ---- Notifications ---
if(!isActiveWindow())
{
trayIcon->setIcon(*iconWarn);
if(notifications)
trayIcon->showMessage("New message from "+LutController::getInstance()->getNameFromId(parts.at(0).toInt()), str);
}
}
else if(data.indexOf("NICK ") == 0)
{
QString str(data.remove(0, 5));
int pos = str.indexOf(" ");
int userId = str.left(pos).toInt();
QString info = LutController::getInstance()->getNameFromId(userId)+" is now known as "+ str.mid(pos+1)+"\n";
DiscussPane *pane = findPaneById(userId);
if(pane)
pane->displayInfo(info);
mainPane->displayInfo(info);
sock->write("LIST");
}
else if(data.indexOf("NC ") == 0)
{
QString str(data.remove(0, 3));
mainPane->displayInfo(str + " has join.\n");
sock->write("LIST");
}
else if(data.indexOf("LEAVE ") == 0)
{
int idClient = data.remove(0, 6).toInt();
QString info = LutController::getInstance()->getNameFromId(idClient)+" has left.\n";
DiscussPane *pane = findPaneById(idClient);
if(pane)
{
pane->displayInfo(info);
pane->setGuyId(0);
}
mainPane->displayInfo(info);
LutController::getInstance()->getUsers()->removeRowById(idClient);
sock->write("LIST");
}
else if(data.indexOf("YID ") == 0)
{
id = data.remove(0, 4).toInt();
}
else if(data.indexOf("LIST ") == 0)
{
QString str = data.remove(0, 5);
QStringList users = str.split(" ; ");
majUserList(users);
}
}
}
DiscussPane* MainWindow::findPaneById(int id)
{
for(int i=0; i<privatePanes->size(); i++)
{
if(privatePanes->at(i)->getGuyId() == id)
return privatePanes->at(i);
}
return 0;
}
void MainWindow::on_actionChange_nickname_triggered()
{
QString n = QInputDialog::getText(this, "Nickname", "Choose a nickname", QLineEdit::Normal, nickname);
if(n.size()>0)
{
QByteArray data = "NICK ";
data.append(n);
sock->write(data);
nickname = n;
settings.setValue("nickname", nickname);
}
}
void MainWindow::onConnected()
{
QString str = "Connected\n";
mainPane->displayInfo(str);
for(int i=0; i<privatePanes->size(); i++)
{
privatePanes->at(i)->displayInfo(str);
}
QByteArray data = "NICK ";
data.append(nickname);
sock->write(data);
}
bool MainWindow::event ( QEvent *event )
{
if(event->type() == QEvent::WindowActivate)
trayIcon->setIcon(*icon);
return QMainWindow::event(event);
}
void MainWindow::onItemDoubleClicked(QModelIndex index)
{
int gid = LutController::getInstance()->getUsers()->data(index,Qt::UserRole).toInt();
QString gname = LutController::getInstance()->getUsers()->data(index,Qt::DisplayRole).toString();
DiscussPane *p = findPaneById( gid );
if( !p )
{
p = new DiscussPane(gid, this);
privatePanes->append(p);
int i = ui->tabWidget->addTab(p, gname);
ui->tabWidget->setCurrentIndex(i);
connect(p, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
}
else
{
int panePos = ui->tabWidget->indexOf(p);
ui->tabWidget->setCurrentIndex(panePos);
}
}
void MainWindow::onToRead(DiscussPane *p)
{
int i = ui->tabWidget->indexOf(p);
i = i<0?0:i;
if(i != ui->tabWidget->currentIndex())
{
ui->tabWidget->setTabIcon(i, QIcon(":/img/warn.png"));
}
}
void MainWindow::onTrayClicked(QSystemTrayIcon::ActivationReason r)
{
if(r == QSystemTrayIcon::Trigger)
{
if(isVisible())
close();
else
show();
}
}
void MainWindow::on_actionChange_server_triggered()
{
serverPort = 1888;
QString ipServer = QInputDialog::getText(this, "server address", "Server address :", QLineEdit::Normal, serverIP+":"+QString::number(serverPort));
QStringList serverInfos = ipServer.split(":");
if(ipServer.size()>0)
{
if(serverInfos.size()>1)
serverPort = serverInfos.at(1).toInt();
serverIP = serverInfos.at(0);
settings.setValue("server", serverIP);
settings.setValue("port", serverPort);
sock->disconnectFromHost();
sock->connectToHost(serverIP, serverPort);
QString str = "Connecting to server at ";
str += serverIP + " on port " + QString::number(serverPort) + "\n";
mainPane->displayInfo(str);
privatePanes->clear();
for(int i=1; i<ui->tabWidget->count(); i++)
{
ui->tabWidget->removeTab(i);
}
LutController::getInstance()->getUsers()->clear();
}
}
int MainWindow::myId()
{
return id;
}
void MainWindow::majUserList(QStringList list)
{
for (int i=0; i<list.size(); i++)
if(list.at(i) != "")
majUser(list.at(i));
}
void MainWindow::majUser(QString data)
{
QStringList infos = data.split(" ");
int uid = infos.at(0).toInt();
LutController::getInstance()->getUsers()->addOrReplace(new User(data));
DiscussPane *pane = findPaneById(uid);
if(pane)
{
int idpane = ui->tabWidget->indexOf(pane);
ui->tabWidget->setTabText(idpane, LutController::getInstance()->getNameFromId(uid));
}
}
void MainWindow::on_actionNotifications_toggled(bool v)
{
notifications = v;
settings.setValue("notifications", v);
}
void MainWindow::on_actionClose_current_tab_triggered()
{
DiscussPane *p = static_cast<DiscussPane*>(ui->tabWidget->currentWidget());
privatePanes->removeOne(p);
ui->tabWidget->removeTab(ui->tabWidget->currentIndex());
}
void MainWindow::onExitAct()
{
LutController::getInstance()->onQuitReq();
}
void MainWindow::on_actionShow_time_triggered()
{
}
void MainWindow::on_actionShow_time_toggled(bool v)
{
showTime = v;
settings.setValue("time", v);
}
void MainWindow::on_actionClear_triggered()
{
DiscussPane *p;
p = ui->tabWidget->currentIndex() > 0 ? static_cast<DiscussPane*>(ui->tabWidget->currentWidget()) : mainPane;
p->clearPane();
}
| C++ |
#ifndef LUTCONTROLLER_H
#define LUTCONTROLLER_H
#include <QObject>
#include "UserList.h"
class MainWindow;
class LutController : public QObject
{
Q_OBJECT
public:
static LutController* getInstance();
int myId();
QString getNameFromId(int id);
void sendMsg(QString str);
void sendPrivateMsg(int to, QString str);
bool getShowTime();
UserList* getUsers();
void startApp();
private:
explicit LutController();
MainWindow *window;
UserList *users;
static LutController *instance;
signals:
void quitMe();
public slots:
void onQuitReq();
};
//extern static LutController *LutController::instance;
#endif // LUTCONTROLLER_H
| C++ |
#ifndef PRIVATEPANE_H
#define PRIVATEPANE_H
#include <QWidget>
#include "User.h"
#include "MainWindow.h"
namespace Ui {
class DiscussPane;
}
class DiscussPane : public QWidget
{
Q_OBJECT
signals:
void toRead(DiscussPane*);
public:
explicit DiscussPane(int gid = -1, QWidget *parent = 0);
~DiscussPane();
void displayInfo(QString str);
void displayError(QString str);
void displayMsg(int from, QString str);
void moveToBottom();
bool isPrivate();
int getGuyId();
void setGuyId(int val);
void clearPane();
private:
Ui::DiscussPane *ui;
int guyId;
private slots:
void sendMsg();
};
#endif // PRIVATEPANE_H
| C++ |
#include "log.hpp"
Log::Log(FString path)
{
if((file = open(path.data(), O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR))<0)
{
cout << "Cannot open log file" << endl;
}
}
Log::~Log()
{
close(file);
}
void Log::logger(FString data)
{
FString str = dateLog();
str.erase(str.size()-1, 1);
str += "\t";
str += data;
str += " \n";
write(file, str.data(), str.size());
}
FString Log::dateLog()
{
time_t t = time(NULL);
char *dateLogs = asctime(localtime(&t));
return FString(dateLogs);
}
| C++ |
#include <iostream>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <time.h>
#include "prompt.hpp"
#include "log.hpp"
#include "fstring.hpp"
#include "user.hpp"
#define BUFFSIZE 100000
#define CMAX 990
using namespace std;
/*
* Cette classe représente le serveur
*
* Elle hérite de prompt comme vous pouvez le voir
*/
class Server : public Prompt
{
public:
Server(int port = 1888, FString logDir = "/var/log/01lut/");
~Server();
void start();
void stop();
private:
char buff[BUFFSIZE];
bool activate;
Log *logMsg;
Log *logSvr;
int lport;
int sockServer;
sockaddr_in serverAddress;
int highestSock;
fd_set socksToListen;
// int clients[CMAX];
User* clients[CMAX];
int nbClients;
void initList();
void runLoop();
void readSocks();
void forwardFrom(int from, FString str);
void forward(FString str);
void handleRequest(User *cli, char *request);
void sendMsg(User *cli, FString msg);
int checkSocket(int id);
User* findClient(int id);
void alertClients();
};
| C++ |
#include "user.hpp"
User::User(int sock)
{
this->sock = sock;
name = "Anonymous";
registered = false;
}
User::~User()
{
}
int User::getSock()
{
return sock;
}
FString User::getName()
{
return this->name;
}
void User::setName(FString str)
{
this->name = str;
}
void User::registerMe()
{
registered = true;
}
bool User::isRegistered()
{
return registered;
}
| C++ |
#include "prompt.hpp"
/**
Constructeur de Prompt
*/
Prompt::Prompt() :
welcome(true)
{
}
/**
Destructeur de l'objet
*/
Prompt::~Prompt()
{
}
/**
Les méthodes qui suivent doivent être redéfinies dans
les classes dérivées. Ici est simplement définit un
comportement par défaut pour chacune d'entre elles,
comportement qui sera redéfinit dans les classes dérivées.
*/
/**
Cette méthode associe chaque commande à une fonction
*/
void Prompt::processCmd(char *cmd)
{
if(strcmp(cmd, "quit") == 0)
{
stop();
}
else
{
cout << "Erreur: Commande inconnue : " << cmd << endl;
}
}
/**
Affichage du prompt, indiquant à l'utilisateur
qu'il a la main pour entrer des commandes sur
l'entrée standard
*/
void Prompt::showPrompt()
{
if(welcome)
cout << "(type quit to quit)" << endl;
cout << "> ";
cout.flush();
welcome = false;
}
| C++ |
#ifndef USER_H
#define USER_H
#include "fstring.hpp"
class User
{
public:
User(int sock);
~User();
FString getName();
int getSock();
void setName(FString str);
bool isRegistered();
void registerMe();
private:
FString name;
int sock;
bool registered;
};
#endif
| C++ |
#include "person.hpp"
Person::Person(int _sock)
{
sock = _sock;
name = "Sans nom";
}
Person::~Person()
{
}
Person::setName(FString n)
{
name = n;
}
| C++ |
#ifndef FRONTEND_H
#define FRONTEND_H
/*
Cette classe fournit une interface à un backend client (voire serveur)
*/
#include "fstring.hpp"
class Frontend
{
public:
Frontend(){};
virtual void updateBids() = 0;
virtual void serverReady() = 0;
};
#endif
| C++ |
#include "fstring.hpp"
// TEST
class Person
{
public:
Person(int _sock);
~Person();
void setName(FString n);
private:
FString name;
int sock;
}
| C++ |
#include "server.hpp"
#include "fstring.hpp"
#include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int port = 1888;
FString logDir = "/var/log/";
char c;
FString str;
while( (c = getopt(argc, argv, "p:d:")) != EOF )
{
switch(c)
{
case 'p':
str = optarg;
port = str.toInt();
break;
case 'd':
logDir = optarg;
break;
}
}
Server s(port, logDir);
s.start();
return 0;
}
| C++ |
#ifndef LOG_H
#define LOG_H
#include <iostream>
#include "fstring.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
class Log
{
public:
Log(FString path);
~Log();
void logger(FString data);
private:
int file;
FString dateLog();
};
#endif
| C++ |
#include "fstring.hpp"
#include <sstream>
/**
Constructeur de la classe
Permet de créer un objet
de type FString
*/
FString::FString() :
std::string()
{
}
/**
Constructeur de la classe
Permet de créer un objet
de type FString à partir d'une
chaine de caractere
*/
FString::FString(const char *s) :
std::string(s)
{
}
/**
Methode qui permet de couper une
chaine de caractere dans un
tableau dynamique en deux parties
Le separateur de type caractere
est la partie referente pour le decoupage
Cette methode retourne un vector contenant
les différentes partie de la chaine coupée
*/
std::vector<FString> FString::split(char separator)
{
std::vector<FString> parts;
unsigned int i = 0;
parts.push_back(FString());
while(i < size())
{
if(data()[i] == separator)
{
parts.push_back(FString());
}
else
{
parts.back().push_back(data()[i]);
}
i++;
}
return parts;
}
/**
Cette methode permet d'isoler la
premiere partie d'un message
qui contient la commande à executer
*/
FString FString::getCmd()
{
return split(' ').at(0);
}
/**
Cette methode permet de recuperer
les arguments d'une requête
*/
FString FString::getArgs()
{
FString args(data());
while(args.size() && args.data()[0] != ' ')
{
args.erase(0, 1);
}
if(args.data()[0] == ' ')
args.erase(0, 1); // efface espace
return args;
}
/**
[static]
Cette methode permet de changer un entier
en une chaine de caractère
*/
FString FString::fromInt(int i)
{
std::stringstream ss;
ss << i;
FString str;
ss >> str;
return str;
}
/**
[static]
Cette methode permet de changer un float
en une chaine de caractère
*/
FString FString::fromFloat(float i)
{
std::stringstream ss;
ss << i;
FString str;
ss >> str;
return str;
}
/**
Retourne la valeur entière représentée
par la chaîne
*/
int FString::toInt()
{
std::stringstream ss(this->data());
int ret;
ss >> ret;
return ret;
}
void FString::removeChar(char c)
{
for(unsigned int i=0; i<size(); i++)
{
if(data()[i] == c)
{
erase(1,i);
i--;
}
}
}
| C++ |
#ifndef FSTRING_HPP
#define FSTRING_HPP
/**
01/12/2009
--
Cette classe représente une std::string sur
laquelle une méthode split() peut être appelée
-> Créée pour simplifier l'interprétations des
requêtes
Ne pas hésiter à rajouter des méthodes qui
simplifient l'usage des chaînes de caractères
*/
#include <string>
#include <vector>
class FString : public std::string
{
public:
FString();
FString(const char *s);
std::vector<FString> split(char separator);
FString getCmd();
FString getArgs();
int toInt();
static FString fromInt(int i);
static FString fromFloat(float i);
void removeChar(char c);
};
#endif
| C++ |
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include "log.hpp"
#include "fstring.hpp"
#include "prompt.hpp"
#define BUFFSIZE 512
using namespace std;
/*
* Cette classe représente un client
*
* Elle aussi hérite de prompt :) :)
*/
class Client : public Prompt
{
public:
Client(const char* adresse);
~Client();
void start();
void stop();
void update();
bool isConnected();
private:
bool activate;
char buff[512];
int dport;
int socketDesc;
fd_set toListen;
char* addressServer;
sockaddr_in serverAddress;
hostent *hostInfo;
bool connected;
void runLoop();
void stdinHandler();
void dataHandler();
FString sendAndWait(FString request);
};
| C++ |
#include "client.hpp"
/**
Permet de lancer un client en mode Shell
**/
int main(int argc, char **argv)
{
FString adresse = "";
if(argc > 1)
adresse += argv[1];
if(adresse.compare("") == 0)
{
adresse = "127.0.0.1";
}
Client c(adresse.data());
c.start();
return 0;
}
| C++ |
#include <cstdio>
#include "server.hpp"
/**
Constructeur d'un objet Serveur
*/
Server::Server(int port, FString logDir)
{
nbClients = 0;
lport = port;
activate = false;
for(int i=0; i<CMAX; i++)
clients[i] = 0;
// set the address structure
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(lport);
FString logFile = logDir;
logFile += "/msg.log";
FString logFile2 = logDir;
logFile2 += "/server.log";
logMsg = new Log(logFile);
logSvr = new Log(logFile2);
}
/**
Destructeur de l'objet Serveur
*/
Server::~Server()
{
}
/**
Methode permettant de demarrer le serveur
*/
void Server::start()
{
activate = true;
// Creation du socket server
// sockServer = socket(AF_INET, SOCK_STREAM, 0);
sockServer = socket(AF_INET, SOCK_STREAM, 0);
int somerandomint = 1;
setsockopt(sockServer, SOL_SOCKET, SO_REUSEADDR, &somerandomint, sizeof(int));
if(sockServer > 0)
{
// bind du socket
int bResult = bind(sockServer,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress));
if(bResult < 0)
{
cout << "\t\t\tFail !" << endl;
cout << "Connexion error" << endl;
close(sockServer);
}
else
{
listen(sockServer, CMAX);
cout << "Starting server..." << endl;
cout << ":: Server is listening on port " << lport << endl;
FString log = "Server started on port ";
log += FString::fromInt(lport);
logSvr->logger(log);
highestSock = sockServer;
runLoop();
}
}
else
{
cout << "\t\t\tFail !" << endl;
cout << "can't create socket" << endl;
}
}
/**
Methode permettant d'arreter proprement le serveur
*/
void Server::stop()
{
activate = false;
cout << "Stopping server...\t\t\tOK" << endl;
FString log = "Server stopped";
logSvr->logger(log);
}
/**
Crée la liste des descripteurs à écouter
*/
void Server::initList()
{
/* on commence par ajouter l'entrée standard */
FD_ZERO(&socksToListen);
FD_SET(sockServer, &socksToListen);
FD_SET(0, &socksToListen);
/* puis on ajoute chaque socket de client */
for(int i=0; i<CMAX; i++)
{
if(clients[i] != 0)
{
FD_SET(clients[i]->getSock(), &socksToListen);
if(clients[i]->getSock() > highestSock)
highestSock = clients[i]->getSock();
}
}
}
/**
Lis les différents descripteurs de fichiers
afin d'y récuprérer les informations présentes
*/
void Server::readSocks()
{
/* tentative de connexion */
if(FD_ISSET(sockServer, &socksToListen))
{
cout << "\n::Un nouveau client essaye de se connecter...";
int connect = accept(sockServer, NULL, NULL);
if(connect < 0)
{
cout << "\t\tEchoue!" << endl;
}
else
{
for(int i=0; i<CMAX; i++)
{
if(clients[i] == 0)
{
clients[i] = new User(connect);
nbClients++;
FString str("YID ");
str += FString::fromInt(connect);
sendMsg(clients[i], str);
cout << "\t\tOK" << endl;
cout << " -> assigne a " << i << endl;
FString log = "New client connected on slot";
log += FString::fromInt(i);
logSvr->logger(log);
showPrompt();
return;
}
}
/* si on arrive ici, c'est qu'il n'y a plus de place */
close(connect);
cout << "\t\t\tEchoue!" << endl;
}
}
/* evenements sur stdin */
if(FD_ISSET(0, &socksToListen))
{
if(read(0, buff, BUFFSIZE))
{
// on enlève le '\n' à la fin
for(int i=0; i<BUFFSIZE; i++)
{
if(buff[i] == '\n')
{
buff[i] = '\0';
i = BUFFSIZE; // Bourrin : pour sortir :)
}
}
if(strcmp("",buff) != 0)
{
processCmd(buff);
}
}
}
/* autres evenements */
for(int i=0; i<CMAX; i++)
{
if(clients[i] && FD_ISSET(clients[i]->getSock(), &socksToListen))
{
int rec_res = recv(clients[i]->getSock(), buff, BUFFSIZE, 0);
/* un client se deconnecte */
if(rec_res == 0)
{
FString log = "Client ";
log += clients[i]->getName();
log += " has left";
logSvr->logger(log);
cout << "\n::Client n°" << i << " a quitte" << endl;
FString str("LEAVE ");
str += FString::fromInt(clients[i]->getSock());
close(clients[i]->getSock());
delete clients[i];
clients[i] = 0;
// avoid hole in tab
for(int k=i; k<nbClients; k++)
clients[k] = clients[k+1];
nbClients--;
forward(str);
}
else if(rec_res > 0)
{
cout << "\n::Reçu: " << buff << endl;
cout << " du client n°" << i << endl;
FString log = "From slot";
log += FString::fromInt(i)+": "+buff;
logSvr->logger(log);
handleRequest(clients[i], buff);
}
}
}
showPrompt();
}
/**
Methode permettant d'envoyer un message à tous les clients inscrits
sauf à celui qui a envoyé le message
*/
void Server::forwardFrom(int from, FString str)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i] && from != clients[i]->getSock())
sendMsg(clients[i], str);
}
}
/**
Envoyer un message à tous les clients
*/
void Server::forward(FString str)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i])
{
sendMsg(clients[i], str);
}
}
}
void Server::sendMsg(User *cli, FString msg)
{
msg += EOF;
send(cli->getSock(), msg.data(), msg.size(), 0);
}
/**
Methode permettant de traiter une information envoyée par un client
*/
void Server::handleRequest(User *cli, char *request)
{
FString req(request);
FString cmd = req.getCmd();
FString arg = req.getArgs();
/* traitement de la requete INFO */
if(cmd.compare("LIST") == 0)
{
FString str("LIST ");
for(int i=0; i<nbClients; i++)
{
str += FString::fromInt(clients[i]->getSock()) + " ";
str += clients[i]->getName()+" ; ";
}
sendMsg(cli, str);
}
/* traitement de la requete MSG */
else if(cmd.compare("MSG") == 0)
{
FString str;
str += cmd + " " + FString::fromInt(cli->getSock()) + " " + arg;
forwardFrom(cli->getSock(), str);
FString log = "From ";
log += cli->getName() + " : " + arg ;
logMsg->logger(log);
}
/* privates msg */
else if(cmd.compare("PMSG") == 0)
{
FString msg = arg;
int idUser = msg.getCmd().toInt();
cout << "--- " << msg << endl;
idUser = checkSocket(idUser);
if(idUser > 0)
{
FString str("PMSG ");
str += FString::fromInt(cli->getSock())+" "+msg.getArgs();
User *to = findClient(idUser);
if(to)
sendMsg(to, str);
}
}
/* traitement de la requete DETAILS */
else if(cmd.compare("NICK") == 0)
{
FString nick = arg.getCmd();
if(nick.compare("") != 0)
{
cli->setName(nick);
if(cli->isRegistered())
{
FString str("NICK ");
str += FString::fromInt(cli->getSock()) + " " + nick;
forward(str);
}
else
{
FString str("NC ");
str += nick;
forward(str);
cli->registerMe();
}
}
}
}
/**
Boucle d'exécution du serveur
on y écoute les différents sockets
*/
void Server::runLoop()
{
int nbSocksToRead;
struct timeval timeout;
showPrompt();
while(activate)
{
for(int k=0; k<BUFFSIZE; k++) //Initialisation du buffer
buff[k] = '\0';
initList();
timeout.tv_sec = 1;
timeout.tv_usec = 0;
nbSocksToRead = select(highestSock+1, &socksToListen, NULL, NULL, &timeout);
if(nbSocksToRead > 0)
{
readSocks();
}
alertClients();
}
}
/**
Check if a socket is registered in client lists
returns socket descriptor if exists, -1 if it doesn't
*/
int Server::checkSocket(int id)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i]->getSock() == id)
return id;
}
return -1;
}
User* Server::findClient(int id)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i]->getSock() == id)
return clients[i];
}
return 0;
}
/**
Methode qui permet d'alerter les clients que une enchere est terminée
*/
void Server::alertClients()
{
}
| C++ |
#ifndef PROMPT_H
#define PROMPT_H
/**
Freddy Teuma - 28/11/2009
--
Cette classe permet de faire l'interface entre
une commande et une action. Dériver cette classe
et implémenter les méthodes abstraites.
*/
#include <iostream>
#include <string.h>
#include "fstring.hpp"
using namespace std;
class Prompt
{
public:
Prompt();
~Prompt();
virtual void start() = 0;
virtual void stop() = 0;
void showPrompt();
void processCmd(char *cmd);
private:
bool welcome;
};
#endif
| C++ |
#include "client.hpp"
#include <sstream>
/**
Constructeur de la classe
*/
Client::Client(const char* adresse)
{
dport = 1888;
activate = false;
connected = false;
hostInfo = gethostbyname(adresse);
addressServer = (char*)adresse;
if(hostInfo != NULL)
{
serverAddress.sin_family = hostInfo->h_addrtype;
memcpy((char *) &serverAddress.sin_addr.s_addr, hostInfo->h_addr_list[0], hostInfo->h_length);
serverAddress.sin_port = htons(dport);
}
}
/**
Démarre le client :
On se connecte au serveur puis on entre dans la boucle
d'exécution si la connexion a réussi : voir runLopp();
*/
void Client::start()
{
activate = true;
cout << "::Connexion au serveur " << addressServer;
socketDesc = socket(AF_INET, SOCK_STREAM, 0);
if(socketDesc <= 0)
{
cout << "\t\t\tEchoue!" << endl;
}
else
{
if(connect(socketDesc, (sockaddr*) &serverAddress, sizeof(sockaddr)) == -1)
{
cout << "\t\t\tEchoue!" << endl;
}
else
{
cout << "\t\t\tOK" << endl;
/* init the list to listen */
connected = true;
runLoop();
}
}
}
/**
Termine l'exécution
*/
void Client::stop()
{
activate = false;
}
/**
Traitement des données reçues sur le socket
*/
void Client::dataHandler()
{
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
if(FD_ISSET(socketDesc, &toListen))
{
int rec_res = recv(socketDesc, buff, BUFFSIZE, 0);
if(rec_res == 0)
{
close(socketDesc);
cout << "Deconnexion: Le serveur semble ne pas etre lance" << endl;
stop();
}
else if(rec_res > 0)
{
FString req(buff);
FString cmd = req.getCmd();
FString arg = req.getArgs();
if(cmd.compare("UPDATE") == 0)
{
if(arg.compare("ALL") == 0)
{
update();
}
}
else
cout << "Recu: " << buff << endl;
}
}
}
/**
Traitement des données sur l'entrée standard
*/
void Client::stdinHandler()
{
if(FD_ISSET(0, &toListen))
{
int rec_res = read(0, buff, BUFFSIZE);
if(rec_res > 0)
{
// on enlève le '\n' à la fin
for(int i=0; i<BUFFSIZE; i++)
{
if(buff[i] == '\n')
{
buff[i] = '\0';
i = BUFFSIZE;
}
}
if(strcmp("",buff) != 0)
{
processCmd(buff);
}
}
}
}
/**
Methode permettant d'envoyer un message et de se mettre en attente
*/
FString Client::sendAndWait(FString request)
{
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
send(socketDesc, request.data(), request.size(), 0);
cout << "Attente du serveur..." << endl;
recv(socketDesc, buff, BUFFSIZE, 0);
return FString(buff);
}
/**
Boucle d'exécution de l'application Client.
*/
void Client::runLoop()
{
struct timeval timeout;
while(activate)
{
showPrompt();
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
FD_ZERO(&toListen);
FD_SET(socketDesc, &toListen);
FD_SET(0, &toListen);
int descMax = max(0, socketDesc);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
int sel_res = select(descMax+1, &toListen, NULL, NULL, NULL);
if(sel_res > 0)
{
dataHandler();
stdinHandler();
}
}
connected = false;
}
void Client::update()
{
FString str = sendAndWait("DETAILS ALL");
}
/**
Renvoie true si la connexion au serveur est active,
false sinon.
*/
bool Client::isConnected()
{
return connected;
}
/**
Destructeur
*/
Client::~Client()
{
}
| C++ |
#include "log.hpp"
Log::Log(FString path)
{
if((file = open(path.data(), O_WRONLY|O_APPEND|O_CREAT, S_IRUSR|S_IWUSR))<0)
{
cout << "Cannot open log file" << endl;
}
}
Log::~Log()
{
close(file);
}
void Log::logger(FString data)
{
FString str = dateLog();
str.erase(str.size()-1, 1);
str += "\t";
str += data;
str += " \n";
write(file, str.data(), str.size());
}
FString Log::dateLog()
{
time_t t = time(NULL);
char *dateLogs = asctime(localtime(&t));
return FString(dateLogs);
}
| C++ |
#include <iostream>
#include <arpa/inet.h>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/select.h>
#include <sys/types.h>
#include <time.h>
#include "prompt.hpp"
#include "log.hpp"
#include "fstring.hpp"
#include "user.hpp"
#define BUFFSIZE 100000
#define CMAX 990
using namespace std;
/*
* Cette classe représente le serveur
*/
class Server : public Prompt
{
public:
Server(int port = 1888, FString logDir = "/var/log/01lut/");
~Server();
void start();
void stop();
private:
char buff[BUFFSIZE];
bool activate;
Log *logMsg;
Log *logSvr;
int lport;
int sockServer;
sockaddr_in serverAddress;
int highestSock;
fd_set socksToListen;
// int clients[CMAX];
User* clients[CMAX];
int nbClients;
void initList();
void runLoop();
void readSocks();
void forwardFrom(int from, FString str);
void forward(FString str);
void handleRequest(User *cli, char *request);
void sendMsg(User *cli, FString msg);
int checkSocket(int id);
User* findClient(int id);
void alertClients();
};
| C++ |
#include "user.hpp"
User::User(int sock)
{
this->sock = sock;
name = "Anonymous";
registered = false;
}
User::~User()
{
}
int User::getSock()
{
return sock;
}
FString User::getName()
{
return this->name;
}
void User::setName(FString str)
{
this->name = str;
}
void User::registerMe()
{
registered = true;
}
bool User::isRegistered()
{
return registered;
}
| C++ |
#include "prompt.hpp"
/**
Constructeur de Prompt
*/
Prompt::Prompt() :
welcome(true)
{
}
/**
Destructeur de l'objet
*/
Prompt::~Prompt()
{
}
/**
Les méthodes qui suivent doivent être redéfinies dans
les classes dérivées. Ici est simplement définit un
comportement par défaut pour chacune d'entre elles,
comportement qui sera redéfinit dans les classes dérivées.
*/
/**
Cette méthode associe chaque commande à une fonction
*/
void Prompt::processCmd(char *cmd)
{
if(strcmp(cmd, "quit") == 0)
{
stop();
}
else
{
cout << "Erreur: Commande inconnue : " << cmd << endl;
}
}
/**
Affichage du prompt, indiquant à l'utilisateur
qu'il a la main pour entrer des commandes sur
l'entrée standard
*/
void Prompt::showPrompt()
{
if(welcome)
cout << "(type quit to quit)" << endl;
cout << "> ";
cout.flush();
welcome = false;
}
| C++ |
#ifndef USER_H
#define USER_H
#include "fstring.hpp"
class User
{
public:
User(int sock);
~User();
FString getName();
int getSock();
void setName(FString str);
bool isRegistered();
void registerMe();
private:
FString name;
int sock;
bool registered;
};
#endif
| C++ |
#include "person.hpp"
Person::Person(int _sock)
{
sock = _sock;
name = "Sans nom";
}
Person::~Person()
{
}
Person::setName(FString n)
{
name = n;
}
| C++ |
#ifndef FRONTEND_H
#define FRONTEND_H
/*
Cette classe fournit une interface à un backend client (voire serveur)
*/
#include "fstring.hpp"
class Frontend
{
public:
Frontend(){};
virtual void updateBids() = 0;
virtual void serverReady() = 0;
};
#endif
| C++ |
#include "fstring.hpp"
// TEST
class Person
{
public:
Person(int _sock);
~Person();
void setName(FString n);
private:
FString name;
int sock;
}
| C++ |
#include "server.hpp"
#include "fstring.hpp"
#include <unistd.h>
#include <stdio.h>
int main(int argc, char** argv)
{
int port = 1888;
FString logDir = "/var/log/";
char c;
FString str;
while( (c = getopt(argc, argv, "p:d:")) != EOF )
{
switch(c)
{
case 'p':
str = optarg;
port = str.toInt();
break;
case 'd':
logDir = optarg;
break;
}
}
Server s(port, logDir);
s.start();
return 0;
}
| C++ |
#ifndef LOG_H
#define LOG_H
#include <iostream>
#include "fstring.hpp"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;
class Log
{
public:
Log(FString path);
~Log();
void logger(FString data);
private:
int file;
FString dateLog();
};
#endif
| C++ |
#include "fstring.hpp"
#include <sstream>
/**
Constructeur de la classe
Permet de créer un objet
de type FString
*/
FString::FString() :
std::string()
{
}
/**
Constructeur de la classe
Permet de créer un objet
de type FString à partir d'une
chaine de caractere
*/
FString::FString(const char *s) :
std::string(s)
{
}
/**
Methode qui permet de couper une
chaine de caractere dans un
tableau dynamique en deux parties
Le separateur de type caractere
est la partie referente pour le decoupage
Cette methode retourne un vector contenant
les différentes partie de la chaine coupée
*/
std::vector<FString> FString::split(char separator)
{
std::vector<FString> parts;
unsigned int i = 0;
parts.push_back(FString());
while(i < size())
{
if(data()[i] == separator)
{
parts.push_back(FString());
}
else
{
parts.back().push_back(data()[i]);
}
i++;
}
return parts;
}
/**
Cette methode permet d'isoler la
premiere partie d'un message
qui contient la commande à executer
*/
FString FString::getCmd()
{
return split(' ').at(0);
}
/**
Cette methode permet de recuperer
les arguments d'une requête
*/
FString FString::getArgs()
{
FString args(data());
while(args.size() && args.data()[0] != ' ')
{
args.erase(0, 1);
}
if(args.data()[0] == ' ')
args.erase(0, 1); // efface espace
return args;
}
/**
[static]
Cette methode permet de changer un entier
en une chaine de caractère
*/
FString FString::fromInt(int i)
{
std::stringstream ss;
ss << i;
FString str;
ss >> str;
return str;
}
/**
[static]
Cette methode permet de changer un float
en une chaine de caractère
*/
FString FString::fromFloat(float i)
{
std::stringstream ss;
ss << i;
FString str;
ss >> str;
return str;
}
/**
Retourne la valeur entière représentée
par la chaîne
*/
int FString::toInt()
{
std::stringstream ss(this->data());
int ret;
ss >> ret;
return ret;
}
void FString::removeChar(char c)
{
for(unsigned int i=0; i<size(); i++)
{
if(data()[i] == c)
{
erase(1,i);
i--;
}
}
}
| C++ |
#ifndef FSTRING_HPP
#define FSTRING_HPP
/**
01/12/2009
--
Cette classe représente une std::string sur
laquelle une méthode split() peut être appelée
-> Créée pour simplifier l'interprétations des
requêtes
Ne pas hésiter à rajouter des méthodes qui
simplifient l'usage des chaînes de caractères
*/
#include <string>
#include <vector>
class FString : public std::string
{
public:
FString();
FString(const char *s);
std::vector<FString> split(char separator);
FString getCmd();
FString getArgs();
int toInt();
static FString fromInt(int i);
static FString fromFloat(float i);
void removeChar(char c);
};
#endif
| C++ |
#include <iostream>
#include <netdb.h>
#include <netinet/in.h>
#include <unistd.h>
#include "log.hpp"
#include "fstring.hpp"
#include "prompt.hpp"
#define BUFFSIZE 512
using namespace std;
class Client : public Prompt
{
public:
Client(const char* adresse);
~Client();
void start();
void stop();
void update();
bool isConnected();
private:
bool activate;
char buff[512];
int dport;
int socketDesc;
fd_set toListen;
char* addressServer;
sockaddr_in serverAddress;
hostent *hostInfo;
bool connected;
void runLoop();
void stdinHandler();
void dataHandler();
FString sendAndWait(FString request);
};
| C++ |
#include "client.hpp"
/**
Permet de lancer un client en mode Shell
**/
int main(int argc, char **argv)
{
FString adresse = "";
if(argc > 1)
adresse += argv[1];
if(adresse.compare("") == 0)
{
adresse = "127.0.0.1";
}
Client c(adresse.data());
c.start();
return 0;
}
| C++ |
#include <cstdio>
#include "server.hpp"
/**
Constructeur d'un objet Serveur
*/
Server::Server(int port, FString logDir)
{
nbClients = 0;
lport = port;
activate = false;
for(int i=0; i<CMAX; i++)
clients[i] = 0;
// set the address structure
serverAddress.sin_family = AF_INET;
serverAddress.sin_addr.s_addr = htonl(INADDR_ANY);
serverAddress.sin_port = htons(lport);
FString logFile = logDir;
logFile += "/msg.log";
FString logFile2 = logDir;
logFile2 += "/server.log";
logMsg = new Log(logFile);
logSvr = new Log(logFile2);
}
/**
Destructeur de l'objet Serveur
*/
Server::~Server()
{
}
/**
Methode permettant de demarrer le serveur
*/
void Server::start()
{
activate = true;
// Creation du socket server
// sockServer = socket(AF_INET, SOCK_STREAM, 0);
sockServer = socket(AF_INET, SOCK_STREAM, 0);
int somerandomint = 1;
setsockopt(sockServer, SOL_SOCKET, SO_REUSEADDR, &somerandomint, sizeof(int));
if(sockServer > 0)
{
// bind du socket
int bResult = bind(sockServer,
(struct sockaddr *) &serverAddress,
sizeof(serverAddress));
if(bResult < 0)
{
cout << "\t\t\tFail !" << endl;
cout << "Connexion error" << endl;
close(sockServer);
}
else
{
listen(sockServer, CMAX);
cout << "Starting server..." << endl;
cout << ":: Server is listening on port " << lport << endl;
FString log = "Server started on port ";
log += FString::fromInt(lport);
logSvr->logger(log);
highestSock = sockServer;
runLoop();
}
}
else
{
cout << "\t\t\tFail !" << endl;
cout << "can't create socket" << endl;
}
}
/**
Methode permettant d'arreter proprement le serveur
*/
void Server::stop()
{
activate = false;
cout << "Stopping server...\t\t\tOK" << endl;
FString log = "Server stopped";
logSvr->logger(log);
}
/**
Crée la liste des descripteurs à écouter
*/
void Server::initList()
{
/* on commence par ajouter l'entrée standard */
FD_ZERO(&socksToListen);
FD_SET(sockServer, &socksToListen);
FD_SET(0, &socksToListen);
/* puis on ajoute chaque socket de client */
for(int i=0; i<CMAX; i++)
{
if(clients[i] != 0)
{
FD_SET(clients[i]->getSock(), &socksToListen);
if(clients[i]->getSock() > highestSock)
highestSock = clients[i]->getSock();
}
}
}
/**
Lis les différents descripteurs de fichiers
afin d'y récuprérer les informations présentes
*/
void Server::readSocks()
{
/* tentative de connexion */
if(FD_ISSET(sockServer, &socksToListen))
{
cout << "\n::Un nouveau client essaye de se connecter...";
int connect = accept(sockServer, NULL, NULL);
if(connect < 0)
{
cout << "\t\tEchoue!" << endl;
}
else
{
for(int i=0; i<CMAX; i++)
{
if(clients[i] == 0)
{
clients[i] = new User(connect);
nbClients++;
FString str("YID ");
str += FString::fromInt(connect);
sendMsg(clients[i], str);
cout << "\t\tOK" << endl;
cout << " -> assigne a " << i << endl;
FString log = "New client connected on slot";
log += FString::fromInt(i);
logSvr->logger(log);
showPrompt();
return;
}
}
/* si on arrive ici, c'est qu'il n'y a plus de place */
close(connect);
cout << "\t\t\tEchoue!" << endl;
}
}
/* evenements sur stdin */
if(FD_ISSET(0, &socksToListen))
{
if(read(0, buff, BUFFSIZE))
{
// on enlève le '\n' à la fin
for(int i=0; i<BUFFSIZE; i++)
{
if(buff[i] == '\n')
{
buff[i] = '\0';
i = BUFFSIZE; // Bourrin : pour sortir :)
}
}
if(strcmp("",buff) != 0)
{
processCmd(buff);
}
}
}
/* autres evenements */
for(int i=0; i<CMAX; i++)
{
if(clients[i] && FD_ISSET(clients[i]->getSock(), &socksToListen))
{
int rec_res = recv(clients[i]->getSock(), buff, BUFFSIZE, 0);
/* un client se deconnecte */
if(rec_res == 0)
{
FString log = "Client ";
log += clients[i]->getName();
log += " has left";
logSvr->logger(log);
cout << "\n::Client n°" << i << " a quitte" << endl;
FString str("LEAVE ");
str += FString::fromInt(clients[i]->getSock());
close(clients[i]->getSock());
delete clients[i];
clients[i] = 0;
// avoid hole in tab
for(int k=i; k<nbClients; k++)
clients[k] = clients[k+1];
nbClients--;
forward(str);
}
else if(rec_res > 0)
{
cout << "\n::Reçu: " << buff << endl;
cout << " du client n°" << i << endl;
FString log = "From slot";
log += FString::fromInt(i)+": "+buff;
logSvr->logger(log);
handleRequest(clients[i], buff);
}
}
}
showPrompt();
}
/**
Methode permettant d'envoyer un message à tous les clients inscrits
sauf à celui qui a envoyé le message
*/
void Server::forwardFrom(int from, FString str)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i] && from != clients[i]->getSock())
sendMsg(clients[i], str);
}
}
/**
Envoyer un message à tous les clients
*/
void Server::forward(FString str)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i])
{
sendMsg(clients[i], str);
}
}
}
void Server::sendMsg(User *cli, FString msg)
{
msg += EOF;
send(cli->getSock(), msg.data(), msg.size(), 0);
}
/**
Methode permettant de traiter une information envoyée par un client
*/
void Server::handleRequest(User *cli, char *request)
{
FString req(request);
FString cmd = req.getCmd();
FString arg = req.getArgs();
/* traitement de la requete INFO */
if(cmd.compare("LIST") == 0)
{
FString str("LIST ");
for(int i=0; i<nbClients; i++)
{
str += FString::fromInt(clients[i]->getSock()) + " ";
str += clients[i]->getName()+" ; ";
}
sendMsg(cli, str);
}
/* traitement de la requete MSG */
else if(cmd.compare("MSG") == 0)
{
FString str;
str += cmd + " " + FString::fromInt(cli->getSock()) + " " + arg;
forwardFrom(cli->getSock(), str);
FString log = "From ";
log += cli->getName() + " : " + arg ;
logMsg->logger(log);
}
/* privates msg */
else if(cmd.compare("PMSG") == 0)
{
FString msg = arg;
int idUser = msg.getCmd().toInt();
cout << "--- " << msg << endl;
idUser = checkSocket(idUser);
if(idUser > 0)
{
FString str("PMSG ");
str += FString::fromInt(cli->getSock())+" "+msg.getArgs();
User *to = findClient(idUser);
if(to)
sendMsg(to, str);
}
}
/* traitement de la requete DETAILS */
else if(cmd.compare("NICK") == 0)
{
FString nick = arg.getCmd();
if(nick.compare("") != 0)
{
cli->setName(nick);
if(cli->isRegistered())
{
FString str("NICK ");
str += FString::fromInt(cli->getSock()) + " " + nick;
forward(str);
}
else
{
FString str("NC ");
str += nick;
forward(str);
cli->registerMe();
}
}
}
}
/**
Boucle d'exécution du serveur
on y écoute les différents sockets
*/
void Server::runLoop()
{
int nbSocksToRead;
struct timeval timeout;
showPrompt();
while(activate)
{
for(int k=0; k<BUFFSIZE; k++) //Initialisation du buffer
buff[k] = '\0';
initList();
timeout.tv_sec = 1;
timeout.tv_usec = 0;
nbSocksToRead = select(highestSock+1, &socksToListen, NULL, NULL, &timeout);
if(nbSocksToRead > 0)
{
readSocks();
}
alertClients();
}
}
/**
Check if a socket is registered in client lists
returns socket descriptor if exists, -1 if it doesn't
*/
int Server::checkSocket(int id)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i]->getSock() == id)
return id;
}
return -1;
}
User* Server::findClient(int id)
{
for(int i=0; i<nbClients; i++)
{
if(clients[i]->getSock() == id)
return clients[i];
}
return 0;
}
/**
Methode qui permet d'alerter les clients que une enchere est terminée
*/
void Server::alertClients()
{
}
| C++ |
#ifndef PROMPT_H
#define PROMPT_H
/**
Freddy Teuma - 28/11/2009
--
Cette classe permet de faire l'interface entre
une commande et une action. Dériver cette classe
et implémenter les méthodes abstraites.
*/
#include <iostream>
#include <string.h>
#include "fstring.hpp"
using namespace std;
class Prompt
{
public:
Prompt();
~Prompt();
virtual void start() = 0;
virtual void stop() = 0;
void showPrompt();
void processCmd(char *cmd);
private:
bool welcome;
};
#endif
| C++ |
#include "client.hpp"
#include <sstream>
/**
Constructeur de la classe
*/
Client::Client(const char* adresse)
{
dport = 1888;
activate = false;
connected = false;
hostInfo = gethostbyname(adresse);
addressServer = (char*)adresse;
if(hostInfo != NULL)
{
serverAddress.sin_family = hostInfo->h_addrtype;
memcpy((char *) &serverAddress.sin_addr.s_addr, hostInfo->h_addr_list[0], hostInfo->h_length);
serverAddress.sin_port = htons(dport);
}
}
/**
Démarre le client :
On se connecte au serveur puis on entre dans la boucle
d'exécution si la connexion a réussi : voir runLopp();
*/
void Client::start()
{
activate = true;
cout << "::Connexion au serveur " << addressServer;
socketDesc = socket(AF_INET, SOCK_STREAM, 0);
if(socketDesc <= 0)
{
cout << "\t\t\tEchoue!" << endl;
}
else
{
if(connect(socketDesc, (sockaddr*) &serverAddress, sizeof(sockaddr)) == -1)
{
cout << "\t\t\tEchoue!" << endl;
}
else
{
cout << "\t\t\tOK" << endl;
/* init the list to listen */
connected = true;
runLoop();
}
}
}
/**
Termine l'exécution
*/
void Client::stop()
{
activate = false;
}
/**
Traitement des données reçues sur le socket
*/
void Client::dataHandler()
{
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
if(FD_ISSET(socketDesc, &toListen))
{
int rec_res = recv(socketDesc, buff, BUFFSIZE, 0);
if(rec_res == 0)
{
close(socketDesc);
cout << "Deconnexion: Le serveur semble ne pas etre lance" << endl;
stop();
}
else if(rec_res > 0)
{
FString req(buff);
FString cmd = req.getCmd();
FString arg = req.getArgs();
if(cmd.compare("UPDATE") == 0)
{
if(arg.compare("ALL") == 0)
{
update();
}
}
else
cout << "Recu: " << buff << endl;
}
}
}
/**
Traitement des données sur l'entrée standard
*/
void Client::stdinHandler()
{
if(FD_ISSET(0, &toListen))
{
int rec_res = read(0, buff, BUFFSIZE);
if(rec_res > 0)
{
// on enlève le '\n' à la fin
for(int i=0; i<BUFFSIZE; i++)
{
if(buff[i] == '\n')
{
buff[i] = '\0';
i = BUFFSIZE;
}
}
if(strcmp("",buff) != 0)
{
processCmd(buff);
}
}
}
}
/**
Methode permettant d'envoyer un message et de se mettre en attente
*/
FString Client::sendAndWait(FString request)
{
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
send(socketDesc, request.data(), request.size(), 0);
cout << "Attente du serveur..." << endl;
recv(socketDesc, buff, BUFFSIZE, 0);
return FString(buff);
}
/**
Boucle d'exécution de l'application Client.
*/
void Client::runLoop()
{
struct timeval timeout;
while(activate)
{
showPrompt();
for(int k=0; k<BUFFSIZE; k++)
buff[k] = '\0';
FD_ZERO(&toListen);
FD_SET(socketDesc, &toListen);
FD_SET(0, &toListen);
int descMax = max(0, socketDesc);
timeout.tv_sec = 1;
timeout.tv_usec = 0;
int sel_res = select(descMax+1, &toListen, NULL, NULL, NULL);
if(sel_res > 0)
{
dataHandler();
stdinHandler();
}
}
connected = false;
}
void Client::update()
{
FString str = sendAndWait("DETAILS ALL");
}
/**
Renvoie true si la connexion au serveur est active,
false sinon.
*/
bool Client::isConnected()
{
return connected;
}
/**
Destructeur
*/
Client::~Client()
{
}
| C++ |
#include "LutController.h"
#include "MainWindow.h"
#include <QtDebug>
LutController *LutController::instance = 0;
LutController::LutController()
{
users = new UserList(this);
window = new MainWindow();
}
LutController* LutController::getInstance()
{
if(!instance)
instance = new LutController();
;
return instance;
}
void LutController::startApp()
{
window->initMainWindow();
window->show();
}
bool LutController::getShowTime()
{
return window->getShowTime();
}
int LutController::myId()
{
return window->myId();
}
QString LutController::getNameFromId(int id)
{
return users->getNameById(id);
}
void LutController::sendMsg(QString str)
{
window->sendMsg(str);
}
void LutController::sendPrivateMsg(int to, QString str)
{
window->sendPrivateMsg(to, str);
}
void LutController::onQuitReq()
{
emit quitMe();
}
UserList* LutController::getUsers()
{
return users;
}
| C++ |
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork>
#include <QSystemTrayIcon>
#include <QSettings>
#include <QListWidgetItem>
#include "LutController.h"
#include "User.h"
class DiscussPane;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
void sendMsg(QString str);
void sendPrivateMsg(int to, QString str);
int myId();
void initMainWindow();
bool getShowTime();
private:
Ui::MainWindow *ui;
QTcpSocket *sock;
QString nickname;
int id;
QSystemTrayIcon *trayIcon;
QIcon *icon;
QIcon *iconWarn;
bool event ( QEvent * event );
DiscussPane *findPaneById(int id);
void majUserList(QStringList list);
void majUser(QString data);
bool notifications;
bool showTime;
QSettings settings;
DiscussPane *mainPane;
QList<DiscussPane*> *privatePanes;
QString serverIP;
int serverPort;
QAction *exitAct;
QMenu *menuTray;
private slots:
void on_actionClear_triggered();
void on_actionShow_time_toggled(bool v);
void on_actionShow_time_triggered();
void on_actionClose_current_tab_triggered();
void on_actionNotifications_toggled(bool v);
void on_actionChange_server_triggered();
void on_actionChange_nickname_triggered();
void onExitAct();
void onTrayClicked(QSystemTrayIcon::ActivationReason r);
void errorReceived(QAbstractSocket::SocketError socketError);
void onConnected();
void dataHandler();
void onItemDoubleClicked(QModelIndex index);
void onTabChanged(int id);
void onToRead(DiscussPane *p);
};
#endif // MAINWINDOW_H
| C++ |
#ifndef USERLIST_H
#define USERLIST_H
#include <QAbstractListModel>
#include "User.h"
class UserList : public QAbstractListModel
{
Q_OBJECT
public:
explicit UserList(QObject *parent = 0);
QVariant data(const QModelIndex &index, int role) const;
int rowCount(const QModelIndex &parent) const;
Qt::ItemFlags flags(const QModelIndex &index) const;
bool setData(const QModelIndex &index, const QVariant &value,
int role = Qt::EditRole);
bool insertRow(int row, const QModelIndex &parent);
bool removeRow(int row, const QModelIndex &parent);
// usermade :)
void addOrReplace(User *u);
QString getNameById(int id);
void removeRowById(int id);
void clear();
private:
QList<User *> *users;
signals:
public slots:
};
#endif // USERLIST_H
| C++ |
#include "User.h"
User::User(int id, QString name) :
id(id),
name(name)
{
}
User::User(QString data)
{
QStringList infos = data.split(" ");
id = infos.at(0).toInt();
name = infos.at(1);
}
int User::getId()
{
return id;
}
QString User::getName()
{
return name;
}
void User::setId(int val)
{
id = val;
}
void User::setName(QString n)
{
this->name = n;
}
| C++ |
#include <QtGui/QApplication>
#include "LutController.h"
int main(int argc, char *argv[])
{
QApplication *a = new QApplication(argc, argv);
a->setQuitOnLastWindowClosed(false);
LutController *ctrl = LutController::getInstance();
QApplication::connect(ctrl, SIGNAL(quitMe()), a, SLOT(quit()));
ctrl->startApp();
return a->exec();
}
| C++ |
#include "UserList.h"
#include "LutController.h"
UserList::UserList(QObject *parent) :
QAbstractListModel(parent)
{
users = new QList<User*>();
}
QVariant UserList::data(const QModelIndex &index, int role) const
{
if (!index.isValid())
return QVariant();
if (index.row() >= users->size())
return QVariant();
if (role == Qt::DisplayRole || role == Qt::EditRole)
return users->at(index.row())->getName();
if (role == Qt::UserRole)
return users->at(index.row())->getId();
if (role == Qt::ForegroundRole)
{
if(LutController::getInstance()->myId() == users->at(index.row())->getId())
return Qt::darkRed;
return Qt::darkBlue;
}
else
return QVariant();
}
int UserList::rowCount(const QModelIndex &) const
{
return users->size();
}
Qt::ItemFlags UserList::flags(const QModelIndex &index) const
{
if (!index.isValid())
return Qt::ItemIsEnabled;
return QAbstractListModel::flags(index);
}
bool UserList::insertRow(int row, const QModelIndex &parent)
{
beginInsertRows(parent, row, row);
users->insert(row, new User(-1, ""));
endInsertRows();
return true;
}
bool UserList::removeRow(int row, const QModelIndex &parent)
{
beginRemoveRows(parent, row, row);
users->removeAt(row);
endRemoveRows();
return true;
}
bool UserList::setData(const QModelIndex &index, const QVariant &value, int role)
{
if(index.isValid() && role == Qt::EditRole)
{
users->at(index.row())->setName(value.toString());
emit dataChanged(index, index);
return true;
}
else if(index.isValid() && role == Qt::UserRole)
{
users->at(index.row())->setId(value.toInt());
emit dataChanged(index, index);
return true;
}
else return false;
}
void UserList::addOrReplace(User *u)
{
User *existing = 0;
int i = 0;
while(i<users->size() && !existing)
{
if(users->at(i)->getId() == u->getId())
{
existing = users->at(i);
existing->setName(u->getName());
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
i++;
}
if(!existing)
{
insertRow(users->size(), QModelIndex());
setData(index(users->size()-1, 0), u->getId(), Qt::UserRole);
setData(index(users->size()-1, 0), u->getName(), Qt::EditRole);
}
}
void UserList::clear()
{
users->clear();
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
void UserList::removeRowById(int id)
{
int i = 0;
while(i<users->size())
{
if(users->at(i)->getId() == id)
{
users->removeAt(i);
emit dataChanged(index(0, 0), index(users->size()-1, 0));
}
i++;
}
}
QString UserList::getNameById(int id)
{
int i = 0;
while(i<users->size())
{
if(users->at(i)->getId() == id)
return users->at(i)->getName();
i++;
}
return "";
}
| C++ |
#include "DiscussPane.h"
#include "ui_DiscussPane.h"
#include "LutController.h"
DiscussPane::DiscussPane(int gid, QWidget *parent) :
QWidget(parent),
ui(new Ui::DiscussPane),
guyId(gid)
{
ui->setupUi(this);
ui->textBrowser->setOpenExternalLinks(true);
connect(ui->lineEdit, SIGNAL(returnPressed()), ui->pushButton, SIGNAL(clicked()));
connect(ui->pushButton, SIGNAL(clicked()), this, SLOT(sendMsg()));
}
DiscussPane::~DiscussPane()
{
delete ui;
}
void DiscussPane::displayInfo(QString str)
{
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->insertPlainText(str);
moveToBottom();
}
void DiscussPane::clearPane()
{
ui->textBrowser->clear();
moveToBottom();
}
void DiscussPane::displayError(QString str)
{
ui->textBrowser->setTextColor(Qt::red);
ui->textBrowser->insertPlainText(str);
moveToBottom();
}
void DiscussPane::displayMsg(int from, QString str)
{
moveToBottom();
if(LutController::getInstance()->getShowTime())
{
QTime ct = QTime::currentTime();
ui->textBrowser->setFontWeight(QFont::Normal);
ui->textBrowser->setTextColor(Qt::gray);
ui->textBrowser->insertPlainText("("+ QString((ct.hour()<10) ? "0":"") + QString::number(ct.hour())
+":"+ ((ct.minute()<10) ? "0":"") + QString::number(ct.minute())
+":"+ ((ct.second()<10) ? "0":"") +QString::number(ct.second())+") ");
}
ui->textBrowser->setFontWeight(QFont::Bold);
ui->textBrowser->setTextColor(Qt::darkBlue);
if(from == LutController::getInstance()->myId())
ui->textBrowser->setTextColor(Qt::darkRed);
ui->textBrowser->insertPlainText(LutController::getInstance()->getNameFromId(from) + ": ");
ui->textBrowser->setFontWeight(QFont::Normal);
str.replace(":)", "<img src=\":/img/sourire.gif\" alt='' title=\":)\" />");
str.replace(":(", "<img src=\":/img/triste.gif\" alt='' title=\":(\" />");
str.replace(":D", "<img src=\":/img/D.gif\" alt='' title=\":D\" />");
str.replace(":nerd:", "<img src=\":/img/nerd.gif\" alt='' title=\":nerd:\" />");
str.replace(";)", "<img src=\":/img/clin_oeil.gif\" alt='' title=\";)\" />");
str.replace(":p", "<img src=\":/img/p.gif\" alt='' title=\":p\" />");
str.replace(QRegExp("<(?!(img.*>))"), "<");
str.replace(QRegExp("(https?://[^ ]*)"), "<a href='\\1'>\\1</a> ");
str.replace("%E2%82%AC", QChar(8364));
str.replace("\n", "<br />");
ui->textBrowser->insertHtml(str);
ui->textBrowser->setTextColor(Qt::black);
ui->textBrowser->setFontUnderline(false);
ui->textBrowser->insertPlainText("\n");
moveToBottom();
emit toRead(this);
}
bool DiscussPane::isPrivate()
{
return (guyId >= 0);
}
void DiscussPane::sendMsg()
{
moveToBottom();
if(ui->lineEdit->text().size() > 0)
{
if(!isPrivate())
{
LutController::getInstance()->sendMsg(ui->lineEdit->text());
}
else
{
LutController::getInstance()->sendPrivateMsg(guyId,
ui->lineEdit->text());
}
displayMsg(LutController::getInstance()->myId(), ui->lineEdit->text());
}
ui->lineEdit->clear();
}
int DiscussPane::getGuyId()
{
return guyId;
}
void DiscussPane::setGuyId(int val)
{
guyId = val;
}
void DiscussPane::moveToBottom()
{
ui->textBrowser->moveCursor(QTextCursor::End, QTextCursor::MoveAnchor);
}
| C++ |
#ifndef USER_H
#define USER_H
#include <QString>
#include <QStringList>
class User // : public QListWidgetItem
{
public:
User(int id, QString name);
User(QString data);
int getId();
QString getName();
void setId(int val);
void setName(QString n);
private:
int id;
QString name;
};
#endif // USER_H
| C++ |
#include "MainWindow.h"
#include "ui_MainWindow.h"
#include <QInputDialog>
#include <QStringList>
#include <QUrl>
#include "DiscussPane.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow),
nickname("Anonymous"),
settings("01Lut", "01Lut")
{
setAttribute(Qt::WA_DeleteOnClose, false);
privatePanes = new QList<DiscussPane*>();
mainPane = new DiscussPane(-1, this);
connect(mainPane, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
icon = new QIcon(":/img/icon.png");
iconWarn = new QIcon(":/img/iconW.png");
trayIcon = new QSystemTrayIcon(*icon);
this->setWindowIcon(*icon);
trayIcon->show();
QDir home = QDir::home();
nickname = settings.value("nickname", home.dirName()).toString();
serverIP = settings.value("server", "127.0.0.1").toString();
serverPort = settings.value("port", 1888).toInt();
showTime = settings.value("time", true).toBool();
QString tmp = settings.value("server").toString();
if(tmp.size() < 1)
{
QString ipServer = QInputDialog::getText(this, "server address", "Server address :", QLineEdit::Normal, "127.0.0.1:1888");
QStringList serverInfos = ipServer.split(":");
if(serverInfos.size()>1)
serverPort = serverInfos.at(1).toInt();
settings.setValue("server", serverInfos.at(0));
settings.setValue("port", serverPort);
serverIP = serverInfos.at(0);
}
ui->setupUi(this);
exitAct = new QAction("Quit", this);
exitAct->setShortcut(QKeySequence::Quit);
connect(exitAct, SIGNAL(triggered()), this, SLOT(onExitAct()));
ui->menuTools->addAction(exitAct);
menuTray= new QMenu("01Lut");
menuTray->addAction(exitAct);
trayIcon->setContextMenu(menuTray);
sock = new QTcpSocket(this);
connect(sock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(errorReceived(QAbstractSocket::SocketError)));
connect(sock, SIGNAL(readyRead()), this, SLOT(dataHandler()));
connect(sock, SIGNAL(connected()), this, SLOT(onConnected()));
QString str = "Connecting to server at ";
str += serverIP + " on port " + QString::number(serverPort) + "\n";
mainPane->displayInfo(str);
sock->connectToHost(serverIP, serverPort);
connect(ui->tabWidget, SIGNAL(currentChanged(int)), this, SLOT(onTabChanged(int)));
connect(ui->listWidget, SIGNAL(doubleClicked(QModelIndex)), this, SLOT(onItemDoubleClicked(QModelIndex)));
connect(trayIcon, SIGNAL(activated(QSystemTrayIcon::ActivationReason)), this, SLOT(onTrayClicked(QSystemTrayIcon::ActivationReason)));
notifications = settings.value("notifications", true).toBool();
ui->actionNotifications->setChecked(notifications);
ui->actionShow_time->setChecked(showTime);
QHBoxLayout *l = static_cast<QHBoxLayout*>(ui->mainTab->layout());
l->insertWidget(0, mainPane, 6);
l->setStretch(1, 1);
onTabChanged(0);
}
bool MainWindow::getShowTime()
{
return showTime;
}
void MainWindow::initMainWindow()
{
ui->listWidget->setModel(LutController::getInstance()->getUsers());
}
void MainWindow::onTabChanged(int id)
{
if(id>0)
{
ui->actionClose_current_tab->setEnabled(true);
}
else
{
ui->actionClose_current_tab->setEnabled(false);
}
ui->tabWidget->setTabIcon(id, QIcon());
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::errorReceived(QAbstractSocket::SocketError socketError)
{
QString str;
if(socketError == QAbstractSocket::ConnectionRefusedError)
{
str = "::Cannot connect to server... Aborting.\n";
}
else
{
str =":: Server error\n";
}
mainPane->displayError(str);
for(int i=0; i<privatePanes->size(); i++)
{
privatePanes->at(i)->displayError(str);
}
this->activateWindow();
}
void MainWindow::sendMsg(QString str)
{
if(str.size() > 0)
{
QByteArray data = "MSG ";
str.replace(QChar(8364), "%E2%82%AC");
data.append(str);
sock->write(data);
}
}
void MainWindow::sendPrivateMsg(int to, QString str)
{
if(str.size() > 0)
{
QByteArray data = "PMSG ";
data.append(QString::number(to)+" ");
str.replace(QChar(8364), "%E2%82%AC");
data.append(str);
sock->write(data);
}
}
void MainWindow::dataHandler()
{
while(sock->bytesAvailable()>0)
{
char c;
QByteArray data;
do {
sock->read(&c, 1);
data.append(c);
} while ( c != EOF );
data.remove(data.size()-1, 1);
if(data.indexOf("MSG ") == 0)
{
QString str(data.remove(0, 4));
QStringList parts = str.split(" ");
int pos = str.indexOf(" ");
str = str.remove(0, pos+1);
// TODO: displaymsg(str)
mainPane->displayMsg(parts.at(0).toInt(), str);
// ----------------------
// ---- Notifications ---
if(!isActiveWindow())
{
trayIcon->setIcon(*iconWarn);
if(notifications)
trayIcon->showMessage("New message from "+LutController::getInstance()->getNameFromId(parts.at(0).toInt()), str);
}
}
else if(data.indexOf("PMSG ") == 0)
{
QString str(data.remove(0, 5));
QStringList parts = str.split(" ");
int pos = str.indexOf(" ");
str = str.remove(0, pos+1);
DiscussPane *pane = findPaneById(parts.at(0).toInt());
if(!pane)
{
int gid = parts.at(0).toInt();
QString gname = LutController::getInstance()->getUsers()->getNameById(gid);
pane = new DiscussPane(gid, this);
privatePanes->append(pane);
ui->tabWidget->addTab(pane, gname);
connect(pane, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
}
pane->displayMsg(parts.at(0).toInt(), str);
// ----------------------
// ---- Notifications ---
if(!isActiveWindow())
{
trayIcon->setIcon(*iconWarn);
if(notifications)
trayIcon->showMessage("New message from "+LutController::getInstance()->getNameFromId(parts.at(0).toInt()), str);
}
}
else if(data.indexOf("NICK ") == 0)
{
QString str(data.remove(0, 5));
int pos = str.indexOf(" ");
int userId = str.left(pos).toInt();
QString info = LutController::getInstance()->getNameFromId(userId)+" is now known as "+ str.mid(pos+1)+"\n";
DiscussPane *pane = findPaneById(userId);
if(pane)
pane->displayInfo(info);
mainPane->displayInfo(info);
sock->write("LIST");
}
else if(data.indexOf("NC ") == 0)
{
QString str(data.remove(0, 3));
mainPane->displayInfo(str + " has join.\n");
sock->write("LIST");
}
else if(data.indexOf("LEAVE ") == 0)
{
int idClient = data.remove(0, 6).toInt();
QString info = LutController::getInstance()->getNameFromId(idClient)+" has left.\n";
DiscussPane *pane = findPaneById(idClient);
if(pane)
{
pane->displayInfo(info);
pane->setGuyId(0);
}
mainPane->displayInfo(info);
LutController::getInstance()->getUsers()->removeRowById(idClient);
sock->write("LIST");
}
else if(data.indexOf("YID ") == 0)
{
id = data.remove(0, 4).toInt();
}
else if(data.indexOf("LIST ") == 0)
{
QString str = data.remove(0, 5);
QStringList users = str.split(" ; ");
majUserList(users);
}
}
}
DiscussPane* MainWindow::findPaneById(int id)
{
for(int i=0; i<privatePanes->size(); i++)
{
if(privatePanes->at(i)->getGuyId() == id)
return privatePanes->at(i);
}
return 0;
}
void MainWindow::on_actionChange_nickname_triggered()
{
QString n = QInputDialog::getText(this, "Nickname", "Choose a nickname", QLineEdit::Normal, nickname);
if(n.size()>0)
{
QByteArray data = "NICK ";
data.append(n);
sock->write(data);
nickname = n;
settings.setValue("nickname", nickname);
}
}
void MainWindow::onConnected()
{
QString str = "Connected\n";
mainPane->displayInfo(str);
for(int i=0; i<privatePanes->size(); i++)
{
privatePanes->at(i)->displayInfo(str);
}
QByteArray data = "NICK ";
data.append(nickname);
sock->write(data);
}
bool MainWindow::event ( QEvent *event )
{
if(event->type() == QEvent::WindowActivate)
trayIcon->setIcon(*icon);
return QMainWindow::event(event);
}
void MainWindow::onItemDoubleClicked(QModelIndex index)
{
int gid = LutController::getInstance()->getUsers()->data(index,Qt::UserRole).toInt();
QString gname = LutController::getInstance()->getUsers()->data(index,Qt::DisplayRole).toString();
DiscussPane *p = findPaneById( gid );
if( !p )
{
p = new DiscussPane(gid, this);
privatePanes->append(p);
int i = ui->tabWidget->addTab(p, gname);
ui->tabWidget->setCurrentIndex(i);
connect(p, SIGNAL(toRead(DiscussPane*)), this, SLOT(onToRead(DiscussPane*)));
}
else
{
int panePos = ui->tabWidget->indexOf(p);
ui->tabWidget->setCurrentIndex(panePos);
}
}
void MainWindow::onToRead(DiscussPane *p)
{
int i = ui->tabWidget->indexOf(p);
i = i<0?0:i;
if(i != ui->tabWidget->currentIndex())
{
ui->tabWidget->setTabIcon(i, QIcon(":/img/warn.png"));
}
}
void MainWindow::onTrayClicked(QSystemTrayIcon::ActivationReason r)
{
if(r == QSystemTrayIcon::Trigger)
{
if(isVisible())
close();
else
show();
}
}
void MainWindow::on_actionChange_server_triggered()
{
serverPort = 1888;
QString ipServer = QInputDialog::getText(this, "server address", "Server address :", QLineEdit::Normal, serverIP+":"+QString::number(serverPort));
QStringList serverInfos = ipServer.split(":");
if(ipServer.size()>0)
{
if(serverInfos.size()>1)
serverPort = serverInfos.at(1).toInt();
serverIP = serverInfos.at(0);
settings.setValue("server", serverIP);
settings.setValue("port", serverPort);
sock->disconnectFromHost();
sock->connectToHost(serverIP, serverPort);
QString str = "Connecting to server at ";
str += serverIP + " on port " + QString::number(serverPort) + "\n";
mainPane->displayInfo(str);
privatePanes->clear();
for(int i=1; i<ui->tabWidget->count(); i++)
{
ui->tabWidget->removeTab(i);
}
LutController::getInstance()->getUsers()->clear();
}
}
int MainWindow::myId()
{
return id;
}
void MainWindow::majUserList(QStringList list)
{
for (int i=0; i<list.size(); i++)
if(list.at(i) != "")
majUser(list.at(i));
}
void MainWindow::majUser(QString data)
{
QStringList infos = data.split(" ");
int uid = infos.at(0).toInt();
LutController::getInstance()->getUsers()->addOrReplace(new User(data));
DiscussPane *pane = findPaneById(uid);
if(pane)
{
int idpane = ui->tabWidget->indexOf(pane);
ui->tabWidget->setTabText(idpane, LutController::getInstance()->getNameFromId(uid));
}
}
void MainWindow::on_actionNotifications_toggled(bool v)
{
notifications = v;
settings.setValue("notifications", v);
}
void MainWindow::on_actionClose_current_tab_triggered()
{
DiscussPane *p = static_cast<DiscussPane*>(ui->tabWidget->currentWidget());
privatePanes->removeOne(p);
ui->tabWidget->removeTab(ui->tabWidget->currentIndex());
}
void MainWindow::onExitAct()
{
LutController::getInstance()->onQuitReq();
}
void MainWindow::on_actionShow_time_triggered()
{
}
void MainWindow::on_actionShow_time_toggled(bool v)
{
showTime = v;
settings.setValue("time", v);
}
void MainWindow::on_actionClear_triggered()
{
DiscussPane *p;
p = ui->tabWidget->currentIndex() > 0 ? static_cast<DiscussPane*>(ui->tabWidget->currentWidget()) : mainPane;
p->clearPane();
}
| C++ |
#ifndef LUTCONTROLLER_H
#define LUTCONTROLLER_H
#include <QObject>
#include "UserList.h"
class MainWindow;
class LutController : public QObject
{
Q_OBJECT
public:
static LutController* getInstance();
int myId();
QString getNameFromId(int id);
void sendMsg(QString str);
void sendPrivateMsg(int to, QString str);
bool getShowTime();
UserList* getUsers();
void startApp();
private:
explicit LutController();
MainWindow *window;
UserList *users;
static LutController *instance;
signals:
void quitMe();
public slots:
void onQuitReq();
};
//extern static LutController *LutController::instance;
#endif // LUTCONTROLLER_H
| C++ |
#ifndef PRIVATEPANE_H
#define PRIVATEPANE_H
#include <QWidget>
#include "User.h"
#include "MainWindow.h"
namespace Ui {
class DiscussPane;
}
class DiscussPane : public QWidget
{
Q_OBJECT
signals:
void toRead(DiscussPane*);
public:
explicit DiscussPane(int gid = -1, QWidget *parent = 0);
~DiscussPane();
void displayInfo(QString str);
void displayError(QString str);
void displayMsg(int from, QString str);
void moveToBottom();
bool isPrivate();
int getGuyId();
void setGuyId(int val);
void clearPane();
private:
Ui::DiscussPane *ui;
int guyId;
private slots:
void sendMsg();
};
#endif // PRIVATEPANE_H
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <QStringList>
#include <QDir>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
}
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> infoList;
#ifdef Q_OS_LINUX
QStringList portNamePrefixes, portNameList;
portNamePrefixes << "ttyS*"; // list normal serial ports first
QDir dir("/dev");
portNameList = dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name);
// remove the values which are not serial ports for e.g. /dev/ttysa
for (int i = 0; i < portNameList.size(); i++) {
bool ok;
QString current = portNameList.at(i);
// remove the ttyS part, and check, if the other part is a number
current.remove(0,4).toInt(&ok, 10);
if (!ok) {
portNameList.removeAt(i);
i--;
}
}
// get the non standard serial ports names
// (USB-serial, bluetooth-serial, 18F PICs, and so on)
// if you know an other name prefix for serial ports please let us know
portNamePrefixes.clear();
portNamePrefixes << "ttyACM*" << "ttyUSB*" << "rfcomm*";
portNameList.append(dir.entryList(portNamePrefixes, (QDir::System | QDir::Files), QDir::Name));
foreach (QString str , portNameList) {
QextPortInfo inf;
inf.physName = "/dev/"+str;
inf.portName = str;
if (str.contains("ttyS")) {
inf.friendName = "Serial port "+str.remove(0, 4);
}
else if (str.contains("ttyUSB")) {
inf.friendName = "USB-serial adapter "+str.remove(0, 6);
}
else if (str.contains("rfcomm")) {
inf.friendName = "Bluetooth-serial adapter "+str.remove(0, 6);
}
inf.enumName = "/dev"; // is there a more helpful name for this?
infoList.append(inf);
}
#else
qCritical("Enumeration for POSIX systems (except Linux) is not implemented yet.");
#endif
return infoList;
}
void QextSerialEnumerator::setUpNotifications( )
{
qCritical("Notifications for *Nix/FreeBSD are not implemented yet");
}
| C++ |
#ifndef _QEXTSERIALPORT_H_
#define _QEXTSERIALPORT_H_
#include "qextserialport_global.h"
/*if all warning messages are turned off, flag portability warnings to be turned off as well*/
#ifdef _TTY_NOWARN_
#define _TTY_NOWARN_PORT_
#endif
/*macros for warning and debug messages*/
#ifdef _TTY_NOWARN_PORT_
#define TTY_PORTABILITY_WARNING(s)
#else
#define TTY_PORTABILITY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_PORT_*/
#ifdef _TTY_NOWARN_
#define TTY_WARNING(s)
#else
#define TTY_WARNING(s) qWarning(s)
#endif /*_TTY_NOWARN_*/
/*line status constants*/
#define LS_CTS 0x01
#define LS_DSR 0x02
#define LS_DCD 0x04
#define LS_RI 0x08
#define LS_RTS 0x10
#define LS_DTR 0x20
#define LS_ST 0x40
#define LS_SR 0x80
/*error constants*/
#define E_NO_ERROR 0
#define E_INVALID_FD 1
#define E_NO_MEMORY 2
#define E_CAUGHT_NON_BLOCKED_SIGNAL 3
#define E_PORT_TIMEOUT 4
#define E_INVALID_DEVICE 5
#define E_BREAK_CONDITION 6
#define E_FRAMING_ERROR 7
#define E_IO_ERROR 8
#define E_BUFFER_OVERRUN 9
#define E_RECEIVE_OVERFLOW 10
#define E_RECEIVE_PARITY_ERROR 11
#define E_TRANSMIT_OVERFLOW 12
#define E_READ_FAILED 13
#define E_WRITE_FAILED 14
#define E_FILE_NOT_FOUND 15
enum BaudRateType
{
BAUD50, //POSIX ONLY
BAUD75, //POSIX ONLY
BAUD110,
BAUD134, //POSIX ONLY
BAUD150, //POSIX ONLY
BAUD200, //POSIX ONLY
BAUD300,
BAUD600,
BAUD1200,
BAUD1800, //POSIX ONLY
BAUD2400,
BAUD4800,
BAUD9600,
BAUD14400, //WINDOWS ONLY
BAUD19200,
BAUD38400,
BAUD56000, //WINDOWS ONLY
BAUD57600,
BAUD76800, //POSIX ONLY
BAUD115200,
BAUD128000, //WINDOWS ONLY
BAUD256000 //WINDOWS ONLY
};
enum DataBitsType
{
DATA_5,
DATA_6,
DATA_7,
DATA_8
};
enum ParityType
{
PAR_NONE,
PAR_ODD,
PAR_EVEN,
PAR_MARK, //WINDOWS ONLY
PAR_SPACE
};
enum StopBitsType
{
STOP_1,
STOP_1_5, //WINDOWS ONLY
STOP_2
};
enum FlowType
{
FLOW_OFF,
FLOW_HARDWARE,
FLOW_XONXOFF
};
/**
* structure to contain port settings
*/
struct PortSettings
{
BaudRateType BaudRate;
DataBitsType DataBits;
ParityType Parity;
StopBitsType StopBits;
FlowType FlowControl;
long Timeout_Millisec;
};
#include <QIODevice>
#include <QMutex>
#ifdef Q_OS_UNIX
#include <stdio.h>
#include <termios.h>
#include <errno.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/ioctl.h>
#include <sys/select.h>
#include <QSocketNotifier>
#elif (defined Q_OS_WIN)
#include <windows.h>
#include <QThread>
#include <QReadWriteLock>
#include <QtCore/private/qwineventnotifier_p.h>
#endif
/*!
Encapsulates a serial port on both POSIX and Windows systems.
\note
Be sure to check the full list of members, as QIODevice provides quite a lot of
functionality for QextSerialPort.
\section Usage
QextSerialPort offers both a polling and event driven API. Event driven is typically easier
to use, since you never have to worry about checking for new data.
\b Example
\code
QextSerialPort* port = new QextSerialPort("COM1", QextSerialPort::EventDriven);
connect(port, SIGNAL(readyRead()), myClass, SLOT(onDataAvailable()));
port->open();
void MyClass::onDataAvailable() {
int avail = port->bytesAvailable();
if( avail > 0 ) {
QByteArray usbdata;
usbdata.resize(avail);
int read = port->read(usbdata.data(), usbdata.size());
if( read > 0 ) {
processNewData(usbdata);
}
}
}
\endcode
\section Compatibility
The user will be notified of errors and possible portability conflicts at run-time
by default - this behavior can be turned off by defining _TTY_NOWARN_
(to turn off all warnings) or _TTY_NOWARN_PORT_ (to turn off portability warnings) in the project.
On Windows NT/2000/XP this class uses Win32 serial port functions by default. The user may
select POSIX behavior under NT, 2000, or XP ONLY by defining Q_OS_UNIX in the project.
No guarantees are made as to the quality of POSIX support under NT/2000 however.
\author Stefan Sander, Michal Policht, Brandon Fosdick, Liam Staskawicz
*/
class QEXTSERIALPORT_EXPORT QextSerialPort: public QIODevice
{
Q_OBJECT
public:
enum QueryMode {
Polling,
EventDriven
};
QextSerialPort(QueryMode mode = EventDriven);
QextSerialPort(const QString & name, QueryMode mode = EventDriven);
QextSerialPort(PortSettings const& s, QueryMode mode = EventDriven);
QextSerialPort(const QString & name, PortSettings const& s, QueryMode mode = EventDriven);
~QextSerialPort();
void setPortName(const QString & name);
QString portName() const;
/**!
* Get query mode.
* \return query mode.
*/
inline QueryMode queryMode() const { return _queryMode; }
/*!
* Set desired serial communication handling style. You may choose from polling
* or event driven approach. This function does nothing when port is open; to
* apply changes port must be reopened.
*
* In event driven approach read() and write() functions are acting
* asynchronously. They return immediately and the operation is performed in
* the background, so they doesn't freeze the calling thread.
* To determine when operation is finished, QextSerialPort runs separate thread
* and monitors serial port events. Whenever the event occurs, adequate signal
* is emitted.
*
* When polling is set, read() and write() are acting synchronously. Signals are
* not working in this mode and some functions may not be available. The advantage
* of polling is that it generates less overhead due to lack of signals emissions
* and it doesn't start separate thread to monitor events.
*
* Generally event driven approach is more capable and friendly, although some
* applications may need as low overhead as possible and then polling comes.
*
* \param mode query mode.
*/
void setQueryMode(QueryMode mode);
void setBaudRate(BaudRateType);
BaudRateType baudRate() const;
void setDataBits(DataBitsType);
DataBitsType dataBits() const;
void setParity(ParityType);
ParityType parity() const;
void setStopBits(StopBitsType);
StopBitsType stopBits() const;
void setFlowControl(FlowType);
FlowType flowControl() const;
void setTimeout(long);
bool open(OpenMode mode);
bool isSequential() const;
void close();
void flush();
qint64 size() const;
qint64 bytesAvailable() const;
QByteArray readAll();
void ungetChar(char c);
ulong lastError() const;
void translateError(ulong error);
void setDtr(bool set=true);
void setRts(bool set=true);
ulong lineStatus();
QString errorString();
#ifdef Q_OS_WIN
virtual bool waitForReadyRead(int msecs); ///< @todo implement.
virtual qint64 bytesToWrite() const;
static QString fullPortNameWin(const QString & name);
#endif
protected:
QMutex* mutex;
QString port;
PortSettings Settings;
ulong lastErr;
QueryMode _queryMode;
// platform specific members
#ifdef Q_OS_UNIX
int fd;
QSocketNotifier *readNotifier;
struct termios Posix_CommConfig;
struct termios old_termios;
struct timeval Posix_Timeout;
struct timeval Posix_Copy_Timeout;
#elif (defined Q_OS_WIN)
HANDLE Win_Handle;
OVERLAPPED overlap;
COMMCONFIG Win_CommConfig;
COMMTIMEOUTS Win_CommTimeouts;
QWinEventNotifier *winEventNotifier;
DWORD eventMask;
QList<OVERLAPPED*> pendingWrites;
QReadWriteLock* bytesToWriteLock;
qint64 _bytesToWrite;
#endif
void construct(); // common construction
void platformSpecificDestruct();
void platformSpecificInit();
qint64 readData(char * data, qint64 maxSize);
qint64 writeData(const char * data, qint64 maxSize);
#ifdef Q_OS_WIN
private slots:
void onWinEvent(HANDLE h);
#endif
private:
Q_DISABLE_COPY(QextSerialPort)
signals:
// /**
// * This signal is emitted whenever port settings are updated.
// * \param valid \p true if settings are valid, \p false otherwise.
// *
// * @todo implement.
// */
// // void validSettings(bool valid);
/*!
* This signal is emitted whenever dsr line has changed its state. You may
* use this signal to check if device is connected.
* \param status \p true when DSR signal is on, \p false otherwise.
*
* \see lineStatus().
*/
void dsrChanged(bool status);
};
#endif
| C++ |
#include <stdio.h>
#include "qextserialport.h"
/*!
Default constructor. Note that the name of the device used by a QextSerialPort constructed with
this constructor will be determined by #defined constants, or lack thereof - the default behavior
is the same as _TTY_LINUX_. Possible naming conventions and their associated constants are:
\verbatim
Constant Used By Naming Convention
---------- ------------- ------------------------
Q_OS_WIN Windows COM1, COM2
_TTY_IRIX_ SGI/IRIX /dev/ttyf1, /dev/ttyf2
_TTY_HPUX_ HP-UX /dev/tty1p0, /dev/tty2p0
_TTY_SUN_ SunOS/Solaris /dev/ttya, /dev/ttyb
_TTY_DIGITAL_ Digital UNIX /dev/tty01, /dev/tty02
_TTY_FREEBSD_ FreeBSD /dev/ttyd0, /dev/ttyd1
_TTY_OPENBSD_ OpenBSD /dev/tty00, /dev/tty01
_TTY_LINUX_ Linux /dev/ttyS0, /dev/ttyS1
<none> Linux /dev/ttyS0, /dev/ttyS1
\endverbatim
This constructor assigns the device name to the name of the first port on the specified system.
See the other constructors if you need to open a different port.
*/
QextSerialPort::QextSerialPort(QextSerialPort::QueryMode mode)
: QIODevice()
{
#ifdef Q_OS_WIN
setPortName("COM1");
#elif defined(_TTY_IRIX_)
setPortName("/dev/ttyf1");
#elif defined(_TTY_HPUX_)
setPortName("/dev/tty1p0");
#elif defined(_TTY_SUN_)
setPortName("/dev/ttya");
#elif defined(_TTY_DIGITAL_)
setPortName("/dev/tty01");
#elif defined(_TTY_FREEBSD_)
setPortName("/dev/ttyd1");
#elif defined(_TTY_OPENBSD_)
setPortName("/dev/tty00");
#else
setPortName("/dev/ttyS0");
#endif
construct();
setQueryMode(mode);
platformSpecificInit();
}
/*!
Constructs a serial port attached to the port specified by name.
name is the name of the device, which is windowsystem-specific,
e.g."COM1" or "/dev/ttyS0".
*/
QextSerialPort::QextSerialPort(const QString & name, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setQueryMode(mode);
setPortName(name);
platformSpecificInit();
}
/*!
Constructs a port with default name and specified settings.
*/
QextSerialPort::QextSerialPort(const PortSettings& settings, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
platformSpecificInit();
}
/*!
Constructs a port with specified name and settings.
*/
QextSerialPort::QextSerialPort(const QString & name, const PortSettings& settings, QextSerialPort::QueryMode mode)
: QIODevice()
{
construct();
setPortName(name);
setBaudRate(settings.BaudRate);
setDataBits(settings.DataBits);
setParity(settings.Parity);
setStopBits(settings.StopBits);
setFlowControl(settings.FlowControl);
setTimeout(settings.Timeout_Millisec);
setQueryMode(mode);
platformSpecificInit();
}
/*!
Common constructor function for setting up default port settings.
(115200 Baud, 8N1, Hardware flow control where supported, otherwise no flow control, and 0 ms timeout).
*/
void QextSerialPort::construct()
{
lastErr = E_NO_ERROR;
Settings.BaudRate=BAUD115200;
Settings.DataBits=DATA_8;
Settings.Parity=PAR_NONE;
Settings.StopBits=STOP_1;
Settings.FlowControl=FLOW_HARDWARE;
Settings.Timeout_Millisec=500;
mutex = new QMutex( QMutex::Recursive );
setOpenMode(QIODevice::NotOpen);
}
void QextSerialPort::setQueryMode(QueryMode mechanism)
{
_queryMode = mechanism;
}
/*!
Sets the name of the device associated with the object, e.g. "COM1", or "/dev/ttyS0".
*/
void QextSerialPort::setPortName(const QString & name)
{
#ifdef Q_OS_WIN
port = fullPortNameWin( name );
#else
port = name;
#endif
}
/*!
Returns the name set by setPortName().
*/
QString QextSerialPort::portName() const
{
return port;
}
/*!
Reads all available data from the device, and returns it as a QByteArray.
This function has no way of reporting errors; returning an empty QByteArray()
can mean either that no data was currently available for reading, or that an error occurred.
*/
QByteArray QextSerialPort::readAll()
{
int avail = this->bytesAvailable();
return (avail > 0) ? this->read(avail) : QByteArray();
}
/*!
Returns the baud rate of the serial port. For a list of possible return values see
the definition of the enum BaudRateType.
*/
BaudRateType QextSerialPort::baudRate(void) const
{
return Settings.BaudRate;
}
/*!
Returns the number of data bits used by the port. For a list of possible values returned by
this function, see the definition of the enum DataBitsType.
*/
DataBitsType QextSerialPort::dataBits() const
{
return Settings.DataBits;
}
/*!
Returns the type of parity used by the port. For a list of possible values returned by
this function, see the definition of the enum ParityType.
*/
ParityType QextSerialPort::parity() const
{
return Settings.Parity;
}
/*!
Returns the number of stop bits used by the port. For a list of possible return values, see
the definition of the enum StopBitsType.
*/
StopBitsType QextSerialPort::stopBits() const
{
return Settings.StopBits;
}
/*!
Returns the type of flow control used by the port. For a list of possible values returned
by this function, see the definition of the enum FlowType.
*/
FlowType QextSerialPort::flowControl() const
{
return Settings.FlowControl;
}
/*!
Returns true if device is sequential, otherwise returns false. Serial port is sequential device
so this function always returns true. Check QIODevice::isSequential() documentation for more
information.
*/
bool QextSerialPort::isSequential() const
{
return true;
}
QString QextSerialPort::errorString()
{
switch(lastErr)
{
case E_NO_ERROR: return "No Error has occurred";
case E_INVALID_FD: return "Invalid file descriptor (port was not opened correctly)";
case E_NO_MEMORY: return "Unable to allocate memory tables (POSIX)";
case E_CAUGHT_NON_BLOCKED_SIGNAL: return "Caught a non-blocked signal (POSIX)";
case E_PORT_TIMEOUT: return "Operation timed out (POSIX)";
case E_INVALID_DEVICE: return "The file opened by the port is not a valid device";
case E_BREAK_CONDITION: return "The port detected a break condition";
case E_FRAMING_ERROR: return "The port detected a framing error (usually caused by incorrect baud rate settings)";
case E_IO_ERROR: return "There was an I/O error while communicating with the port";
case E_BUFFER_OVERRUN: return "Character buffer overrun";
case E_RECEIVE_OVERFLOW: return "Receive buffer overflow";
case E_RECEIVE_PARITY_ERROR: return "The port detected a parity error in the received data";
case E_TRANSMIT_OVERFLOW: return "Transmit buffer overflow";
case E_READ_FAILED: return "General read operation failure";
case E_WRITE_FAILED: return "General write operation failure";
case E_FILE_NOT_FOUND: return "The "+this->portName()+" file doesn't exists";
default: return QString("Unknown error: %1").arg(lastErr);
}
}
/*!
Standard destructor.
*/
QextSerialPort::~QextSerialPort()
{
if (isOpen()) {
close();
}
platformSpecificDestruct();
delete mutex;
}
| C++ |
#include <QMutexLocker>
#include <QDebug>
#include <QRegExp>
#include "qextserialport.h"
void QextSerialPort::platformSpecificInit()
{
Win_Handle=INVALID_HANDLE_VALUE;
ZeroMemory(&overlap, sizeof(OVERLAPPED));
overlap.hEvent = CreateEvent(NULL, true, false, NULL);
winEventNotifier = 0;
bytesToWriteLock = new QReadWriteLock;
_bytesToWrite = 0;
}
/*!
Standard destructor.
*/
void QextSerialPort::platformSpecificDestruct() {
CloseHandle(overlap.hEvent);
delete bytesToWriteLock;
}
QString QextSerialPort::fullPortNameWin(const QString & name)
{
QRegExp rx("^COM(\\d+)");
QString fullName(name);
if(fullName.contains(rx)) {
int portnum = rx.cap(1).toInt();
if(portnum > 9) // COM ports greater than 9 need \\.\ prepended
fullName.prepend("\\\\.\\");
}
return fullName;
}
/*!
Opens a serial port. Note that this function does not specify which device to open. If you need
to open a device by name, see QextSerialPort::open(const char*). This function has no effect
if the port associated with the class is already open. The port is also configured to the current
settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode) {
unsigned long confSize = sizeof(COMMCONFIG);
Win_CommConfig.dwSize = confSize;
DWORD dwFlagsAndAttributes = 0;
if (queryMode() == QextSerialPort::EventDriven)
dwFlagsAndAttributes += FILE_FLAG_OVERLAPPED;
QMutexLocker lock(mutex);
if (mode == QIODevice::NotOpen)
return isOpen();
if (!isOpen()) {
/*open the port*/
Win_Handle=CreateFileA(port.toAscii(), GENERIC_READ|GENERIC_WRITE,
0, NULL, OPEN_EXISTING, dwFlagsAndAttributes, NULL);
if (Win_Handle!=INVALID_HANDLE_VALUE) {
QIODevice::open(mode);
/*configure port settings*/
GetCommConfig(Win_Handle, &Win_CommConfig, &confSize);
GetCommState(Win_Handle, &(Win_CommConfig.dcb));
/*set up parameters*/
Win_CommConfig.dcb.fBinary=TRUE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
Win_CommConfig.dcb.fAbortOnError=FALSE;
Win_CommConfig.dcb.fNull=FALSE;
setBaudRate(Settings.BaudRate);
setDataBits(Settings.DataBits);
setStopBits(Settings.StopBits);
setParity(Settings.Parity);
setFlowControl(Settings.FlowControl);
setTimeout(Settings.Timeout_Millisec);
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
//init event driven approach
if (queryMode() == QextSerialPort::EventDriven) {
Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
Win_CommTimeouts.WriteTotalTimeoutMultiplier = 0;
Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
if (!SetCommMask( Win_Handle, EV_TXEMPTY | EV_RXCHAR | EV_DSR)) {
qWarning() << "failed to set Comm Mask. Error code:", GetLastError();
return false;
}
winEventNotifier = new QWinEventNotifier(overlap.hEvent, this);
connect(winEventNotifier, SIGNAL(activated(HANDLE)), this, SLOT(onWinEvent(HANDLE)));
WaitCommEvent(Win_Handle, &eventMask, &overlap);
}
}
} else {
return false;
}
return isOpen();
}
/*!
Closes a serial port. This function has no effect if the serial port associated with the class
is not currently open.
*/
void QextSerialPort::close()
{
QMutexLocker lock(mutex);
if (isOpen()) {
flush();
QIODevice::close(); // mark ourselves as closed
CancelIo(Win_Handle);
if (CloseHandle(Win_Handle))
Win_Handle = INVALID_HANDLE_VALUE;
if (winEventNotifier)
winEventNotifier->deleteLater();
_bytesToWrite = 0;
foreach(OVERLAPPED* o, pendingWrites) {
CloseHandle(o->hEvent);
delete o;
}
pendingWrites.clear();
}
}
/*!
Flushes all pending I/O to the serial port. This function has no effect if the serial port
associated with the class is not currently open.
*/
void QextSerialPort::flush() {
QMutexLocker lock(mutex);
if (isOpen()) {
FlushFileBuffers(Win_Handle);
}
}
/*!
This function will return the number of bytes waiting in the receive queue of the serial port.
It is included primarily to provide a complete QIODevice interface, and will not record errors
in the lastErr member (because it is const). This function is also not thread-safe - in
multithreading situations, use QextSerialPort::bytesAvailable() instead.
*/
qint64 QextSerialPort::size() const {
int availBytes;
COMSTAT Win_ComStat;
DWORD Win_ErrorMask=0;
ClearCommError(Win_Handle, &Win_ErrorMask, &Win_ComStat);
availBytes = Win_ComStat.cbInQue;
return (qint64)availBytes;
}
/*!
Returns the number of bytes waiting in the port's receive queue. This function will return 0 if
the port is not currently open, or -1 on error.
*/
qint64 QextSerialPort::bytesAvailable() const {
QMutexLocker lock(mutex);
if (isOpen()) {
DWORD Errors;
COMSTAT Status;
if (ClearCommError(Win_Handle, &Errors, &Status)) {
return Status.cbInQue + QIODevice::bytesAvailable();
}
return (qint64)-1;
}
return 0;
}
/*!
Translates a system-specific error code to a QextSerialPort error code. Used internally.
*/
void QextSerialPort::translateError(ulong error) {
if (error&CE_BREAK) {
lastErr=E_BREAK_CONDITION;
}
else if (error&CE_FRAME) {
lastErr=E_FRAMING_ERROR;
}
else if (error&CE_IOE) {
lastErr=E_IO_ERROR;
}
else if (error&CE_MODE) {
lastErr=E_INVALID_FD;
}
else if (error&CE_OVERRUN) {
lastErr=E_BUFFER_OVERRUN;
}
else if (error&CE_RXPARITY) {
lastErr=E_RECEIVE_PARITY_ERROR;
}
else if (error&CE_RXOVER) {
lastErr=E_RECEIVE_OVERFLOW;
}
else if (error&CE_TXFULL) {
lastErr=E_TRANSMIT_OVERFLOW;
}
}
/*!
Reads a block of data from the serial port. This function will read at most maxlen bytes from
the serial port and place them in the buffer pointed to by data. Return value is the number of
bytes actually read, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::readData(char *data, qint64 maxSize)
{
DWORD retVal;
QMutexLocker lock(mutex);
retVal = 0;
if (queryMode() == QextSerialPort::EventDriven) {
OVERLAPPED overlapRead;
ZeroMemory(&overlapRead, sizeof(OVERLAPPED));
if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, & overlapRead)) {
if (GetLastError() == ERROR_IO_PENDING)
GetOverlappedResult(Win_Handle, & overlapRead, & retVal, true);
else {
lastErr = E_READ_FAILED;
retVal = (DWORD)-1;
}
}
} else if (!ReadFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) {
lastErr = E_READ_FAILED;
retVal = (DWORD)-1;
}
return (qint64)retVal;
}
/*!
Writes a block of data to the serial port. This function will write len bytes
from the buffer pointed to by data to the serial port. Return value is the number
of bytes actually written, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::writeData(const char *data, qint64 maxSize)
{
QMutexLocker lock( mutex );
DWORD retVal = 0;
if (queryMode() == QextSerialPort::EventDriven) {
OVERLAPPED* newOverlapWrite = new OVERLAPPED;
ZeroMemory(newOverlapWrite, sizeof(OVERLAPPED));
newOverlapWrite->hEvent = CreateEvent(NULL, true, false, NULL);
if (WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, newOverlapWrite)) {
CloseHandle(newOverlapWrite->hEvent);
delete newOverlapWrite;
}
else if (GetLastError() == ERROR_IO_PENDING) {
// writing asynchronously...not an error
QWriteLocker writelocker(bytesToWriteLock);
_bytesToWrite += maxSize;
pendingWrites.append(newOverlapWrite);
}
else {
qDebug() << "serialport write error:" << GetLastError();
lastErr = E_WRITE_FAILED;
retVal = (DWORD)-1;
if(!CancelIo(newOverlapWrite->hEvent))
qDebug() << "serialport: couldn't cancel IO";
if(!CloseHandle(newOverlapWrite->hEvent))
qDebug() << "serialport: couldn't close OVERLAPPED handle";
delete newOverlapWrite;
}
} else if (!WriteFile(Win_Handle, (void*)data, (DWORD)maxSize, & retVal, NULL)) {
lastErr = E_WRITE_FAILED;
retVal = (DWORD)-1;
}
return (qint64)retVal;
}
/*!
This function is included to implement the full QIODevice interface, and currently has no
purpose within this class. This function is meaningless on an unbuffered device and currently
only prints a warning message to that effect.
*/
void QextSerialPort::ungetChar(char c) {
/*meaningless on unbuffered sequential device - return error and print a warning*/
TTY_WARNING("QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless");
}
/*!
Sets the flow control used by the port. Possible values of flow are:
\verbatim
FLOW_OFF No flow control
FLOW_HARDWARE Hardware (RTS/CTS) flow control
FLOW_XONXOFF Software (XON/XOFF) flow control
\endverbatim
*/
void QextSerialPort::setFlowControl(FlowType flow) {
QMutexLocker lock(mutex);
if (Settings.FlowControl!=flow) {
Settings.FlowControl=flow;
}
if (isOpen()) {
switch(flow) {
/*no flow control*/
case FLOW_OFF:
Win_CommConfig.dcb.fOutxCtsFlow=FALSE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
/*software (XON/XOFF) flow control*/
case FLOW_XONXOFF:
Win_CommConfig.dcb.fOutxCtsFlow=FALSE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_DISABLE;
Win_CommConfig.dcb.fInX=TRUE;
Win_CommConfig.dcb.fOutX=TRUE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
case FLOW_HARDWARE:
Win_CommConfig.dcb.fOutxCtsFlow=TRUE;
Win_CommConfig.dcb.fRtsControl=RTS_CONTROL_HANDSHAKE;
Win_CommConfig.dcb.fInX=FALSE;
Win_CommConfig.dcb.fOutX=FALSE;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
}
}
}
/*!
Sets the parity associated with the serial port. The possible values of parity are:
\verbatim
PAR_SPACE Space Parity
PAR_MARK Mark Parity
PAR_NONE No Parity
PAR_EVEN Even Parity
PAR_ODD Odd Parity
\endverbatim
*/
void QextSerialPort::setParity(ParityType parity) {
QMutexLocker lock(mutex);
if (Settings.Parity!=parity) {
Settings.Parity=parity;
}
if (isOpen()) {
Win_CommConfig.dcb.Parity=(unsigned char)parity;
switch (parity) {
/*space parity*/
case PAR_SPACE:
if (Settings.DataBits==DATA_8) {
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Space parity with 8 data bits is not supported by POSIX systems.");
}
Win_CommConfig.dcb.fParity=TRUE;
break;
/*mark parity - WINDOWS ONLY*/
case PAR_MARK:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Mark parity is not supported by POSIX systems");
Win_CommConfig.dcb.fParity=TRUE;
break;
/*no parity*/
case PAR_NONE:
Win_CommConfig.dcb.fParity=FALSE;
break;
/*even parity*/
case PAR_EVEN:
Win_CommConfig.dcb.fParity=TRUE;
break;
/*odd parity*/
case PAR_ODD:
Win_CommConfig.dcb.fParity=TRUE;
break;
}
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
}
/*!
Sets the number of data bits used by the serial port. Possible values of dataBits are:
\verbatim
DATA_5 5 data bits
DATA_6 6 data bits
DATA_7 7 data bits
DATA_8 8 data bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
5 data bits cannot be used with 2 stop bits.
\par
1.5 stop bits can only be used with 5 data bits.
\par
8 data bits cannot be used with space parity on POSIX systems.
*/
void QextSerialPort::setDataBits(DataBitsType dataBits) {
QMutexLocker lock(mutex);
if (Settings.DataBits!=dataBits) {
if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
(Settings.StopBits==STOP_1_5 && dataBits!=DATA_5)) {
}
else {
Settings.DataBits=dataBits;
}
}
if (isOpen()) {
switch(dataBits) {
/*5 data bits*/
case DATA_5:
if (Settings.StopBits==STOP_2) {
TTY_WARNING("QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=5;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*6 data bits*/
case DATA_6:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=6;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*7 data bits*/
case DATA_7:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=7;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*8 data bits*/
case DATA_8:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
}
else {
Win_CommConfig.dcb.ByteSize=8;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
}
}
}
/*!
Sets the number of stop bits used by the serial port. Possible values of stopBits are:
\verbatim
STOP_1 1 stop bit
STOP_1_5 1.5 stop bits
STOP_2 2 stop bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
2 stop bits cannot be used with 5 data bits.
\par
1.5 stop bits cannot be used with 6 or more data bits.
\par
POSIX does not support 1.5 stop bits.
*/
void QextSerialPort::setStopBits(StopBitsType stopBits) {
QMutexLocker lock(mutex);
if (Settings.StopBits!=stopBits) {
if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) ||
(stopBits==STOP_1_5 && Settings.DataBits!=DATA_5)) {
}
else {
Settings.StopBits=stopBits;
}
}
if (isOpen()) {
switch (stopBits) {
/*one stop bit*/
case STOP_1:
Win_CommConfig.dcb.StopBits=ONESTOPBIT;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
break;
/*1.5 stop bits*/
case STOP_1_5:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: 1.5 stop bit operation is not supported by POSIX.");
if (Settings.DataBits!=DATA_5) {
TTY_WARNING("QextSerialPort: 1.5 stop bits can only be used with 5 data bits");
}
else {
Win_CommConfig.dcb.StopBits=ONE5STOPBITS;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
/*two stop bits*/
case STOP_2:
if (Settings.DataBits==DATA_5) {
TTY_WARNING("QextSerialPort: 2 stop bits cannot be used with 5 data bits");
}
else {
Win_CommConfig.dcb.StopBits=TWOSTOPBITS;
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
break;
}
}
}
/*!
Sets the baud rate of the serial port. Note that not all rates are applicable on
all platforms. The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an *
are speeds that are usable on both Windows and POSIX.
\verbatim
RATE Windows Speed POSIX Speed
----------- ------------- -----------
BAUD50 110 50
BAUD75 110 75
*BAUD110 110 110
BAUD134 110 134.5
BAUD150 110 150
BAUD200 110 200
*BAUD300 300 300
*BAUD600 600 600
*BAUD1200 1200 1200
BAUD1800 1200 1800
*BAUD2400 2400 2400
*BAUD4800 4800 4800
*BAUD9600 9600 9600
BAUD14400 14400 9600
*BAUD19200 19200 19200
*BAUD38400 38400 38400
BAUD56000 56000 38400
*BAUD57600 57600 57600
BAUD76800 57600 76800
*BAUD115200 115200 115200
BAUD128000 128000 115200
BAUD256000 256000 115200
\endverbatim
*/
void QextSerialPort::setBaudRate(BaudRateType baudRate) {
QMutexLocker lock(mutex);
if (Settings.BaudRate!=baudRate) {
switch (baudRate) {
case BAUD50:
case BAUD75:
case BAUD134:
case BAUD150:
case BAUD200:
Settings.BaudRate=BAUD110;
break;
case BAUD1800:
Settings.BaudRate=BAUD1200;
break;
case BAUD76800:
Settings.BaudRate=BAUD57600;
break;
default:
Settings.BaudRate=baudRate;
break;
}
}
if (isOpen()) {
switch (baudRate) {
/*50 baud*/
case BAUD50:
TTY_WARNING("QextSerialPort: Windows does not support 50 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*75 baud*/
case BAUD75:
TTY_WARNING("QextSerialPort: Windows does not support 75 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*110 baud*/
case BAUD110:
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*134.5 baud*/
case BAUD134:
TTY_WARNING("QextSerialPort: Windows does not support 134.5 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*150 baud*/
case BAUD150:
TTY_WARNING("QextSerialPort: Windows does not support 150 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*200 baud*/
case BAUD200:
TTY_WARNING("QextSerialPort: Windows does not support 200 baud operation. Switching to 110 baud.");
Win_CommConfig.dcb.BaudRate=CBR_110;
break;
/*300 baud*/
case BAUD300:
Win_CommConfig.dcb.BaudRate=CBR_300;
break;
/*600 baud*/
case BAUD600:
Win_CommConfig.dcb.BaudRate=CBR_600;
break;
/*1200 baud*/
case BAUD1200:
Win_CommConfig.dcb.BaudRate=CBR_1200;
break;
/*1800 baud*/
case BAUD1800:
TTY_WARNING("QextSerialPort: Windows does not support 1800 baud operation. Switching to 1200 baud.");
Win_CommConfig.dcb.BaudRate=CBR_1200;
break;
/*2400 baud*/
case BAUD2400:
Win_CommConfig.dcb.BaudRate=CBR_2400;
break;
/*4800 baud*/
case BAUD4800:
Win_CommConfig.dcb.BaudRate=CBR_4800;
break;
/*9600 baud*/
case BAUD9600:
Win_CommConfig.dcb.BaudRate=CBR_9600;
break;
/*14400 baud*/
case BAUD14400:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 14400 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_14400;
break;
/*19200 baud*/
case BAUD19200:
Win_CommConfig.dcb.BaudRate=CBR_19200;
break;
/*38400 baud*/
case BAUD38400:
Win_CommConfig.dcb.BaudRate=CBR_38400;
break;
/*56000 baud*/
case BAUD56000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 56000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_56000;
break;
/*57600 baud*/
case BAUD57600:
Win_CommConfig.dcb.BaudRate=CBR_57600;
break;
/*76800 baud*/
case BAUD76800:
TTY_WARNING("QextSerialPort: Windows does not support 76800 baud operation. Switching to 57600 baud.");
Win_CommConfig.dcb.BaudRate=CBR_57600;
break;
/*115200 baud*/
case BAUD115200:
Win_CommConfig.dcb.BaudRate=CBR_115200;
break;
/*128000 baud*/
case BAUD128000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 128000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_128000;
break;
/*256000 baud*/
case BAUD256000:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: POSIX does not support 256000 baud operation.");
Win_CommConfig.dcb.BaudRate=CBR_256000;
break;
}
SetCommConfig(Win_Handle, &Win_CommConfig, sizeof(COMMCONFIG));
}
}
/*!
Sets DTR line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setDtr(bool set) {
QMutexLocker lock(mutex);
if (isOpen()) {
if (set) {
EscapeCommFunction(Win_Handle, SETDTR);
}
else {
EscapeCommFunction(Win_Handle, CLRDTR);
}
}
}
/*!
Sets RTS line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setRts(bool set) {
QMutexLocker lock(mutex);
if (isOpen()) {
if (set) {
EscapeCommFunction(Win_Handle, SETRTS);
}
else {
EscapeCommFunction(Win_Handle, CLRRTS);
}
}
}
/*!
Returns the line status as stored by the port function. This function will retrieve the states
of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines
can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned
long with specific bits indicating which lines are high. The following constants should be used
to examine the states of individual lines:
\verbatim
Mask Line
------ ----
LS_CTS CTS
LS_DSR DSR
LS_DCD DCD
LS_RI RI
\endverbatim
This function will return 0 if the port associated with the class is not currently open.
*/
ulong QextSerialPort::lineStatus(void) {
unsigned long Status=0, Temp=0;
QMutexLocker lock(mutex);
if (isOpen()) {
GetCommModemStatus(Win_Handle, &Temp);
if (Temp&MS_CTS_ON) {
Status|=LS_CTS;
}
if (Temp&MS_DSR_ON) {
Status|=LS_DSR;
}
if (Temp&MS_RING_ON) {
Status|=LS_RI;
}
if (Temp&MS_RLSD_ON) {
Status|=LS_DCD;
}
}
return Status;
}
bool QextSerialPort::waitForReadyRead(int msecs)
{
//@todo implement
return false;
}
qint64 QextSerialPort::bytesToWrite() const
{
QReadLocker rl(bytesToWriteLock);
return _bytesToWrite;
}
/*
Triggered when there's activity on our HANDLE.
*/
void QextSerialPort::onWinEvent(HANDLE h)
{
QMutexLocker lock(mutex);
if(h == overlap.hEvent) {
if (eventMask & EV_RXCHAR) {
if (sender() != this && bytesAvailable() > 0)
emit readyRead();
}
if (eventMask & EV_TXEMPTY) {
/*
A write completed. Run through the list of OVERLAPPED writes, and if
they completed successfully, take them off the list and delete them.
Otherwise, leave them on there so they can finish.
*/
qint64 totalBytesWritten = 0;
QList<OVERLAPPED*> overlapsToDelete;
foreach(OVERLAPPED* o, pendingWrites) {
DWORD numBytes = 0;
if (GetOverlappedResult(Win_Handle, o, & numBytes, false)) {
overlapsToDelete.append(o);
totalBytesWritten += numBytes;
} else if( GetLastError() != ERROR_IO_INCOMPLETE ) {
overlapsToDelete.append(o);
qWarning() << "CommEvent overlapped write error:" << GetLastError();
}
}
if (sender() != this && totalBytesWritten > 0) {
QWriteLocker writelocker(bytesToWriteLock);
emit bytesWritten(totalBytesWritten);
_bytesToWrite = 0;
}
foreach(OVERLAPPED* o, overlapsToDelete) {
OVERLAPPED *toDelete = pendingWrites.takeAt(pendingWrites.indexOf(o));
CloseHandle(toDelete->hEvent);
delete toDelete;
}
}
if (eventMask & EV_DSR) {
if (lineStatus() & LS_DSR)
emit dsrChanged(true);
else
emit dsrChanged(false);
}
}
WaitCommEvent(Win_Handle, &eventMask, &overlap);
}
/*!
Sets the read and write timeouts for the port to millisec milliseconds.
Setting 0 indicates that timeouts are not used for read nor write operations;
however read() and write() functions will still block. Set -1 to provide
non-blocking behaviour (read() and write() will return immediately).
\note this function does nothing in event driven mode.
*/
void QextSerialPort::setTimeout(long millisec) {
QMutexLocker lock(mutex);
Settings.Timeout_Millisec = millisec;
if (millisec == -1) {
Win_CommTimeouts.ReadIntervalTimeout = MAXDWORD;
Win_CommTimeouts.ReadTotalTimeoutConstant = 0;
} else {
Win_CommTimeouts.ReadIntervalTimeout = millisec;
Win_CommTimeouts.ReadTotalTimeoutConstant = millisec;
}
Win_CommTimeouts.ReadTotalTimeoutMultiplier = 0;
Win_CommTimeouts.WriteTotalTimeoutMultiplier = millisec;
Win_CommTimeouts.WriteTotalTimeoutConstant = 0;
if (queryMode() != QextSerialPort::EventDriven)
SetCommTimeouts(Win_Handle, &Win_CommTimeouts);
}
| C++ |
/*!
* \file qextserialenumerator.h
* \author Michal Policht
* \see QextSerialEnumerator
*/
#ifndef _QEXTSERIALENUMERATOR_H_
#define _QEXTSERIALENUMERATOR_H_
#include <QString>
#include <QList>
#include <QObject>
#include "qextserialport_global.h"
#ifdef Q_OS_WIN
#include <windows.h>
#include <setupapi.h>
#include <dbt.h>
#endif /*Q_OS_WIN*/
#ifdef Q_OS_MAC
#include <IOKit/usb/IOUSBLib.h>
#endif
/*!
* Structure containing port information.
*/
struct QextPortInfo {
QString portName; ///< Port name.
QString physName; ///< Physical name.
QString friendName; ///< Friendly name.
QString enumName; ///< Enumerator name.
int vendorID; ///< Vendor ID.
int productID; ///< Product ID
};
#ifdef Q_OS_WIN
#ifdef QT_GUI_LIB
#include <QWidget>
class QextSerialEnumerator;
class QextSerialRegistrationWidget : public QWidget
{
Q_OBJECT
public:
QextSerialRegistrationWidget( QextSerialEnumerator* qese ) {
this->qese = qese;
}
~QextSerialRegistrationWidget( ) { }
protected:
QextSerialEnumerator* qese;
bool winEvent( MSG* message, long* result );
};
#endif // QT_GUI_LIB
#endif // Q_OS_WIN
/*!
Provides list of ports available in the system.
\section Usage
To poll the system for a list of connected devices, simply use getPorts(). Each
QextPortInfo structure will populated with information about the corresponding device.
\b Example
\code
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
foreach( QextPortInfo port, ports ) {
// inspect port...
}
\endcode
To enable event-driven notification of device connection events, first call
setUpNotifications() and then connect to the deviceDiscovered() and deviceRemoved()
signals. Event-driven behavior is currently available only on Windows and OS X.
\b Example
\code
QextSerialEnumerator* enumerator = new QextSerialEnumerator();
connect(enumerator, SIGNAL(deviceDiscovered(const QextPortInfo &)),
myClass, SLOT(onDeviceDiscovered(const QextPortInfo &)));
connect(enumerator, SIGNAL(deviceRemoved(const QextPortInfo &)),
myClass, SLOT(onDeviceRemoved(const QextPortInfo &)));
\endcode
\section Credits
Windows implementation is based on Zach Gorman's work from
<a href="http://www.codeproject.com">The Code Project</a> (http://www.codeproject.com/system/setupdi.asp).
OS X implementation, see
http://developer.apple.com/documentation/DeviceDrivers/Conceptual/AccessingHardware/AH_Finding_Devices/chapter_4_section_2.html
\author Michal Policht, Liam Staskawicz
*/
class QEXTSERIALPORT_EXPORT QextSerialEnumerator : public QObject
{
Q_OBJECT
public:
QextSerialEnumerator( );
~QextSerialEnumerator( );
#ifdef Q_OS_WIN
LRESULT onDeviceChangeWin( WPARAM wParam, LPARAM lParam );
private:
/*!
* Get value of specified property from the registry.
* \param key handle to an open key.
* \param property property name.
* \return property value.
*/
static QString getRegKeyValue(HKEY key, LPCTSTR property);
/*!
* Get specific property from registry.
* \param devInfo pointer to the device information set that contains the interface
* and its underlying device. Returned by SetupDiGetClassDevs() function.
* \param devData pointer to an SP_DEVINFO_DATA structure that defines the device instance.
* this is returned by SetupDiGetDeviceInterfaceDetail() function.
* \param property registry property. One of defined SPDRP_* constants.
* \return property string.
*/
static QString getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property);
/*!
* Search for serial ports using setupapi.
* \param infoList list with result.
*/
static void setupAPIScan(QList<QextPortInfo> & infoList);
void setUpNotificationWin( );
static bool getDeviceDetailsWin( QextPortInfo* portInfo, HDEVINFO devInfo,
PSP_DEVINFO_DATA devData, WPARAM wParam = DBT_DEVICEARRIVAL );
static void enumerateDevicesWin( const GUID & guidDev, QList<QextPortInfo>* infoList );
bool matchAndDispatchChangedDevice(const QString & deviceID, const GUID & guid, WPARAM wParam);
#ifdef QT_GUI_LIB
QextSerialRegistrationWidget* notificationWidget;
#endif
#endif /*Q_OS_WIN*/
#ifdef Q_OS_UNIX
#ifdef Q_OS_MAC
private:
/*!
* Search for serial ports using IOKit.
* \param infoList list with result.
*/
static void scanPortsOSX(QList<QextPortInfo> & infoList);
static void iterateServicesOSX(io_object_t service, QList<QextPortInfo> & infoList);
static bool getServiceDetailsOSX( io_object_t service, QextPortInfo* portInfo );
void setUpNotificationOSX( );
void onDeviceDiscoveredOSX( io_object_t service );
void onDeviceTerminatedOSX( io_object_t service );
friend void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
friend void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
IONotificationPortRef notificationPortRef;
#else // Q_OS_MAC
private:
/*!
* Search for serial ports on unix.
* \param infoList list with result.
*/
static void scanPortsNix(QList<QextPortInfo> & infoList);
#endif // Q_OS_MAC
#endif /* Q_OS_UNIX */
public:
/*!
Get list of ports.
\return list of ports currently available in the system.
*/
static QList<QextPortInfo> getPorts();
/*!
Enable event-driven notifications of board discovery/removal.
*/
void setUpNotifications( );
signals:
/*!
A new device has been connected to the system.
setUpNotifications() must be called first to enable event-driven device notifications.
Currently only implemented on Windows and OS X.
\param info The device that has been discovered.
*/
void deviceDiscovered( const QextPortInfo & info );
/*!
A device has been disconnected from the system.
setUpNotifications() must be called first to enable event-driven device notifications.
Currently only implemented on Windows and OS X.
\param info The device that was disconnected.
*/
void deviceRemoved( const QextPortInfo & info );
};
#endif /*_QEXTSERIALENUMERATOR_H_*/
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <IOKit/serial/IOSerialKeys.h>
#include <CoreFoundation/CFNumber.h>
#include <sys/param.h>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
IONotificationPortDestroy( notificationPortRef );
}
// static
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> infoList;
io_iterator_t serialPortIterator = 0;
kern_return_t kernResult = KERN_FAILURE;
CFMutableDictionaryRef matchingDictionary;
// first try to get any serialbsd devices, then try any USBCDC devices
if( !(matchingDictionary = IOServiceMatching(kIOSerialBSDServiceValue) ) ) {
qWarning("IOServiceMatching returned a NULL dictionary.");
return infoList;
}
CFDictionaryAddValue(matchingDictionary, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
// then create the iterator with all the matching devices
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return infoList;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
serialPortIterator = 0;
if( !(matchingDictionary = IOServiceNameMatching("AppleUSBCDC")) ) {
qWarning("IOServiceNameMatching returned a NULL dictionary.");
return infoList;
}
if( IOServiceGetMatchingServices(kIOMasterPortDefault, matchingDictionary, &serialPortIterator) != KERN_SUCCESS ) {
qCritical() << "IOServiceGetMatchingServices failed, returned" << kernResult;
return infoList;
}
iterateServicesOSX(serialPortIterator, infoList);
IOObjectRelease(serialPortIterator);
return infoList;
}
void QextSerialEnumerator::iterateServicesOSX(io_object_t service, QList<QextPortInfo> & infoList)
{
// Iterate through all modems found.
io_object_t usbService;
while( ( usbService = IOIteratorNext(service) ) )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
getServiceDetailsOSX( usbService, &info );
infoList.append(info);
}
}
bool QextSerialEnumerator::getServiceDetailsOSX( io_object_t service, QextPortInfo* portInfo )
{
bool retval = true;
CFTypeRef bsdPathAsCFString = NULL;
CFTypeRef productNameAsCFString = NULL;
CFTypeRef vendorIdAsCFNumber = NULL;
CFTypeRef productIdAsCFNumber = NULL;
// check the name of the modem's callout device
bsdPathAsCFString = IORegistryEntryCreateCFProperty(service, CFSTR(kIOCalloutDeviceKey),
kCFAllocatorDefault, 0);
// wander up the hierarchy until we find the level that can give us the
// vendor/product IDs and the product name, if available
io_registry_entry_t parent;
kern_return_t kernResult = IORegistryEntryGetParentEntry(service, kIOServicePlane, &parent);
while( kernResult == KERN_SUCCESS && !vendorIdAsCFNumber && !productIdAsCFNumber )
{
if(!productNameAsCFString)
productNameAsCFString = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR("Product Name"),
kCFAllocatorDefault, 0);
vendorIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBVendorID),
kCFAllocatorDefault, 0);
productIdAsCFNumber = IORegistryEntrySearchCFProperty(parent,
kIOServicePlane,
CFSTR(kUSBProductID),
kCFAllocatorDefault, 0);
io_registry_entry_t oldparent = parent;
kernResult = IORegistryEntryGetParentEntry(parent, kIOServicePlane, &parent);
IOObjectRelease(oldparent);
}
io_string_t ioPathName;
IORegistryEntryGetPath( service, kIOServicePlane, ioPathName );
portInfo->physName = ioPathName;
if( bsdPathAsCFString )
{
char path[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)bsdPathAsCFString, path,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->portName = path;
CFRelease(bsdPathAsCFString);
}
if(productNameAsCFString)
{
char productName[MAXPATHLEN];
if( CFStringGetCString((CFStringRef)productNameAsCFString, productName,
PATH_MAX, kCFStringEncodingUTF8) )
portInfo->friendName = productName;
CFRelease(productNameAsCFString);
}
if(vendorIdAsCFNumber)
{
SInt32 vID;
if(CFNumberGetValue((CFNumberRef)vendorIdAsCFNumber, kCFNumberSInt32Type, &vID))
portInfo->vendorID = vID;
CFRelease(vendorIdAsCFNumber);
}
if(productIdAsCFNumber)
{
SInt32 pID;
if(CFNumberGetValue((CFNumberRef)productIdAsCFNumber, kCFNumberSInt32Type, &pID))
portInfo->productID = pID;
CFRelease(productIdAsCFNumber);
}
IOObjectRelease(service);
return retval;
}
// IOKit callbacks registered via setupNotifications()
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator );
void deviceDiscoveredCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceDiscoveredOSX(serialService);
}
void deviceTerminatedCallbackOSX( void *ctxt, io_iterator_t serialPortIterator )
{
QextSerialEnumerator* qese = (QextSerialEnumerator*)ctxt;
io_object_t serialService;
while ((serialService = IOIteratorNext(serialPortIterator)))
qese->onDeviceTerminatedOSX(serialService);
}
/*
A device has been discovered via IOKit.
Create a QextPortInfo if possible, and emit the signal indicating that we've found it.
*/
void QextSerialEnumerator::onDeviceDiscoveredOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceDiscovered( info );
}
/*
Notification via IOKit that a device has been removed.
Create a QextPortInfo if possible, and emit the signal indicating that it's gone.
*/
void QextSerialEnumerator::onDeviceTerminatedOSX( io_object_t service )
{
QextPortInfo info;
info.vendorID = 0;
info.productID = 0;
if( getServiceDetailsOSX( service, &info ) )
emit deviceRemoved( info );
}
/*
Create matching dictionaries for the devices we want to get notifications for,
and add them to the current run loop. Invoke the callbacks that will be responding
to these notifications once to arm them, and discover any devices that
are currently connected at the time notifications are setup.
*/
void QextSerialEnumerator::setUpNotifications( )
{
kern_return_t kernResult;
mach_port_t masterPort;
CFRunLoopSourceRef notificationRunLoopSource;
CFMutableDictionaryRef classesToMatch;
CFMutableDictionaryRef cdcClassesToMatch;
io_iterator_t portIterator;
kernResult = IOMasterPort(MACH_PORT_NULL, &masterPort);
if (KERN_SUCCESS != kernResult) {
qDebug() << "IOMasterPort returned:" << kernResult;
return;
}
classesToMatch = IOServiceMatching(kIOSerialBSDServiceValue);
if (classesToMatch == NULL)
qDebug("IOServiceMatching returned a NULL dictionary.");
else
CFDictionarySetValue(classesToMatch, CFSTR(kIOSerialBSDTypeKey), CFSTR(kIOSerialBSDAllTypes));
if( !(cdcClassesToMatch = IOServiceNameMatching("AppleUSBCDC") ) ) {
qWarning("couldn't create cdc matching dict");
return;
}
// Retain an additional reference since each call to IOServiceAddMatchingNotification consumes one.
classesToMatch = (CFMutableDictionaryRef) CFRetain(classesToMatch);
cdcClassesToMatch = (CFMutableDictionaryRef) CFRetain(cdcClassesToMatch);
notificationPortRef = IONotificationPortCreate(masterPort);
if(notificationPortRef == NULL) {
qDebug("IONotificationPortCreate return a NULL IONotificationPortRef.");
return;
}
notificationRunLoopSource = IONotificationPortGetRunLoopSource(notificationPortRef);
if (notificationRunLoopSource == NULL) {
qDebug("IONotificationPortGetRunLoopSource returned NULL CFRunLoopSourceRef.");
return;
}
CFRunLoopAddSource(CFRunLoopGetCurrent(), notificationRunLoopSource, kCFRunLoopDefaultMode);
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, classesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOMatchedNotification, cdcClassesToMatch,
deviceDiscoveredCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and grab any devices that are already connected
deviceDiscoveredCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, classesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
kernResult = IOServiceAddMatchingNotification(notificationPortRef, kIOTerminatedNotification, cdcClassesToMatch,
deviceTerminatedCallbackOSX, this, &portIterator);
if (kernResult != KERN_SUCCESS) {
qDebug() << "IOServiceAddMatchingNotification return:" << kernResult;
return;
}
// arm the callback, and clear any devices that are terminated
deviceTerminatedCallbackOSX( this, portIterator );
}
| C++ |
#include "qextserialenumerator.h"
#include <QDebug>
#include <QMetaType>
#include <objbase.h>
#include <initguid.h>
#include "qextserialport.h"
#include <QRegExp>
QextSerialEnumerator::QextSerialEnumerator( )
{
if( !QMetaType::isRegistered( QMetaType::type("QextPortInfo") ) )
qRegisterMetaType<QextPortInfo>("QextPortInfo");
#if (defined QT_GUI_LIB)
notificationWidget = 0;
#endif // Q_OS_WIN
}
QextSerialEnumerator::~QextSerialEnumerator( )
{
#if (defined QT_GUI_LIB)
if( notificationWidget )
delete notificationWidget;
#endif
}
// see http://msdn.microsoft.com/en-us/library/ms791134.aspx for list of GUID classes
#ifndef GUID_DEVCLASS_PORTS
DEFINE_GUID(GUID_DEVCLASS_PORTS, 0x4D36E978, 0xE325, 0x11CE, 0xBF, 0xC1, 0x08, 0x00, 0x2B, 0xE1, 0x03, 0x18 );
#endif
/* Gordon Schumacher's macros for TCHAR -> QString conversions and vice versa */
#ifdef UNICODE
#define QStringToTCHAR(x) (wchar_t*) x.utf16()
#define PQStringToTCHAR(x) (wchar_t*) x->utf16()
#define TCHARToQString(x) QString::fromUtf16((ushort*)(x))
#define TCHARToQStringN(x,y) QString::fromUtf16((ushort*)(x),(y))
#else
#define QStringToTCHAR(x) x.local8Bit().constData()
#define PQStringToTCHAR(x) x->local8Bit().constData()
#define TCHARToQString(x) QString::fromLocal8Bit((x))
#define TCHARToQStringN(x,y) QString::fromLocal8Bit((x),(y))
#endif /*UNICODE*/
//static
QString QextSerialEnumerator::getRegKeyValue(HKEY key, LPCTSTR property)
{
DWORD size = 0;
DWORD type;
RegQueryValueEx(key, property, NULL, NULL, NULL, & size);
BYTE* buff = new BYTE[size];
QString result;
if( RegQueryValueEx(key, property, NULL, &type, buff, & size) == ERROR_SUCCESS )
result = TCHARToQString(buff);
RegCloseKey(key);
delete [] buff;
return result;
}
//static
QString QextSerialEnumerator::getDeviceProperty(HDEVINFO devInfo, PSP_DEVINFO_DATA devData, DWORD property)
{
DWORD buffSize = 0;
SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, NULL, 0, & buffSize);
BYTE* buff = new BYTE[buffSize];
SetupDiGetDeviceRegistryProperty(devInfo, devData, property, NULL, buff, buffSize, NULL);
QString result = TCHARToQString(buff);
delete [] buff;
return result;
}
QList<QextPortInfo> QextSerialEnumerator::getPorts()
{
QList<QextPortInfo> ports;
enumerateDevicesWin(GUID_DEVCLASS_PORTS, &ports);
return ports;
}
void QextSerialEnumerator::enumerateDevicesWin( const GUID & guid, QList<QextPortInfo>* infoList )
{
HDEVINFO devInfo;
if( (devInfo = SetupDiGetClassDevs(&guid, NULL, NULL, DIGCF_PRESENT)) != INVALID_HANDLE_VALUE)
{
SP_DEVINFO_DATA devInfoData;
devInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for(int i = 0; SetupDiEnumDeviceInfo(devInfo, i, &devInfoData); i++)
{
QextPortInfo info;
info.productID = info.vendorID = 0;
getDeviceDetailsWin( &info, devInfo, &devInfoData );
infoList->append(info);
}
SetupDiDestroyDeviceInfoList(devInfo);
}
}
#ifdef QT_GUI_LIB
bool QextSerialRegistrationWidget::winEvent( MSG* message, long* result )
{
if ( message->message == WM_DEVICECHANGE ) {
qese->onDeviceChangeWin( message->wParam, message->lParam );
*result = 1;
return true;
}
return false;
}
#endif
void QextSerialEnumerator::setUpNotifications( )
{
#ifdef QT_GUI_LIB
if(notificationWidget)
return;
notificationWidget = new QextSerialRegistrationWidget(this);
DEV_BROADCAST_DEVICEINTERFACE dbh;
ZeroMemory(&dbh, sizeof(dbh));
dbh.dbcc_size = sizeof(dbh);
dbh.dbcc_devicetype = DBT_DEVTYP_DEVICEINTERFACE;
CopyMemory(&dbh.dbcc_classguid, &GUID_DEVCLASS_PORTS, sizeof(GUID));
if( RegisterDeviceNotification( notificationWidget->winId( ), &dbh, DEVICE_NOTIFY_WINDOW_HANDLE ) == NULL)
qWarning() << "RegisterDeviceNotification failed:" << GetLastError();
// setting up notifications doesn't tell us about devices already connected
// so get those manually
foreach( QextPortInfo port, getPorts() )
emit deviceDiscovered( port );
#else
qWarning("QextSerialEnumerator: GUI not enabled - can't register for device notifications.");
#endif // QT_GUI_LIB
}
LRESULT QextSerialEnumerator::onDeviceChangeWin( WPARAM wParam, LPARAM lParam )
{
if ( DBT_DEVICEARRIVAL == wParam || DBT_DEVICEREMOVECOMPLETE == wParam )
{
PDEV_BROADCAST_HDR pHdr = (PDEV_BROADCAST_HDR)lParam;
if( pHdr->dbch_devicetype == DBT_DEVTYP_DEVICEINTERFACE )
{
PDEV_BROADCAST_DEVICEINTERFACE pDevInf = (PDEV_BROADCAST_DEVICEINTERFACE)pHdr;
// delimiters are different across APIs...change to backslash. ugh.
QString deviceID = TCHARToQString(pDevInf->dbcc_name).toUpper().replace("#", "\\");
matchAndDispatchChangedDevice(deviceID, GUID_DEVCLASS_PORTS, wParam);
}
}
return 0;
}
bool QextSerialEnumerator::matchAndDispatchChangedDevice(const QString & deviceID, const GUID & guid, WPARAM wParam)
{
bool rv = false;
DWORD dwFlag = (DBT_DEVICEARRIVAL == wParam) ? DIGCF_PRESENT : DIGCF_ALLCLASSES;
HDEVINFO devInfo;
if( (devInfo = SetupDiGetClassDevs(&guid,NULL,NULL,dwFlag)) != INVALID_HANDLE_VALUE )
{
SP_DEVINFO_DATA spDevInfoData;
spDevInfoData.cbSize = sizeof(SP_DEVINFO_DATA);
for(int i=0; SetupDiEnumDeviceInfo(devInfo, i, &spDevInfoData); i++)
{
DWORD nSize=0 ;
TCHAR buf[MAX_PATH];
if ( SetupDiGetDeviceInstanceId(devInfo, &spDevInfoData, buf, MAX_PATH, &nSize) &&
deviceID.contains(TCHARToQString(buf))) // we found a match
{
rv = true;
QextPortInfo info;
info.productID = info.vendorID = 0;
getDeviceDetailsWin( &info, devInfo, &spDevInfoData, wParam );
if( wParam == DBT_DEVICEARRIVAL )
emit deviceDiscovered(info);
else if( wParam == DBT_DEVICEREMOVECOMPLETE )
emit deviceRemoved(info);
break;
}
}
SetupDiDestroyDeviceInfoList(devInfo);
}
return rv;
}
bool QextSerialEnumerator::getDeviceDetailsWin( QextPortInfo* portInfo, HDEVINFO devInfo, PSP_DEVINFO_DATA devData, WPARAM wParam )
{
portInfo->friendName = getDeviceProperty(devInfo, devData, SPDRP_FRIENDLYNAME);
if( wParam == DBT_DEVICEARRIVAL)
portInfo->physName = getDeviceProperty(devInfo, devData, SPDRP_PHYSICAL_DEVICE_OBJECT_NAME);
portInfo->enumName = getDeviceProperty(devInfo, devData, SPDRP_ENUMERATOR_NAME);
QString hardwareIDs = getDeviceProperty(devInfo, devData, SPDRP_HARDWAREID);
HKEY devKey = SetupDiOpenDevRegKey(devInfo, devData, DICS_FLAG_GLOBAL, 0, DIREG_DEV, KEY_READ);
portInfo->portName = QextSerialPort::fullPortNameWin( getRegKeyValue(devKey, TEXT("PortName")) );
QRegExp idRx("VID_(\\w+)&PID_(\\w+)");
if( hardwareIDs.toUpper().contains(idRx) )
{
bool dummy;
portInfo->vendorID = idRx.cap(1).toInt(&dummy, 16);
portInfo->productID = idRx.cap(2).toInt(&dummy, 16);
//qDebug() << "got vid:" << vid << "pid:" << pid;
}
return true;
}
| C++ |
#include <fcntl.h>
#include <stdio.h>
#include "qextserialport.h"
#include <QMutexLocker>
#include <QDebug>
void QextSerialPort::platformSpecificInit()
{
fd = 0;
readNotifier = 0;
}
/*!
Standard destructor.
*/
void QextSerialPort::platformSpecificDestruct()
{}
/*!
Sets the baud rate of the serial port. Note that not all rates are applicable on
all platforms. The following table shows translations of the various baud rate
constants on Windows(including NT/2000) and POSIX platforms. Speeds marked with an *
are speeds that are usable on both Windows and POSIX.
\note
BAUD76800 may not be supported on all POSIX systems. SGI/IRIX systems do not support
BAUD1800.
\verbatim
RATE Windows Speed POSIX Speed
----------- ------------- -----------
BAUD50 110 50
BAUD75 110 75
*BAUD110 110 110
BAUD134 110 134.5
BAUD150 110 150
BAUD200 110 200
*BAUD300 300 300
*BAUD600 600 600
*BAUD1200 1200 1200
BAUD1800 1200 1800
*BAUD2400 2400 2400
*BAUD4800 4800 4800
*BAUD9600 9600 9600
BAUD14400 14400 9600
*BAUD19200 19200 19200
*BAUD38400 38400 38400
BAUD56000 56000 38400
*BAUD57600 57600 57600
BAUD76800 57600 76800
*BAUD115200 115200 115200
BAUD128000 128000 115200
BAUD256000 256000 115200
\endverbatim
*/
void QextSerialPort::setBaudRate(BaudRateType baudRate)
{
QMutexLocker lock(mutex);
if (Settings.BaudRate!=baudRate) {
switch (baudRate) {
case BAUD14400:
Settings.BaudRate=BAUD9600;
break;
case BAUD56000:
Settings.BaudRate=BAUD38400;
break;
case BAUD76800:
#ifndef B76800
Settings.BaudRate=BAUD57600;
#else
Settings.BaudRate=baudRate;
#endif
break;
case BAUD128000:
case BAUD256000:
Settings.BaudRate=BAUD115200;
break;
default:
Settings.BaudRate=baudRate;
break;
}
}
if (isOpen()) {
switch (baudRate) {
/*50 baud*/
case BAUD50:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 50 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B50;
#else
cfsetispeed(&Posix_CommConfig, B50);
cfsetospeed(&Posix_CommConfig, B50);
#endif
break;
/*75 baud*/
case BAUD75:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 75 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B75;
#else
cfsetispeed(&Posix_CommConfig, B75);
cfsetospeed(&Posix_CommConfig, B75);
#endif
break;
/*110 baud*/
case BAUD110:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B110;
#else
cfsetispeed(&Posix_CommConfig, B110);
cfsetospeed(&Posix_CommConfig, B110);
#endif
break;
/*134.5 baud*/
case BAUD134:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 134.5 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B134;
#else
cfsetispeed(&Posix_CommConfig, B134);
cfsetospeed(&Posix_CommConfig, B134);
#endif
break;
/*150 baud*/
case BAUD150:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 150 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B150;
#else
cfsetispeed(&Posix_CommConfig, B150);
cfsetospeed(&Posix_CommConfig, B150);
#endif
break;
/*200 baud*/
case BAUD200:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows does not support 200 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B200;
#else
cfsetispeed(&Posix_CommConfig, B200);
cfsetospeed(&Posix_CommConfig, B200);
#endif
break;
/*300 baud*/
case BAUD300:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B300;
#else
cfsetispeed(&Posix_CommConfig, B300);
cfsetospeed(&Posix_CommConfig, B300);
#endif
break;
/*600 baud*/
case BAUD600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B600;
#else
cfsetispeed(&Posix_CommConfig, B600);
cfsetospeed(&Posix_CommConfig, B600);
#endif
break;
/*1200 baud*/
case BAUD1200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1200;
#else
cfsetispeed(&Posix_CommConfig, B1200);
cfsetospeed(&Posix_CommConfig, B1200);
#endif
break;
/*1800 baud*/
case BAUD1800:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows and IRIX do not support 1800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B1800;
#else
cfsetispeed(&Posix_CommConfig, B1800);
cfsetospeed(&Posix_CommConfig, B1800);
#endif
break;
/*2400 baud*/
case BAUD2400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B2400;
#else
cfsetispeed(&Posix_CommConfig, B2400);
cfsetospeed(&Posix_CommConfig, B2400);
#endif
break;
/*4800 baud*/
case BAUD4800:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B4800;
#else
cfsetispeed(&Posix_CommConfig, B4800);
cfsetospeed(&Posix_CommConfig, B4800);
#endif
break;
/*9600 baud*/
case BAUD9600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*14400 baud*/
case BAUD14400:
TTY_WARNING("QextSerialPort: POSIX does not support 14400 baud operation. Switching to 9600 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B9600;
#else
cfsetispeed(&Posix_CommConfig, B9600);
cfsetospeed(&Posix_CommConfig, B9600);
#endif
break;
/*19200 baud*/
case BAUD19200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B19200;
#else
cfsetispeed(&Posix_CommConfig, B19200);
cfsetospeed(&Posix_CommConfig, B19200);
#endif
break;
/*38400 baud*/
case BAUD38400:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*56000 baud*/
case BAUD56000:
TTY_WARNING("QextSerialPort: POSIX does not support 56000 baud operation. Switching to 38400 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B38400;
#else
cfsetispeed(&Posix_CommConfig, B38400);
cfsetospeed(&Posix_CommConfig, B38400);
#endif
break;
/*57600 baud*/
case BAUD57600:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B57600;
#else
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif
break;
/*76800 baud*/
case BAUD76800:
TTY_PORTABILITY_WARNING("QextSerialPort Portability Warning: Windows and some POSIX systems do not support 76800 baud operation.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
#ifdef B76800
Posix_CommConfig.c_cflag|=B76800;
#else
TTY_WARNING("QextSerialPort: QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
Posix_CommConfig.c_cflag|=B57600;
#endif //B76800
#else //CBAUD
#ifdef B76800
cfsetispeed(&Posix_CommConfig, B76800);
cfsetospeed(&Posix_CommConfig, B76800);
#else
TTY_WARNING("QextSerialPort: QextSerialPort was compiled without 76800 baud support. Switching to 57600 baud.");
cfsetispeed(&Posix_CommConfig, B57600);
cfsetospeed(&Posix_CommConfig, B57600);
#endif //B76800
#endif //CBAUD
break;
/*115200 baud*/
case BAUD115200:
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*128000 baud*/
case BAUD128000:
TTY_WARNING("QextSerialPort: POSIX does not support 128000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
/*256000 baud*/
case BAUD256000:
TTY_WARNING("QextSerialPort: POSIX does not support 256000 baud operation. Switching to 115200 baud.");
#ifdef CBAUD
Posix_CommConfig.c_cflag&=(~CBAUD);
Posix_CommConfig.c_cflag|=B115200;
#else
cfsetispeed(&Posix_CommConfig, B115200);
cfsetospeed(&Posix_CommConfig, B115200);
#endif
break;
}
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
}
/*!
Sets the number of data bits used by the serial port. Possible values of dataBits are:
\verbatim
DATA_5 5 data bits
DATA_6 6 data bits
DATA_7 7 data bits
DATA_8 8 data bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
5 data bits cannot be used with 2 stop bits.
\par
8 data bits cannot be used with space parity on POSIX systems.
*/
void QextSerialPort::setDataBits(DataBitsType dataBits)
{
QMutexLocker lock(mutex);
if (Settings.DataBits!=dataBits) {
if ((Settings.StopBits==STOP_2 && dataBits==DATA_5) ||
(Settings.StopBits==STOP_1_5 && dataBits!=DATA_5) ||
(Settings.Parity==PAR_SPACE && dataBits==DATA_8)) {
}
else {
Settings.DataBits=dataBits;
}
}
if (isOpen()) {
switch(dataBits) {
/*5 data bits*/
case DATA_5:
if (Settings.StopBits==STOP_2) {
TTY_WARNING("QextSerialPort: 5 Data bits cannot be used with 2 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS5;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*6 data bits*/
case DATA_6:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 6 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS6;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*7 data bits*/
case DATA_7:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 7 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS7;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*8 data bits*/
case DATA_8:
if (Settings.StopBits==STOP_1_5) {
TTY_WARNING("QextSerialPort: 8 Data bits cannot be used with 1.5 stop bits.");
}
else {
Settings.DataBits=dataBits;
Posix_CommConfig.c_cflag&=(~CSIZE);
Posix_CommConfig.c_cflag|=CS8;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
}
/*!
Sets the parity associated with the serial port. The possible values of parity are:
\verbatim
PAR_SPACE Space Parity
PAR_MARK Mark Parity
PAR_NONE No Parity
PAR_EVEN Even Parity
PAR_ODD Odd Parity
\endverbatim
\note
This function is subject to the following limitations:
\par
POSIX systems do not support mark parity.
\par
POSIX systems support space parity only if tricked into doing so, and only with
fewer than 8 data bits. Use space parity very carefully with POSIX systems.
*/
void QextSerialPort::setParity(ParityType parity)
{
QMutexLocker lock(mutex);
if (Settings.Parity!=parity) {
if (parity==PAR_MARK || (parity==PAR_SPACE && Settings.DataBits==DATA_8)) {
}
else {
Settings.Parity=parity;
}
}
if (isOpen()) {
switch (parity) {
/*space parity*/
case PAR_SPACE:
if (Settings.DataBits==DATA_8) {
TTY_PORTABILITY_WARNING("QextSerialPort: Space parity is only supported in POSIX with 7 or fewer data bits");
}
else {
/*space parity not directly supported - add an extra data bit to simulate it*/
Posix_CommConfig.c_cflag&=~(PARENB|CSIZE);
switch(Settings.DataBits) {
case DATA_5:
Settings.DataBits=DATA_6;
Posix_CommConfig.c_cflag|=CS6;
break;
case DATA_6:
Settings.DataBits=DATA_7;
Posix_CommConfig.c_cflag|=CS7;
break;
case DATA_7:
Settings.DataBits=DATA_8;
Posix_CommConfig.c_cflag|=CS8;
break;
case DATA_8:
break;
}
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
/*mark parity - WINDOWS ONLY*/
case PAR_MARK:
TTY_WARNING("QextSerialPort: Mark parity is not supported by POSIX.");
break;
/*no parity*/
case PAR_NONE:
Posix_CommConfig.c_cflag&=(~PARENB);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*even parity*/
case PAR_EVEN:
Posix_CommConfig.c_cflag&=(~PARODD);
Posix_CommConfig.c_cflag|=PARENB;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*odd parity*/
case PAR_ODD:
Posix_CommConfig.c_cflag|=(PARENB|PARODD);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
}
}
}
/*!
Sets the number of stop bits used by the serial port. Possible values of stopBits are:
\verbatim
STOP_1 1 stop bit
STOP_1_5 1.5 stop bits
STOP_2 2 stop bits
\endverbatim
\note
This function is subject to the following restrictions:
\par
2 stop bits cannot be used with 5 data bits.
\par
POSIX does not support 1.5 stop bits.
*/
void QextSerialPort::setStopBits(StopBitsType stopBits)
{
QMutexLocker lock(mutex);
if (Settings.StopBits!=stopBits) {
if ((Settings.DataBits==DATA_5 && stopBits==STOP_2) || stopBits==STOP_1_5) {}
else {
Settings.StopBits=stopBits;
}
}
if (isOpen()) {
switch (stopBits) {
/*one stop bit*/
case STOP_1:
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag&=(~CSTOPB);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*1.5 stop bits*/
case STOP_1_5:
TTY_WARNING("QextSerialPort: 1.5 stop bit operation is not supported by POSIX.");
break;
/*two stop bits*/
case STOP_2:
if (Settings.DataBits==DATA_5) {
TTY_WARNING("QextSerialPort: 2 stop bits cannot be used with 5 data bits");
}
else {
Settings.StopBits=stopBits;
Posix_CommConfig.c_cflag|=CSTOPB;
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
}
break;
}
}
}
/*!
Sets the flow control used by the port. Possible values of flow are:
\verbatim
FLOW_OFF No flow control
FLOW_HARDWARE Hardware (RTS/CTS) flow control
FLOW_XONXOFF Software (XON/XOFF) flow control
\endverbatim
\note
FLOW_HARDWARE may not be supported on all versions of UNIX. In cases where it is
unsupported, FLOW_HARDWARE is the same as FLOW_OFF.
*/
void QextSerialPort::setFlowControl(FlowType flow)
{
QMutexLocker lock(mutex);
if (Settings.FlowControl!=flow) {
Settings.FlowControl=flow;
}
if (isOpen()) {
switch(flow) {
/*no flow control*/
case FLOW_OFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
/*software (XON/XOFF) flow control*/
case FLOW_XONXOFF:
Posix_CommConfig.c_cflag&=(~CRTSCTS);
Posix_CommConfig.c_iflag|=(IXON|IXOFF|IXANY);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
case FLOW_HARDWARE:
Posix_CommConfig.c_cflag|=CRTSCTS;
Posix_CommConfig.c_iflag&=(~(IXON|IXOFF|IXANY));
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
break;
}
}
}
/*!
Sets the read and write timeouts for the port to millisec milliseconds.
Note that this is a per-character timeout, i.e. the port will wait this long for each
individual character, not for the whole read operation. This timeout also applies to the
bytesWaiting() function.
\note
POSIX does not support millisecond-level control for I/O timeout values. Any
timeout set using this function will be set to the next lowest tenth of a second for
the purposes of detecting read or write timeouts. For example a timeout of 550 milliseconds
will be seen by the class as a timeout of 500 milliseconds for the purposes of reading and
writing the port. However millisecond-level control is allowed by the select() system call,
so for example a 550-millisecond timeout will be seen as 550 milliseconds on POSIX systems for
the purpose of detecting available bytes in the read buffer.
*/
void QextSerialPort::setTimeout(long millisec)
{
QMutexLocker lock(mutex);
Settings.Timeout_Millisec = millisec;
Posix_Copy_Timeout.tv_sec = millisec / 1000;
Posix_Copy_Timeout.tv_usec = millisec % 1000;
if (isOpen()) {
if (millisec == -1)
fcntl(fd, F_SETFL, O_NDELAY);
else
//O_SYNC should enable blocking ::write()
//however this seems not working on Linux 2.6.21 (works on OpenBSD 4.2)
fcntl(fd, F_SETFL, O_SYNC);
tcgetattr(fd, & Posix_CommConfig);
Posix_CommConfig.c_cc[VTIME] = millisec/100;
tcsetattr(fd, TCSAFLUSH, & Posix_CommConfig);
}
}
/*!
Opens the serial port associated to this class.
This function has no effect if the port associated with the class is already open.
The port is also configured to the current settings, as stored in the Settings structure.
*/
bool QextSerialPort::open(OpenMode mode)
{
QMutexLocker lock(mutex);
if (mode == QIODevice::NotOpen)
return isOpen();
if (!isOpen()) {
qDebug() << "trying to open file" << port.toAscii();
//note: linux 2.6.21 seems to ignore O_NDELAY flag
if ((fd = ::open(port.toAscii() ,O_RDWR | O_NOCTTY | O_NDELAY)) != -1) {
qDebug("file opened succesfully");
setOpenMode(mode); // Flag the port as opened
tcgetattr(fd, &old_termios); // Save the old termios
Posix_CommConfig = old_termios; // Make a working copy
cfmakeraw(&Posix_CommConfig); // Enable raw access
/*set up other port settings*/
Posix_CommConfig.c_cflag|=CREAD|CLOCAL;
Posix_CommConfig.c_lflag&=(~(ICANON|ECHO|ECHOE|ECHOK|ECHONL|ISIG));
Posix_CommConfig.c_iflag&=(~(INPCK|IGNPAR|PARMRK|ISTRIP|ICRNL|IXANY));
Posix_CommConfig.c_oflag&=(~OPOST);
Posix_CommConfig.c_cc[VMIN]= 0;
#ifdef _POSIX_VDISABLE // Is a disable character available on this system?
// Some systems allow for per-device disable-characters, so get the
// proper value for the configured device
const long vdisable = fpathconf(fd, _PC_VDISABLE);
Posix_CommConfig.c_cc[VINTR] = vdisable;
Posix_CommConfig.c_cc[VQUIT] = vdisable;
Posix_CommConfig.c_cc[VSTART] = vdisable;
Posix_CommConfig.c_cc[VSTOP] = vdisable;
Posix_CommConfig.c_cc[VSUSP] = vdisable;
#endif //_POSIX_VDISABLE
setBaudRate(Settings.BaudRate);
setDataBits(Settings.DataBits);
setParity(Settings.Parity);
setStopBits(Settings.StopBits);
setFlowControl(Settings.FlowControl);
setTimeout(Settings.Timeout_Millisec);
tcsetattr(fd, TCSAFLUSH, &Posix_CommConfig);
if (queryMode() == QextSerialPort::EventDriven) {
readNotifier = new QSocketNotifier(fd, QSocketNotifier::Read, this);
connect(readNotifier, SIGNAL(activated(int)), this, SIGNAL(readyRead()));
}
} else {
qDebug() << "could not open file:" << strerror(errno);
lastErr = E_FILE_NOT_FOUND;
}
}
return isOpen();
}
/*!
Closes a serial port. This function has no effect if the serial port associated with the class
is not currently open.
*/
void QextSerialPort::close()
{
QMutexLocker lock(mutex);
if( isOpen() )
{
// Force a flush and then restore the original termios
flush();
// Using both TCSAFLUSH and TCSANOW here discards any pending input
tcsetattr(fd, TCSAFLUSH | TCSANOW, &old_termios); // Restore termios
// Be a good QIODevice and call QIODevice::close() before POSIX close()
// so the aboutToClose() signal is emitted at the proper time
QIODevice::close(); // Flag the device as closed
// QIODevice::close() doesn't actually close the port, so do that here
::close(fd);
if(readNotifier) {
delete readNotifier;
readNotifier = 0;
}
}
}
/*!
Flushes all pending I/O to the serial port. This function has no effect if the serial port
associated with the class is not currently open.
*/
void QextSerialPort::flush()
{
QMutexLocker lock(mutex);
if (isOpen())
tcflush(fd, TCIOFLUSH);
}
/*!
This function will return the number of bytes waiting in the receive queue of the serial port.
It is included primarily to provide a complete QIODevice interface, and will not record errors
in the lastErr member (because it is const). This function is also not thread-safe - in
multithreading situations, use QextSerialPort::bytesWaiting() instead.
*/
qint64 QextSerialPort::size() const
{
int numBytes;
if (ioctl(fd, FIONREAD, &numBytes)<0) {
numBytes = 0;
}
return (qint64)numBytes;
}
/*!
Returns the number of bytes waiting in the port's receive queue. This function will return 0 if
the port is not currently open, or -1 on error.
*/
qint64 QextSerialPort::bytesAvailable() const
{
QMutexLocker lock(mutex);
if (isOpen()) {
int bytesQueued;
if (ioctl(fd, FIONREAD, &bytesQueued) == -1) {
return (qint64)-1;
}
return bytesQueued + QIODevice::bytesAvailable();
}
return 0;
}
/*!
This function is included to implement the full QIODevice interface, and currently has no
purpose within this class. This function is meaningless on an unbuffered device and currently
only prints a warning message to that effect.
*/
void QextSerialPort::ungetChar(char)
{
/*meaningless on unbuffered sequential device - return error and print a warning*/
TTY_WARNING("QextSerialPort: ungetChar() called on an unbuffered sequential device - operation is meaningless");
}
/*!
Translates a system-specific error code to a QextSerialPort error code. Used internally.
*/
void QextSerialPort::translateError(ulong error)
{
switch (error) {
case EBADF:
case ENOTTY:
lastErr=E_INVALID_FD;
break;
case EINTR:
lastErr=E_CAUGHT_NON_BLOCKED_SIGNAL;
break;
case ENOMEM:
lastErr=E_NO_MEMORY;
break;
}
}
/*!
Sets DTR line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setDtr(bool set)
{
QMutexLocker lock(mutex);
if (isOpen()) {
int status;
ioctl(fd, TIOCMGET, &status);
if (set) {
status|=TIOCM_DTR;
}
else {
status&=~TIOCM_DTR;
}
ioctl(fd, TIOCMSET, &status);
}
}
/*!
Sets RTS line to the requested state (high by default). This function will have no effect if
the port associated with the class is not currently open.
*/
void QextSerialPort::setRts(bool set)
{
QMutexLocker lock(mutex);
if (isOpen()) {
int status;
ioctl(fd, TIOCMGET, &status);
if (set) {
status|=TIOCM_RTS;
}
else {
status&=~TIOCM_RTS;
}
ioctl(fd, TIOCMSET, &status);
}
}
/*!
Returns the line status as stored by the port function. This function will retrieve the states
of the following lines: DCD, CTS, DSR, and RI. On POSIX systems, the following additional lines
can be monitored: DTR, RTS, Secondary TXD, and Secondary RXD. The value returned is an unsigned
long with specific bits indicating which lines are high. The following constants should be used
to examine the states of individual lines:
\verbatim
Mask Line
------ ----
LS_CTS CTS
LS_DSR DSR
LS_DCD DCD
LS_RI RI
LS_RTS RTS (POSIX only)
LS_DTR DTR (POSIX only)
LS_ST Secondary TXD (POSIX only)
LS_SR Secondary RXD (POSIX only)
\endverbatim
This function will return 0 if the port associated with the class is not currently open.
*/
unsigned long QextSerialPort::lineStatus()
{
unsigned long Status=0, Temp=0;
QMutexLocker lock(mutex);
if (isOpen()) {
ioctl(fd, TIOCMGET, &Temp);
if (Temp&TIOCM_CTS) {
Status|=LS_CTS;
}
if (Temp&TIOCM_DSR) {
Status|=LS_DSR;
}
if (Temp&TIOCM_RI) {
Status|=LS_RI;
}
if (Temp&TIOCM_CD) {
Status|=LS_DCD;
}
if (Temp&TIOCM_DTR) {
Status|=LS_DTR;
}
if (Temp&TIOCM_RTS) {
Status|=LS_RTS;
}
if (Temp&TIOCM_ST) {
Status|=LS_ST;
}
if (Temp&TIOCM_SR) {
Status|=LS_SR;
}
}
return Status;
}
/*!
Reads a block of data from the serial port. This function will read at most maxSize bytes from
the serial port and place them in the buffer pointed to by data. Return value is the number of
bytes actually read, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::readData(char * data, qint64 maxSize)
{
QMutexLocker lock(mutex);
int retVal = ::read(fd, data, maxSize);
if (retVal == -1)
lastErr = E_READ_FAILED;
return retVal;
}
/*!
Writes a block of data to the serial port. This function will write maxSize bytes
from the buffer pointed to by data to the serial port. Return value is the number
of bytes actually written, or -1 on error.
\warning before calling this function ensure that serial port associated with this class
is currently open (use isOpen() function to check if port is open).
*/
qint64 QextSerialPort::writeData(const char * data, qint64 maxSize)
{
QMutexLocker lock(mutex);
int retVal = ::write(fd, data, maxSize);
if (retVal == -1)
lastErr = E_WRITE_FAILED;
return (qint64)retVal;
}
| C++ |
/* qesptest.h
**************************************/
#ifndef _QESPTEST_H_
#define _QESPTEST_H_
#include <QWidget>
class QLineEdit;
class QTextEdit;
class QextSerialPort;
class QSpinBox;
class QespTest : public QWidget
{
Q_OBJECT
public:
QespTest(QWidget *parent=0);
virtual ~QespTest();
private:
QLineEdit *message;
QSpinBox* delaySpinBox;
QTextEdit *received_msg;
QextSerialPort *port;
private slots:
void transmitMsg();
void receiveMsg();
void appendCR();
void appendLF();
void closePort();
void openPort();
};
#endif
| C++ |
/* QespTest.cpp
**************************************/
#include "QespTest.h"
#include <qextserialport.h>
#include <QLayout>
#include <QLineEdit>
#include <QTextEdit>
#include <QPushButton>
#include <QSpinBox>
QespTest::QespTest(QWidget* parent)
: QWidget(parent)
{
//modify the port settings on your own
#ifdef _TTY_POSIX_
port = new QextSerialPort("/dev/ttyS0", QextSerialPort::Polling);
#else
port = new QextSerialPort("COM1", QextSerialPort::Polling);
#endif /*_TTY_POSIX*/
port->setBaudRate(BAUD19200);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
//set timeouts to 500 ms
port->setTimeout(500);
message = new QLineEdit(this);
// transmit receive
QPushButton *transmitButton = new QPushButton("Transmit");
connect(transmitButton, SIGNAL(clicked()), SLOT(transmitMsg()));
QPushButton *receiveButton = new QPushButton("Receive");
connect(receiveButton, SIGNAL(clicked()), SLOT(receiveMsg()));
QHBoxLayout* trLayout = new QHBoxLayout;
trLayout->addWidget(transmitButton);
trLayout->addWidget(receiveButton);
//CR LF
QPushButton *CRButton = new QPushButton("CR");
connect(CRButton, SIGNAL(clicked()), SLOT(appendCR()));
QPushButton *LFButton = new QPushButton("LF");
connect(LFButton, SIGNAL(clicked()), SLOT(appendLF()));
QHBoxLayout *crlfLayout = new QHBoxLayout;
crlfLayout->addWidget(CRButton);
crlfLayout->addWidget(LFButton);
//open close
QPushButton *openButton = new QPushButton("Open");
connect(openButton, SIGNAL(clicked()), SLOT(openPort()));
QPushButton *closeButton = new QPushButton("Close");
connect(closeButton, SIGNAL(clicked()), SLOT(closePort()));
QHBoxLayout *ocLayout = new QHBoxLayout;
ocLayout->addWidget(openButton);
ocLayout->addWidget(closeButton);
received_msg = new QTextEdit();
QVBoxLayout *myVBox = new QVBoxLayout;
myVBox->addWidget(message);
myVBox->addLayout(crlfLayout);
myVBox->addLayout(trLayout);
myVBox->addLayout(ocLayout);
myVBox->addWidget(received_msg);
setLayout(myVBox);
qDebug("isOpen : %d", port->isOpen());
}
QespTest::~QespTest()
{
delete port;
port = NULL;
}
void QespTest::transmitMsg()
{
int i = port->write((message->text()).toAscii(),
(message->text()).length());
qDebug("trasmitted : %d", i);
}
void QespTest::receiveMsg()
{
char buff[1024];
int numBytes;
numBytes = port->bytesAvailable();
if(numBytes > 1024)
numBytes = 1024;
int i = port->read(buff, numBytes);
if (i != -1)
buff[i] = '\0';
else
buff[0] = '\0';
QString msg = buff;
received_msg->append(msg);
received_msg->ensureCursorVisible();
qDebug("bytes available: %d", numBytes);
qDebug("received: %d", i);
}
void QespTest::appendCR()
{
message->insert("\x0D");
}
void QespTest::appendLF()
{
message->insert("\x0A");
}
void QespTest::closePort()
{
port->close();
qDebug("is open: %d", port->isOpen());
}
void QespTest::openPort()
{
port->open(QIODevice::ReadWrite | QIODevice::Unbuffered);
qDebug("is open: %d", port->isOpen());
}
| C++ |
#ifndef PORTLISTENER_H_
#define PORTLISTENER_H_
#include <QObject>
#include "qextserialport.h"
class PortListener : public QObject
{
Q_OBJECT
public:
PortListener(const QString & portName);
private:
QextSerialPort *port;
private slots:
void onReadyRead();
void onDsrChanged(bool status);
};
#endif /*PORTLISTENER_H_*/
| C++ |
#include "PortListener.h"
#include <QtDebug>
PortListener::PortListener(const QString & portName)
{
qDebug() << "hi there";
this->port = new QextSerialPort(portName, QextSerialPort::EventDriven);
port->setBaudRate(BAUD56000);
port->setFlowControl(FLOW_OFF);
port->setParity(PAR_NONE);
port->setDataBits(DATA_8);
port->setStopBits(STOP_2);
if (port->open(QIODevice::ReadWrite) == true) {
connect(port, SIGNAL(readyRead()), this, SLOT(onReadyRead()));
connect(port, SIGNAL(dsrChanged(bool)), this, SLOT(onDsrChanged(bool)));
if (!(port->lineStatus() & LS_DSR))
qDebug() << "warning: device is not turned on";
qDebug() << "listening for data on" << port->portName();
}
else {
qDebug() << "device failed to open:" << port->errorString();
}
}
void PortListener::onReadyRead()
{
QByteArray bytes;
int a = port->bytesAvailable();
bytes.resize(a);
port->read(bytes.data(), bytes.size());
qDebug() << "bytes read:" << bytes.size();
qDebug() << "bytes:" << bytes;
}
void PortListener::onDsrChanged(bool status)
{
if (status)
qDebug() << "device was turned on";
else
qDebug() << "device was turned off";
}
| C++ |
/**
* @file main.cpp
* @brief Main file.
* @author Michal Policht
*/
#include <QCoreApplication>
#include "PortListener.h"
int main(int argc, char *argv[])
{
QCoreApplication app(argc, argv);
QString portName = "COM1"; // update this to use your port of choice
PortListener *listener = new PortListener(portName); // signals get hooked up internally
// start the event loop and wait for signals
return app.exec();
}
| C++ |
/**
* @file main.cpp
* @brief Main file.
* @author Michał Policht
*/
#include <qextserialenumerator.h>
#include <QList>
#include <QtDebug>
int main(int argc, char *argv[])
{
(void)argc;
(void)argv;
QList<QextPortInfo> ports = QextSerialEnumerator::getPorts();
qDebug() << "List of ports:";
for (int i = 0; i < ports.size(); i++) {
qDebug() << "port name:" << ports.at(i).portName;
qDebug() << "friendly name:" << ports.at(i).friendName;
qDebug() << "physical name:" << ports.at(i).physName;
qDebug() << "enumerator name:" << ports.at(i).enumName;
qDebug() << "vendor ID:" << QString::number(ports.at(i).vendorID, 16);
qDebug() << "product ID:" << QString::number(ports.at(i).productID, 16);
qDebug() << "===================================";
}
return EXIT_SUCCESS;
}
| C++ |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include <comdef.h>
#include "ffactivex.h"
#include "scriptable.h"
#include "axhost.h"
#ifdef NO_REGISTRY_AUTHORIZE
static const char *WellKnownProgIds[] = {
NULL
};
static const char *WellKnownClsIds[] = {
NULL
};
#endif
static const bool AcceptOnlyWellKnown = false;
static const bool TrustWellKnown = true;
static bool
isWellKnownProgId(const char *progid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!progid) {
return false;
}
while (WellKnownProgIds[i]) {
if (!strnicmp(WellKnownProgIds[i], progid, strlen(WellKnownProgIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static bool
isWellKnownClsId(const char *clsid)
{
#ifdef NO_REGISTRY_AUTHORIZE
unsigned int i = 0;
if (!clsid) {
return false;
}
while (WellKnownClsIds[i]) {
if (!strnicmp(WellKnownClsIds[i], clsid, strlen(WellKnownClsIds[i])))
return true;
++i;
}
return false;
#else
return true;
#endif
}
static LRESULT CALLBACK AxHostWinProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
LRESULT result;
CAxHost *host = (CAxHost *)GetWindowLong(hWnd, GWL_USERDATA);
if (!host) {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
switch (msg)
{
case WM_SETFOCUS:
case WM_KILLFOCUS:
case WM_SIZE:
if (host->Site) {
host->Site->OnDefWindowMessage(msg, wParam, lParam, &result);
return result;
}
else {
return DefWindowProc(hWnd, msg, wParam, lParam);
}
// Window being destroyed
case WM_DESTROY:
break;
default:
return DefWindowProc(hWnd, msg, wParam, lParam);
}
return true;
}
CAxHost::~CAxHost()
{
log(instance, 0, "AxHost.~AXHost: destroying the control...");
if (Window){
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
if (Sink) {
Sink->UnsubscribeFromEvents();
Sink->Release();
}
if (Site) {
Site->Detach();
Site->Release();
}
CoFreeUnusedLibraries();
}
CAxHost::CAxHost(NPP inst):
instance(inst),
ClsID(CLSID_NULL),
isValidClsID(false),
Sink(NULL),
Site(NULL),
Window(NULL),
OldProc(NULL),
Props(),
isKnown(false),
CodeBaseUrl(NULL)
{
}
void
CAxHost::setWindow(HWND win)
{
if (win != Window) {
if (win) {
// subclass window so we can intercept window messages and
// do our drawing to it
OldProc = (WNDPROC)::SetWindowLong(win, GWL_WNDPROC, (LONG)AxHostWinProc);
// associate window with our CAxHost object so we can access
// it in the window procedure
::SetWindowLong(win, GWL_USERDATA, (LONG)this);
}
else {
if (OldProc)
::SetWindowLong(Window, GWL_WNDPROC, (LONG)OldProc);
::SetWindowLong(Window, GWL_USERDATA, (LONG)NULL);
}
Window = win;
}
}
HWND
CAxHost::getWinfow()
{
return Window;
}
void
CAxHost::UpdateRect(RECT rcPos)
{
HRESULT hr = -1;
if (Site && Window) {
if (Site->GetParentWindow() == NULL) {
hr = Site->Attach(Window, rcPos, NULL);
if (FAILED(hr)) {
log(instance, 0, "AxHost.UpdateRect: failed to attach control");
}
}
else {
Site->SetPosition(rcPos);
}
// Ensure clipping on parent to keep child controls happy
::SetWindowLong(Window, GWL_STYLE, ::GetWindowLong(Window, GWL_STYLE) | WS_CLIPCHILDREN);
}
}
bool
CAxHost::verifyClsID(LPOLESTR oleClsID)
{
CRegKey keyExplorer;
if (ERROR_SUCCESS == keyExplorer.Open(HKEY_LOCAL_MACHINE,
_T("SOFTWARE\\Microsoft\\Internet Explorer\\ActiveX Compatibility"),
KEY_READ)) {
CRegKey keyCLSID;
if (ERROR_SUCCESS == keyCLSID.Open(keyExplorer, W2T(oleClsID), KEY_READ)) {
DWORD dwType = REG_DWORD;
DWORD dwFlags = 0;
DWORD dwBufSize = sizeof(dwFlags);
if (ERROR_SUCCESS == ::RegQueryValueEx(keyCLSID,
_T("Compatibility Flags"),
NULL,
&dwType,
(LPBYTE)
&dwFlags,
&dwBufSize)) {
// Flags for this reg key
const DWORD kKillBit = 0x00000400;
if (dwFlags & kKillBit) {
log(instance, 0, "AxHost.verifyClsID: the control is marked as unsafe by IE kill bits");
return false;
}
}
}
}
log(instance, 1, "AxHost.verifyClsID: verified successfully");
return true;
}
bool
CAxHost::setClsID(const char *clsid)
{
HRESULT hr = -1;
USES_CONVERSION;
LPOLESTR oleClsID = A2OLE(clsid);
if (isWellKnownClsId(clsid)) {
isKnown = true;
}
else if (AcceptOnlyWellKnown) {
log(instance, 0, "AxHost.setClsID: the requested CLSID is not on the Well Known list");
return false;
}
// Check the Internet Explorer list of vulnerable controls
if (oleClsID && verifyClsID(oleClsID)) {
hr = CLSIDFromString(oleClsID, &ClsID);
if (SUCCEEDED(hr) && !::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
log(instance, 1, "AxHost.setClsID: CLSID %s set", clsid);
return true;
}
}
log(instance, 0, "AxHost.setClsID: failed to set the requested clsid");
return false;
}
void CAxHost::setCodeBaseUrl(LPCWSTR codeBaseUrl)
{
CodeBaseUrl = codeBaseUrl;
}
bool
CAxHost::setClsIDFromProgID(const char *progid)
{
HRESULT hr = -1;
CLSID clsid = CLSID_NULL;
USES_CONVERSION;
LPOLESTR oleClsID = NULL;
LPOLESTR oleProgID = A2OLE(progid);
if (AcceptOnlyWellKnown) {
if (isWellKnownProgId(progid)) {
isKnown = true;
}
else {
log(instance, 0, "AxHost.setClsIDFromProgID: the requested PROGID is not on the Well Known list");
return false;
}
}
hr = CLSIDFromProgID(oleProgID, &clsid);
if (FAILED(hr)) {
log(instance, 0, "AxHost.setClsIDFromProgID: could not resolve PROGID");
return false;
}
hr = StringFromCLSID(clsid, &oleClsID);
// Check the Internet Explorer list of vulnerable controls
if ( SUCCEEDED(hr)
&& oleClsID
&& verifyClsID(oleClsID)) {
ClsID = clsid;
if (!::IsEqualCLSID(ClsID, CLSID_NULL)) {
isValidClsID = true;
log(instance, 1, "AxHost.setClsIDFromProgID: PROGID %s resolved and set", progid);
return true;
}
}
log(instance, 0, "AxHost.setClsIDFromProgID: failed to set the resolved CLSID");
return false;
}
bool
CAxHost::hasValidClsID()
{
return isValidClsID;
}
bool
CAxHost::CreateControl(bool subscribeToEvents)
{
if (!isValidClsID) {
log(instance, 0, "AxHost.CreateControl: current location is not trusted");
return false;
}
// Create the control site
CControlSiteInstance::CreateInstance(&Site);
if (Site == NULL) {
log(instance, 0, "AxHost.CreateControl: CreateInstance failed");
return false;
}
Site->m_bSupportWindowlessActivation = false;
if (TrustWellKnown && isKnown) {
Site->SetSecurityPolicy(NULL);
Site->m_bSafeForScriptingObjectsOnly = false;
}
else {
Site->m_bSafeForScriptingObjectsOnly = true;
}
Site->AddRef();
// Create the object
HRESULT hr;
hr = Site->Create(ClsID, Props, CodeBaseUrl);
if (FAILED(hr)) {
LPSTR lpMsgBuf;
DWORD dw = GetLastError();
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL );
log(instance, 0, lpMsgBuf);
log(instance, 0, "AxHost.CreateControl: failed to create site");
return false;
}
IUnknown *control = NULL;
Site->GetControlUnknown(&control);
if (!control) {
log(instance, 0, "AxHost.CreateControl: failed to create control (was it just downloaded?)");
return false;
}
// Create the event sink
CControlEventSinkInstance::CreateInstance(&Sink);
Sink->AddRef();
Sink->instance = instance;
hr = Sink->SubscribeToEvents(control);
control->Release();
if (FAILED(hr) && subscribeToEvents) {
LPSTR lpMsgBuf;
DWORD dw = GetLastError();
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
dw,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPSTR) &lpMsgBuf,
0,
NULL );
log(instance, 0, lpMsgBuf);
log(instance, 0, "AxHost.CreateControl: SubscribeToEvents failed");
return false;
}
log(instance, 1, "AxHost.CreateControl: control created successfully");
return true;
}
bool
CAxHost::AddEventHandler(wchar_t *name, wchar_t *handler)
{
HRESULT hr;
DISPID id = 0;
USES_CONVERSION;
LPOLESTR oleName = name;
if (!Sink) {
log(instance, 0, "AxHost.AddEventHandler: no valid sink");
return false;
}
hr = Sink->m_spEventSinkTypeInfo->GetIDsOfNames(&oleName, 1, &id);
if (FAILED(hr)) {
log(instance, 0, "AxHost.AddEventHandler: GetIDsOfNames failed to resolve event name");
return false;
}
Sink->events[id] = handler;
log(instance, 1, "AxHost.AddEventHandler: handler %S set for event %S", handler, name);
return true;
}
int16
CAxHost::HandleEvent(void *event)
{
NPEvent *npEvent = (NPEvent *)event;
LRESULT result = 0;
if (!npEvent) {
return 0;
}
// forward all events to the hosted control
return (int16)Site->OnDefWindowMessage(npEvent->event, npEvent->wParam, npEvent->lParam, &result);
}
NPObject *
CAxHost::GetScriptableObject()
{
IUnknown *unk;
NPObject *obj = NPNFuncs.createobject(instance, &ScriptableNPClass);
Site->GetControlUnknown(&unk);
((Scriptable *)obj)->setControl(unk);
((Scriptable *)obj)->setInstance(instance);
return obj;
}
| C++ |
// stdafx.cpp : source file that includes just the standard includes
// ffactivex.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "stdafx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| C++ |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#pragma once
#include <atlbase.h>
#include <comdef.h>
#include <npapi.h>
#include <npfunctions.h>
#include <npruntime.h>
#include "variants.h"
extern NPNetscapeFuncs NPNFuncs;
extern NPClass ScriptableNPClass;
class Scriptable: public NPObject
{
private:
Scriptable(const Scriptable &);
// This method iterates all members of the current interface, looking for the member with the
// id of member_id. If not found within this interface, it will iterate all base interfaces
// recursively, until a match is found, or all the hierarchy was searched.
bool find_member(ITypeInfoPtr info, TYPEATTR *attr, DISPID member_id, unsigned int invKind) {
bool found = false;
unsigned int i = 0;
FUNCDESC *fDesc;
for (i = 0;
(i < attr->cFuncs)
&& !found;
++i) {
HRESULT hr = info->GetFuncDesc(i, &fDesc);
if ( SUCCEEDED(hr)
&& fDesc
&& (fDesc->memid == member_id)) {
if (invKind & fDesc->invkind)
found = true;
}
info->ReleaseFuncDesc(fDesc);
}
if (!found && (invKind & ~INVOKE_FUNC)) {
VARDESC *vDesc;
for (i = 0;
(i < attr->cVars)
&& !found;
++i) {
HRESULT hr = info->GetVarDesc(i, &vDesc);
if ( SUCCEEDED(hr)
&& vDesc
&& (vDesc->memid == member_id)) {
found = true;
}
info->ReleaseVarDesc(vDesc);
}
}
if (!found) {
// iterate inherited interfaces
HREFTYPE refType = NULL;
for (i = 0; (i < attr->cImplTypes) && !found; ++i) {
ITypeInfoPtr baseInfo;
TYPEATTR *baseAttr;
if (FAILED(info->GetRefTypeOfImplType(0, &refType))) {
continue;
}
if (FAILED(info->GetRefTypeInfo(refType, &baseInfo))) {
continue;
}
if (FAILED(baseInfo->GetTypeAttr(&baseAttr))) {
continue;
}
found = find_member(baseInfo, baseAttr, member_id, invKind);
baseInfo->ReleaseTypeAttr(baseAttr);
}
}
return found;
}
DISPID ResolveName(NPIdentifier name, unsigned int invKind) {
bool found = false;
DISPID dID = -1;
USES_CONVERSION;
if (!name || !invKind) {
return -1;
}
if (!NPNFuncs.identifierisstring(name)) {
return -1;
}
NPUTF8 *npname = NPNFuncs.utf8fromidentifier(name);
LPOLESTR oleName = A2W(npname);
IDispatchPtr disp = control.GetInterfacePtr();
if (!disp) {
return -1;
}
disp->GetIDsOfNames(IID_NULL, &oleName, 1, LOCALE_SYSTEM_DEFAULT, &dID);
if (dID != -1) {
ITypeInfoPtr info;
disp->GetTypeInfo(0, LOCALE_SYSTEM_DEFAULT, &info);
if (!info) {
return -1;
}
TYPEATTR *attr;
if (FAILED(info->GetTypeAttr(&attr))) {
return -1;
}
found = find_member(info, attr, dID, invKind);
info->ReleaseTypeAttr(attr);
}
return found ? dID : -1;
}
bool InvokeControl(DISPID id, WORD wFlags, DISPPARAMS *pDispParams, VARIANT *pVarResult) {
IDispatchPtr disp = control.GetInterfacePtr();
if (!disp) {
return false;
}
HRESULT hr = disp->Invoke(id, IID_NULL, LOCALE_SYSTEM_DEFAULT, wFlags, pDispParams, pVarResult, NULL, NULL);
return (SUCCEEDED(hr)) ? true : false;
}
IUnknownPtr control;
NPP instance;
bool invalid;
public:
Scriptable():
invalid(false),
control(NULL),
instance(NULL) {
}
~Scriptable() {control->Release();}
void setControl(IUnknown *unk) {control = unk;}
void setControl(IDispatch *disp) {disp->QueryInterface(IID_IUnknown, (void **)&control);}
void setInstance(NPP inst) {instance = inst;}
void Invalidate() {invalid = true;}
static bool _HasMethod(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasMethod(name);
}
static bool _Invoke(NPObject *npobj, NPIdentifier name,
const NPVariant *args, uint32_t argCount,
NPVariant *result) {
return ((Scriptable *)npobj)->Invoke(name, args, argCount, result);
}
static bool _HasProperty(NPObject *npobj, NPIdentifier name) {
return ((Scriptable *)npobj)->HasProperty(name);
}
static bool _GetProperty(NPObject *npobj, NPIdentifier name, NPVariant *result) {
return ((Scriptable *)npobj)->GetProperty(name, result);
}
static bool _SetProperty(NPObject *npobj, NPIdentifier name, const NPVariant *value) {
return ((Scriptable *)npobj)->SetProperty(name, value);
}
bool HasMethod(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
return (id != -1) ? true : false;
}
bool Invoke(NPIdentifier name, const NPVariant *args, uint32_t argCount, NPVariant *result) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_FUNC);
if (-1 == id) {
return false;
}
VARIANT *vArgs = NULL;
if (argCount) {
vArgs = new VARIANT[argCount];
if (!vArgs) {
return false;
}
for (unsigned int i = 0; i < argCount; ++i) {
// copy the arguments in reverse order
NPVar2Variant(&args[i], &vArgs[argCount - i - 1], instance);
}
}
DISPPARAMS params = {NULL, NULL, 0, 0};
params.cArgs = argCount;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = vArgs;
VARIANT vResult;
bool rc = InvokeControl(id, DISPATCH_METHOD, ¶ms, &vResult);
if (vArgs) delete[] vArgs;
if (!rc) {
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool HasProperty(NPIdentifier name) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET | INVOKE_PROPERTYPUT);
return (id != -1) ? true : false;
}
bool GetProperty(NPIdentifier name, NPVariant *result) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYGET);
if (-1 == id) {
return false;
}
DISPPARAMS params;
params.cArgs = 0;
params.cNamedArgs = 0;
params.rgdispidNamedArgs = NULL;
params.rgvarg = NULL;
VARIANT vResult;
if (!InvokeControl(id, DISPATCH_PROPERTYGET, ¶ms, &vResult)) {
return false;
}
Variant2NPVar(&vResult, result, instance);
return true;
}
bool SetProperty(NPIdentifier name, const NPVariant *value) {
if (invalid) return false;
DISPID id = ResolveName(name, INVOKE_PROPERTYPUT);
if (-1 == id) {
return false;
}
VARIANT val;
NPVar2Variant(value, &val, instance);
DISPPARAMS params;
// Special initialization needed when using propery put.
DISPID dispidNamed = DISPID_PROPERTYPUT;
params.cNamedArgs = 1;
params.rgdispidNamedArgs = &dispidNamed;
params.cArgs = 1;
params.rgvarg = &val;
VARIANT vResult;
if (!InvokeControl(id, DISPATCH_PROPERTYPUT, ¶ms, &vResult)) {
return false;
}
return true;
}
};
| C++ |
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is itstructures.com code.
*
* The Initial Developer of the Original Code is IT Structures.
* Portions created by the Initial Developer are Copyright (C) 2008
* the Initial Developer. All Rights Reserved.
*
* Contributor:
* Ruediger Jungbeck <ruediger.jungbeck@rsj.de>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
// dllmain.cpp : Defines the entry point for the DLL application.
#include "ffactivex.h"
#include "axhost.h"
CComModule _Module;
NPNetscapeFuncs NPNFuncs;
BOOL APIENTRY DllMain( HMODULE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved
)
{
switch (ul_reason_for_call)
{
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
// ==============================
// ! Scriptability related code !
// ==============================
//
// here the plugin is asked by Mozilla to tell if it is scriptable
// we should return a valid interface id and a pointer to
// nsScriptablePeer interface which we should have implemented
// and which should be defined in the corressponding *.xpt file
// in the bin/components folder
NPError NPP_GetValue(NPP instance, NPPVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
if(instance == NULL)
return NPERR_GENERIC_ERROR;
CAxHost *host = (CAxHost *)instance->pdata;
if(host == NULL)
return NPERR_GENERIC_ERROR;
switch (variable) {
case NPPVpluginNameString:
*((char **)value) = "ITSTActiveX";
break;
case NPPVpluginDescriptionString:
*((char **)value) = "IT Structures ActiveX for Firefox";
break;
case NPPVpluginScriptableNPObject:
*(NPObject **)value = host->GetScriptableObject();
break;
default:
rv = NPERR_GENERIC_ERROR;
}
return rv;
}
NPError NPP_NewStream(NPP instance,
NPMIMEType type,
NPStream* stream,
NPBool seekable,
uint16* stype)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int32_t NPP_WriteReady (NPP instance, NPStream *stream)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = 0x0fffffff;
return rv;
}
int32_t NPP_Write (NPP instance, NPStream *stream, int32_t offset, int32_t len, void *buffer)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
int32 rv = len;
return rv;
}
NPError NPP_DestroyStream (NPP instance, NPStream *stream, NPError reason)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
void NPP_StreamAsFile (NPP instance, NPStream* stream, const char* fname)
{
if(instance == NULL)
return;
}
void NPP_Print (NPP instance, NPPrint* printInfo)
{
if(instance == NULL)
return;
}
void NPP_URLNotify(NPP instance, const char* url, NPReason reason, void* notifyData)
{
if(instance == NULL)
return;
}
NPError NPP_SetValue(NPP instance, NPNVariable variable, void *value)
{
if(instance == NULL)
return NPERR_INVALID_INSTANCE_ERROR;
NPError rv = NPERR_NO_ERROR;
return rv;
}
int16 NPP_HandleEvent(NPP instance, void* event)
{
if(instance == NULL)
return 0;
int16 rv = 0;
CAxHost *host = (CAxHost *)instance->pdata;
if (host)
rv = host->HandleEvent(event);
return rv;
}
NPError OSCALL NP_GetEntryPoints(NPPluginFuncs* pFuncs)
{
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
if(pFuncs->size < sizeof(NPPluginFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
pFuncs->version = (NP_VERSION_MAJOR << 8) | NP_VERSION_MINOR;
pFuncs->newp = NPP_New;
pFuncs->destroy = NPP_Destroy;
pFuncs->setwindow = NPP_SetWindow;
pFuncs->newstream = NPP_NewStream;
pFuncs->destroystream = NPP_DestroyStream;
pFuncs->asfile = NPP_StreamAsFile;
pFuncs->writeready = NPP_WriteReady;
pFuncs->write = NPP_Write;
pFuncs->print = NPP_Print;
pFuncs->event = NPP_HandleEvent;
pFuncs->urlnotify = NPP_URLNotify;
pFuncs->getvalue = NPP_GetValue;
pFuncs->setvalue = NPP_SetValue;
pFuncs->javaClass = NULL;
return NPERR_NO_ERROR;
}
#define MIN(x, y) ((x) < (y)) ? (x) : (y)
/*
* Initialize the plugin. Called the first time the browser comes across a
* MIME Type this plugin is registered to handle.
*/
NPError OSCALL NP_Initialize(NPNetscapeFuncs* pFuncs)
{
// _asm {int 3};
if(pFuncs == NULL)
return NPERR_INVALID_FUNCTABLE_ERROR;
#ifdef NDEF
// The following statements prevented usage of newer Mozilla sources than installed browser at runtime
if(HIBYTE(pFuncs->version) > NP_VERSION_MAJOR)
return NPERR_INCOMPATIBLE_VERSION_ERROR;
if(pFuncs->size < sizeof(NPNetscapeFuncs))
return NPERR_INVALID_FUNCTABLE_ERROR;
#endif
if (!AtlAxWinInit()) {
return NPERR_GENERIC_ERROR;
}
CoInitialize(NULL);
_pAtlModule = &_Module;
memset(&NPNFuncs, 0, sizeof(NPNetscapeFuncs));
memcpy(&NPNFuncs, pFuncs, MIN(pFuncs->size, sizeof(NPNetscapeFuncs)));
return NPERR_NO_ERROR;
}
/*
* Shutdown the plugin. Called when no more instanced of this plugin exist and
* the browser wants to unload it.
*/
NPError OSCALL NP_Shutdown(void)
{
AtlAxWinTerm();
return NPERR_NO_ERROR;
}
| C++ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.