git-svn-id: svn://db.shs.com.ru/pip@283 12ceb7fc-bf1f-11e4-8940-5bc7170c53b5

This commit is contained in:
2016-11-23 15:10:40 +00:00
parent 8f6e7d2cae
commit e66e78ac16
29 changed files with 973 additions and 973 deletions

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
C++ code parser C++ code parser
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "picodeparser.h" #include "picodeparser.h"
@@ -42,7 +42,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
} }
if (args.size() != arg_vals.size()) { if (args.size() != arg_vals.size()) {
piCout << ("Error: in expansion of macro \"" + name + "(" + args.join(", ") + ")\": expect") piCout << ("Error: in expansion of macro \"" + name + "(" + args.join(", ") + ")\": expect")
<< args.size() << "arguments but takes" << arg_vals.size() << "!"; << args.size() << "arguments but takes" << arg_vals.size() << "!";
if (ok != 0) *ok = false; if (ok != 0) *ok = false;
return PIString(); return PIString();
} }
@@ -54,7 +54,7 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
PIChar ppc(0), pc(0), nc(0); PIChar ppc(0), pc(0), nc(0);
if (ind > 1) ppc = ret[ind - 2]; if (ind > 1) ppc = ret[ind - 2];
if (ind > 0) pc = ret[ind - 1]; if (ind > 0) pc = ret[ind - 1];
if (ind + an.size_s() < ret.size_s()) nc = ret.mid(ind + an.size_s(),1)[0]; if (ind + an.size_s() < ret.size_s()) nc = ret.mid(ind + an.size_s(),1)[0];
if (ppc != '#' && pc == '#' && !_isCChar(nc)) { // to chars if (ppc != '#' && pc == '#' && !_isCChar(nc)) { // to chars
ind--; ind--;
ret.replace(ind, an.size_s() + 1, "\"" + av + "\""); ret.replace(ind, an.size_s() + 1, "\"" + av + "\"");
@@ -105,7 +105,7 @@ void PICodeParser::parseFile(const PIString & file, bool follow_includes) {
void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes) { void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes) {
clear(); clear();
piForeachC (PIString & f, files) piForeachC (PIString & f, files)
parseFileInternal(f, follow_includes); parseFileInternal(f, follow_includes);
/*piCout << "\n\nDefines:"; /*piCout << "\n\nDefines:";
piForeachC (Define & m, defines) piForeachC (Define & m, defines)
piCout << "define" << m.first << m.second; piCout << "define" << m.first << m.second;
@@ -126,7 +126,7 @@ void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes)
bool PICodeParser::isEnum(const PIString & name) { bool PICodeParser::isEnum(const PIString & name) {
piForeachC (Enum & e, enums) piForeachC (Enum & e, enums)
if (e.name == name) if (e.name == name)
return true; return true;
return false; return false;
} }
@@ -170,7 +170,7 @@ void PICodeParser::clear() {
cur_namespace.clear(); cur_namespace.clear();
main_file.clear(); main_file.clear();
evaluator.clearCustomVariables(); evaluator.clearCustomVariables();
cur_def_vis = Global; cur_def_vis = Global;
defines << Define("PICODE", "") << custom_defines; defines << Define("PICODE", "") << custom_defines;
} }
@@ -231,7 +231,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
while ((ind = pfc.find(d.first, ind + 1)) >= 0) { while ((ind = pfc.find(d.first, ind + 1)) >= 0) {
PIChar pc(0), nc(0); PIChar pc(0), nc(0);
if (ind > 0) pc = pfc[ind - 1]; if (ind > 0) pc = pfc[ind - 1];
if (ind + d.first.size_s() < pfc.size_s()) nc = pfc.mid(ind + d.first.size_s(),1)[0]; if (ind + d.first.size_s() < pfc.size_s()) nc = pfc.mid(ind + d.first.size_s(),1)[0];
if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue; if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue;
pfc.replace(ind, d.first.size_s(), d.second); pfc.replace(ind, d.first.size_s(), d.second);
ind -= d.first.size_s() - d.second.size_s(); ind -= d.first.size_s() - d.second.size_s();
@@ -243,7 +243,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
while ((ind = pfc.find(m.name, ind + 1)) >= 0) { while ((ind = pfc.find(m.name, ind + 1)) >= 0) {
PIChar pc(0), nc(0); PIChar pc(0), nc(0);
if (ind > 0) pc = pfc[ind - 1]; if (ind > 0) pc = pfc[ind - 1];
if (ind + m.name.size_s() < pfc.size_s()) nc = pfc.mid(ind + m.name.size_s(),1)[0]; if (ind + m.name.size_s() < pfc.size_s()) nc = pfc.mid(ind + m.name.size_s(),1)[0];
if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue; if (_isCChar(pc) || _isCChar(nc) || nc.isDigit()) continue;
PIString ret, range; bool ok(false); PIString ret, range; bool ok(false);
range = pfc.mid(ind + m.name.size_s()).takeRange("(", ")"); range = pfc.mid(ind + m.name.size_s()).takeRange("(", ")");
@@ -483,7 +483,7 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
int i = 0; int i = 0;
//piCout << me.arguments_full; //piCout << me.arguments_full;
piForeach (PIString & a, me.arguments_full) piForeach (PIString & a, me.arguments_full)
if ((i = a.find("=")) > 0) if ((i = a.find("=")) > 0)
a.cutRight(a.size_s() - i).trim(); a.cutRight(a.size_s() - i).trim();
for (int j = 0; j < me.arguments_full.size_s(); ++j) for (int j = 0; j < me.arguments_full.size_s(); ++j)
if (me.arguments_full[j] == "void") { if (me.arguments_full[j] == "void") {
@@ -596,21 +596,21 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
} }
} }
piForeachC (Enum & e, enums) piForeachC (Enum & e, enums)
if ((f = e.name.find(n)) >= 0) if ((f = e.name.find(n)) >= 0)
if (e.name.mid(f - 1, 1) == ":") if (e.name.mid(f - 1, 1) == ":")
if (e.name.find(cur_namespace) >= 0) { if (e.name.find(cur_namespace) >= 0) {
//piCout << "change" << n << "to" << e.name + suff; //piCout << "change" << n << "to" << e.name + suff;
n = pref + e.name + suff; n = pref + e.name + suff;
return; return;
} }
piForeachC (Typedef & e, typedefs) piForeachC (Typedef & e, typedefs)
if ((f = e.first.find(n)) >= 0) if ((f = e.first.find(n)) >= 0)
if (e.first.mid(f - 1, 1) == ":") if (e.first.mid(f - 1, 1) == ":")
if (e.first.find(cur_namespace) >= 0) { if (e.first.find(cur_namespace) >= 0) {
//piCout << "change" << n << "to" << e.name + suff; //piCout << "change" << n << "to" << e.name + suff;
n = pref + e.first + suff; n = pref + e.first + suff;
return; return;
} }
n = (pref + n + suff).trim(); n = (pref + n + suff).trim();
} }
@@ -669,8 +669,8 @@ double PICodeParser::procMacrosCond(PIString fc) {
//piCout << "oper" << oper << "with" << ce; //piCout << "oper" << oper << "with" << ce;
if (!br) brv = defineValue(ce); if (!br) brv = defineValue(ce);
switch (oper) { switch (oper) {
case 1: ret = ret && (neg ? -brv : brv); break; case 1: ret = ret && (neg ? -brv : brv); break;
case 2: ret = ret || (neg ? -brv : brv); break; case 2: ret = ret || (neg ? -brv : brv); break;
} }
} }
if (ps == fc.size_s()) fc.cutLeft(1); if (ps == fc.size_s()) fc.cutLeft(1);
@@ -702,7 +702,7 @@ double PICodeParser::defineValue(const PIString & dn) {
PICodeParser::Entity * PICodeParser::findEntityByName(const PIString & en) { PICodeParser::Entity * PICodeParser::findEntityByName(const PIString & en) {
piForeach (Entity * e, entities) piForeach (Entity * e, entities)
if (e->name == en) if (e->name == en)
return e; return e;
return 0; return 0;
} }

View File

@@ -2,22 +2,22 @@
* \brief C++ code parser * \brief C++ code parser
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
C++ code parser C++ code parser
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Console output/input Console output/input
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "piconsole.h" #include "piconsole.h"
@@ -38,7 +38,7 @@
* \section PIConsole_sec0 Synopsis * \section PIConsole_sec0 Synopsis
* This class provides output to console with automatic alignment and update. * This class provides output to console with automatic alignment and update.
* It supports tabs, keyboard listening, formats and colors. * It supports tabs, keyboard listening, formats and colors.
* *
* \section PIConsole_sec1 Layout * \section PIConsole_sec1 Layout
* %PIConsole works with variable pointers. You should add your variables with * %PIConsole works with variable pointers. You should add your variables with
* functions \a addVariable() which receives label name, pointer to variable * functions \a addVariable() which receives label name, pointer to variable
@@ -48,12 +48,12 @@
* filled from top to bottom, but you can add just string with function * filled from top to bottom, but you can add just string with function
* \a addString() or add empty line with function \a addEmptyLine(). Layout scheme: * \a addString() or add empty line with function \a addEmptyLine(). Layout scheme:
* \image html piconsole_layout.png * \image html piconsole_layout.png
* *
* \section PIConsole_sec2 Keyboard usage * \section PIConsole_sec2 Keyboard usage
* %PIConsole should to be single in application. %PIConsole aggregate PIKbdListener * %PIConsole should to be single in application. %PIConsole aggregate PIKbdListener
* which grab keyboard and automatic switch tabs by theirs bind keys. If there is no * which grab keyboard and automatic switch tabs by theirs bind keys. If there is no
* tab binded to pressed key external function "slot" will be called * tab binded to pressed key external function "slot" will be called
* *
**/ **/
@@ -62,14 +62,14 @@ extern PIMutex __PICout_mutex__;
PRIVATE_DEFINITION_START(PIConsole) PRIVATE_DEFINITION_START(PIConsole)
#ifdef WINDOWS #ifdef WINDOWS
void getWinCurCoord() {GetConsoleScreenBufferInfo(hOut, &csbi); ccoord = csbi.dwCursorPosition;} void getWinCurCoord() {GetConsoleScreenBufferInfo(hOut, &csbi); ccoord = csbi.dwCursorPosition;}
COORD & getWinCoord(int dx = 0, int dy = 0) {getWinCurCoord(); ccoord.X += dx; ccoord.Y += dy; return ccoord;} COORD & getWinCoord(int dx = 0, int dy = 0) {getWinCurCoord(); ccoord.X += dx; ccoord.Y += dy; return ccoord;}
void * hOut; void * hOut;
CONSOLE_SCREEN_BUFFER_INFO sbi, csbi; CONSOLE_SCREEN_BUFFER_INFO sbi, csbi;
CONSOLE_CURSOR_INFO curinfo; CONSOLE_CURSOR_INFO curinfo;
COORD ccoord, ulcoord; COORD ccoord, ulcoord;
WORD dattr; WORD dattr;
DWORD smode, written; DWORD smode, written;
#endif #endif
PRIVATE_DEFINITION_END(PIConsole) PRIVATE_DEFINITION_END(PIConsole)
@@ -416,7 +416,7 @@ inline int PIConsole::couts(const double v) {
} }
inline int PIConsole::couts(const PISystemTime & v) { inline int PIConsole::couts(const PISystemTime & v) {
switch (systime_format) {case (1): return printf("%.6lg", v.toSeconds()); break; switch (systime_format) {case (1): return printf("%.6lg", v.toSeconds()); break;
default: return couts(v.seconds) + printf(" s, ") + couts(v.nanoseconds) + printf(" ns"); break;} default: return couts(v.seconds) + printf(" s, ") + couts(v.nanoseconds) + printf(" ns"); break;}
} }
@@ -426,7 +426,7 @@ void PIConsole::moveRight(int n) {SetConsoleCursorPosition(PRIVATE->hOut, PRIVAT
void PIConsole::moveLeft(int n) {SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->getWinCoord(-n));} void PIConsole::moveLeft(int n) {SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->getWinCoord(-n));}
void PIConsole::moveTo(int x, int y) {PRIVATE->ccoord.X = x; PRIVATE->ccoord.Y = PRIVATE->ulcoord.Y + y; SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->ccoord);} void PIConsole::moveTo(int x, int y) {PRIVATE->ccoord.X = x; PRIVATE->ccoord.Y = PRIVATE->ulcoord.Y + y; SetConsoleCursorPosition(PRIVATE->hOut, PRIVATE->ccoord);}
void PIConsole::clearScreen() {couts(fstr(Normal)); toUpperLeft(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written); void PIConsole::clearScreen() {couts(fstr(Normal)); toUpperLeft(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written);
FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written);} FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * (height + 1), PRIVATE->ulcoord, &PRIVATE->written);}
void PIConsole::clearScreenLower() {couts(fstr(Normal)); PRIVATE->getWinCurCoord(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written); void PIConsole::clearScreenLower() {couts(fstr(Normal)); PRIVATE->getWinCurCoord(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);} FillConsoleOutputCharacter(PRIVATE->hOut, ' ', width * height - width * PRIVATE->ccoord.Y + PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);}
void PIConsole::clearLine() {PRIVATE->getWinCurCoord(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width - PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written); void PIConsole::clearLine() {PRIVATE->getWinCurCoord(); FillConsoleOutputAttribute(PRIVATE->hOut, PRIVATE->dattr, width - PRIVATE->ccoord.X, PRIVATE->ccoord, &PRIVATE->written);
@@ -480,51 +480,51 @@ void PIConsole::run() {
toUpperLeft(); toUpperLeft();
if (max_y < cvars.size()) max_y = cvars.size(); if (max_y < cvars.size()) max_y = cvars.size();
j = 0; j = 0;
piForeachC (Variable & tv_, cvars) { piForeachC (Variable & tv_, cvars) {
if (j > height - 3) continue; if (j > height - 3) continue;
j++; j++;
moveRight(cx); moveRight(cx);
if (tv_.type == 15) { if (tv_.type == 15) {
newLine(); newLine();
continue; continue;
} }
moveRight(tv_.offset); moveRight(tv_.offset);
const void * ptr = 0; const void * ptr = 0;
if (tv_.remote) { if (tv_.remote) {
if (tv_.type == 0) { if (tv_.type == 0) {
rstr.clear(); rstr.clear();
rba = tv_.rdata; rba = tv_.rdata;
rba >> rstr; rba >> rstr;
rstr.trim(); rstr.trim();
ptr = &rstr; ptr = &rstr;
} else } else
ptr = tv_.rdata.data(); ptr = tv_.rdata.data();
} else } else
ptr = tv_.ptr; ptr = tv_.ptr;
switch (tv_.type) { switch (tv_.type) {
case 0: clen = printValue(ptr != 0 ? *(const PIString*)ptr : PIString(), tv_.format); break; case 0: clen = printValue(ptr != 0 ? *(const PIString*)ptr : PIString(), tv_.format); break;
case 1: clen = printValue(ptr != 0 ? *(const bool*)ptr : false, tv_.format); break; case 1: clen = printValue(ptr != 0 ? *(const bool*)ptr : false, tv_.format); break;
case 2: clen = printValue(ptr != 0 ? *(const int*)ptr : 0, tv_.format); break; case 2: clen = printValue(ptr != 0 ? *(const int*)ptr : 0, tv_.format); break;
case 3: clen = printValue(ptr != 0 ? *(const long*)ptr : 0l, tv_.format); break; case 3: clen = printValue(ptr != 0 ? *(const long*)ptr : 0l, tv_.format); break;
case 4: clen = printValue(ptr != 0 ? *(const char*)ptr : char(0), tv_.format); break; case 4: clen = printValue(ptr != 0 ? *(const char*)ptr : char(0), tv_.format); break;
case 5: clen = printValue(ptr != 0 ? *(const float*)ptr : 0.f, tv_.format); break; case 5: clen = printValue(ptr != 0 ? *(const float*)ptr : 0.f, tv_.format); break;
case 6: clen = printValue(ptr != 0 ? *(const double*)ptr : 0., tv_.format); break; case 6: clen = printValue(ptr != 0 ? *(const double*)ptr : 0., tv_.format); break;
case 7: clen = printValue(ptr != 0 ? *(const short*)ptr : short(0), tv_.format); break; case 7: clen = printValue(ptr != 0 ? *(const short*)ptr : short(0), tv_.format); break;
case 8: clen = printValue(ptr != 0 ? *(const uint*)ptr : 0u, tv_.format); break; case 8: clen = printValue(ptr != 0 ? *(const uint*)ptr : 0u, tv_.format); break;
case 9: clen = printValue(ptr != 0 ? *(const ulong*)ptr : 0ul, tv_.format); break; case 9: clen = printValue(ptr != 0 ? *(const ulong*)ptr : 0ul, tv_.format); break;
case 10: clen = printValue(ptr != 0 ? *(const ushort*)ptr : ushort(0), tv_.format); break; case 10: clen = printValue(ptr != 0 ? *(const ushort*)ptr : ushort(0), tv_.format); break;
case 11: clen = printValue(ptr != 0 ? *(const uchar*)ptr : uchar(0), tv_.format); break; case 11: clen = printValue(ptr != 0 ? *(const uchar*)ptr : uchar(0), tv_.format); break;
case 12: clen = printValue(ptr != 0 ? *(const llong*)ptr : 0l, tv_.format); break; case 12: clen = printValue(ptr != 0 ? *(const llong*)ptr : 0l, tv_.format); break;
case 13: clen = printValue(ptr != 0 ? *(const ullong*)ptr: 0ull, tv_.format); break; case 13: clen = printValue(ptr != 0 ? *(const ullong*)ptr: 0ull, tv_.format); break;
case 20: clen = printValue(ptr != 0 ? *(const PISystemTime*)ptr: PISystemTime(), tv_.format); break; case 20: clen = printValue(ptr != 0 ? *(const PISystemTime*)ptr: PISystemTime(), tv_.format); break;
case 14: clen = printValue(bitsValue(ptr, tv_.bitFrom, tv_.bitCount), tv_.format); break; case 14: clen = printValue(bitsValue(ptr, tv_.bitFrom, tv_.bitCount), tv_.format); break;
} }
if (clen + tv_.offset < (uint)col_wid) { if (clen + tv_.offset < (uint)col_wid) {
PIString ts = PIString( PIString ts = PIString(
#if defined(QNX) || defined(FREE_BSD) #if defined(QNX) || defined(FREE_BSD)
col_wid - clen - tv_.offset - 1, ' '); col_wid - clen - tv_.offset - 1, ' ');
#else #else
col_wid - clen - tv_.offset, ' '); col_wid - clen - tv_.offset, ' ');
#endif #endif
printf("%s", ts.data()); printf("%s", ts.data());
} }
@@ -563,9 +563,9 @@ void PIConsole::fillLabels() {
if (ccol.alignment != Nothing) { if (ccol.alignment != Nothing) {
mx = 0; mx = 0;
piForeachC (Variable & j, cvars) piForeachC (Variable & j, cvars)
if (!j.isEmpty()) if (!j.isEmpty())
if (mx < j.name.size()) if (mx < j.name.size())
mx = j.name.size(); mx = j.name.size();
mx += 2; mx += 2;
} }
cx = col_wid * i; cx = col_wid * i;
@@ -575,10 +575,10 @@ void PIConsole::fillLabels() {
if (int(j) > height - 3) continue; if (int(j) > height - 3) continue;
if (max_y < j) max_y = j; if (max_y < j) max_y = j;
moveRight(cx); moveRight(cx);
Variable & tv_(cvars[j]); Variable & tv_(cvars[j]);
cvars[j].nx = cx; cvars[j].nx = cx;
cvars[j].ny = cy; cvars[j].ny = cy;
if (tv_.name.isEmpty()) { if (tv_.name.isEmpty()) {
cvars[j].offset = 0; cvars[j].offset = 0;
clearLine(); clearLine();
newLine(); newLine();
@@ -586,34 +586,34 @@ void PIConsole::fillLabels() {
continue; continue;
} }
clearLine(); clearLine();
//piCout << tv_.name << tv_.type << tv_.ptr; //piCout << tv_.name << tv_.type << tv_.ptr;
if (tv_.type == 15) { if (tv_.type == 15) {
cvars[j].offset = cvars[j].name.length(); cvars[j].offset = cvars[j].name.length();
cvars[j].nx += cvars[j].offset; cvars[j].nx += cvars[j].offset;
printLine(tv_.name, cx, tv_.format); printLine(tv_.name, cx, tv_.format);
newLine(); newLine();
cy++; cy++;
continue; continue;
} }
if (!tv_.isEmpty()) { if (!tv_.isEmpty()) {
switch (ccol.alignment) { switch (ccol.alignment) {
case Nothing: case Nothing:
cvars[j].offset = (tv_.name + ": ").length(); cvars[j].offset = (tv_.name + ": ").length();
cvars[j].nx += cvars[j].offset; cvars[j].nx += cvars[j].offset;
printValue(tv_.name + ": ", tv_.format); printValue(tv_.name + ": ", tv_.format);
break; break;
case Left: case Left:
cvars[j].offset = mx; cvars[j].offset = mx;
cvars[j].nx += cvars[j].offset; cvars[j].nx += cvars[j].offset;
printValue(tv_.name + ": ", tv_.format); printValue(tv_.name + ": ", tv_.format);
break; break;
case Right: case Right:
cvars[j].offset = mx; cvars[j].offset = mx;
cvars[j].nx += cvars[j].offset; cvars[j].nx += cvars[j].offset;
dx = mx - (tv_.name + ": ").length(); dx = mx - (tv_.name + ": ").length();
moveRight(dx); moveRight(dx);
printValue(tv_.name + ": ", tv_.format); printValue(tv_.name + ": ", tv_.format);
moveLeft(dx); moveLeft(dx);
break; break;
} }
} }
@@ -827,9 +827,9 @@ PIString PIConsole::getString(int x, int y) {
PIString PIConsole::getString(const PIString & name) { PIString PIConsole::getString(const PIString & name) {
piForeachC (Column & i, tabs[cur_tab].columns) piForeachC (Column & i, tabs[cur_tab].columns)
piForeachC (Variable & j, i.variables) piForeachC (Variable & j, i.variables)
if (j.name == name) if (j.name == name)
return getString(j.nx + 1, j.ny); return getString(j.nx + 1, j.ny);
return PIString(); return PIString();
} }
@@ -949,29 +949,29 @@ void PIConsole::serverSendData() {
PIByteArray ba; PIByteArray ba;
PIVector<VariableContent> content; PIVector<VariableContent> content;
piForeach (Tab & t, tabs) piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns) piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables) piForeach (Variable & v, c.variables)
if (!v.isEmpty() && v.id > 0) { if (!v.isEmpty() && v.id > 0) {
VariableContent vc; VariableContent vc;
vc.id = v.id; vc.id = v.id;
v.writeData(vc.rdata); v.writeData(vc.rdata);
content << vc; content << vc;
} }
piForeach (RemoteClient & rc, remote_clients) { piForeach (RemoteClient & rc, remote_clients) {
ba.clear(); ba.clear();
switch (rc.state) { switch (rc.state) {
case FetchingData: case FetchingData:
ba << int(0xCC) << tabs; ba << int(0xCC) << tabs;
//piCout << "server send const data" << rc.name << ba.size_s(); //piCout << "server send const data" << rc.name << ba.size_s();
break; break;
case Committing: case Committing:
ba << int(0xDD); ba << int(0xDD);
break; break;
case Connected: case Connected:
ba << int(0xEE) << content; ba << int(0xEE) << content;
//piCout << "send data" << ba.size(); //piCout << "send data" << ba.size();
break; break;
default: break; default: break;
} }
if (!ba.isEmpty()) if (!ba.isEmpty())
peer->send(rc.name, ba); peer->send(rc.name, ba);
@@ -981,7 +981,7 @@ void PIConsole::serverSendData() {
PIConsole::RemoteClient & PIConsole::remoteClient(const PIString & fname) { PIConsole::RemoteClient & PIConsole::remoteClient(const PIString & fname) {
piForeach (RemoteClient & i, remote_clients) piForeach (RemoteClient & i, remote_clients)
if (i.name == fname) if (i.name == fname)
return i; return i;
remote_clients << RemoteClient(fname); remote_clients << RemoteClient(fname);
return remote_clients.back(); return remote_clients.back();
@@ -998,17 +998,17 @@ void PIConsole::peerReceived(const PIString & from, const PIByteArray & data) {
//PIString rcn = from.right(from.length() - 6); //PIString rcn = from.right(from.length() - 6);
RemoteClient & rc(remoteClient(from)); RemoteClient & rc(remoteClient(from));
switch (type) { switch (type) {
case 0xBB: // fetch const data request case 0xBB: // fetch const data request
//piCout << "fetch data request from" << from << rc.state; //piCout << "fetch data request from" << from << rc.state;
if (rc.state != Connected) if (rc.state != Connected)
rc.state = FetchingData; rc.state = FetchingData;
break; break;
case 0xCC: // const data commit case 0xCC: // const data commit
//piCout << "commit from" << from; //piCout << "commit from" << from;
if (rc.state != Connected) if (rc.state != Connected)
rc.state = Connected; rc.state = Connected;
break; break;
default: break; default: break;
} }
} else { } else {
PIVector<VariableContent> content; PIVector<VariableContent> content;
@@ -1016,40 +1016,40 @@ void PIConsole::peerReceived(const PIString & from, const PIByteArray & data) {
if (from.left(5) != "_rcs_") return; if (from.left(5) != "_rcs_") return;
//PIString rcn = from.right(from.length() - 6); //PIString rcn = from.right(from.length() - 6);
switch (type) { switch (type) {
case 0xAA: // new server case 0xAA: // new server
//piCout << "new server" << rcn; //piCout << "new server" << rcn;
break; break;
case 0xCC: // const data case 0xCC: // const data
//piCout << "received const data"; //piCout << "received const data";
state = Committing; state = Committing;
ba >> tabs; ba >> tabs;
cur_tab = tabs.isEmpty() ? -1 : 0; cur_tab = tabs.isEmpty() ? -1 : 0;
piForeach (Tab & t, tabs) piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns) piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables) piForeach (Variable & v, c.variables)
v.remote = true; v.remote = true;
break; break;
case 0xDD: // const data commit case 0xDD: // const data commit
//piCout << "received commit"; //piCout << "received commit";
state = Connected; state = Connected;
break; break;
case 0xEE: // dynamic data case 0xEE: // dynamic data
//piCout << "received data" << ba.size_s(); //piCout << "received data" << ba.size_s();
piForeach (Tab & t, tabs) piForeach (Tab & t, tabs)
piForeach (Column & c, t.columns) piForeach (Column & c, t.columns)
piForeach (Variable & v, c.variables) piForeach (Variable & v, c.variables)
if (!v.isEmpty() && v.id > 0) if (!v.isEmpty() && v.id > 0)
vids[v.id] = &v; vids[v.id] = &v;
ba >> content; ba >> content;
piForeach (VariableContent & vc, content) { piForeach (VariableContent & vc, content) {
if (vc.id <= 0) continue; if (vc.id <= 0) continue;
Variable * v = vids.at(vc.id); Variable * v = vids.at(vc.id);
if (v == 0) continue; if (v == 0) continue;
//piCout << "read" << v->name << vc.rdata.size_s(); //piCout << "read" << v->name << vc.rdata.size_s();
v->rdata = vc.rdata; v->rdata = vc.rdata;
} }
break; break;
default: break; default: break;
} }
} }
} }
@@ -1069,29 +1069,29 @@ void PIConsole::peerTimer(void * data, int delim) {
if (p == 0) return; if (p == 0) return;
PIByteArray ba; PIByteArray ba;
switch (state) { switch (state) {
case Disconnected: case Disconnected:
peer_tm.reset(); peer_tm.reset();
ba << int(0xBB); ba << int(0xBB);
//piCout << "send to" << server_name << "fetch request disc"; //piCout << "send to" << server_name << "fetch request disc";
peer->send(p, ba); peer->send(p, ba);
state = FetchingData; state = FetchingData;
break; break;
case FetchingData: case FetchingData:
if (peer_tm.elapsed_s() < 3.) if (peer_tm.elapsed_s() < 3.)
return; return;
peer_tm.reset(); peer_tm.reset();
ba << int(0xBB); ba << int(0xBB);
//piCout << "send to" << server_name << "fetch request fd"; //piCout << "send to" << server_name << "fetch request fd";
peer->send(p, ba); peer->send(p, ba);
break; break;
case Committing: case Committing:
peer_tm.reset(); peer_tm.reset();
ba << int(0xCC); ba << int(0xCC);
//piCout << "send to" << server_name << "committing"; //piCout << "send to" << server_name << "committing";
state = Connected; state = Connected;
peer->send(p, ba); peer->send(p, ba);
break; break;
default: break; default: break;
}; };
} }
} }

View File

@@ -2,22 +2,22 @@
* \brief Console output class * \brief Console output class
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Console output/input Console output/input
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PICONSOLE_H #ifndef PICONSOLE_H
@@ -35,13 +35,13 @@ class PIP_EXPORT PIConsole: public PIThread
{ {
PIOBJECT_SUBCLASS(PIConsole, PIThread) PIOBJECT_SUBCLASS(PIConsole, PIThread)
public: public:
//! Constructs %PIConsole with key handler "slot" and if "startNow" start it //! Constructs %PIConsole with key handler "slot" and if "startNow" start it
explicit PIConsole(bool startNow = true, PIKbdListener::KBFunc slot = 0); explicit PIConsole(bool startNow = true, PIKbdListener::KBFunc slot = 0);
~PIConsole(); ~PIConsole();
//! Variables output format //! Variables output format
enum Format { enum Format {
Normal /** Default console format */ = 0x01, Normal /** Default console format */ = 0x01,
@@ -75,74 +75,74 @@ public:
SystemTimeSplit /** PISystemTime split representation (* s, * ns) */ = 0x20000000, SystemTimeSplit /** PISystemTime split representation (* s, * ns) */ = 0x20000000,
SystemTimeSeconds /** PISystemTime seconds representation (*.* s) */ = 0x40000000 SystemTimeSeconds /** PISystemTime seconds representation (*.* s) */ = 0x40000000
}; };
//! Column labels alignment //! Column labels alignment
enum Alignment { enum Alignment {
Nothing /** No alignment */ , Nothing /** No alignment */ ,
Left /** Labels align left and variables align left */ , Left /** Labels align left and variables align left */ ,
Right /** Labels align right and variables align left */ Right /** Labels align right and variables align left */
}; };
typedef PIFlags<PIConsole::Format> FormatFlags; typedef PIFlags<PIConsole::Format> FormatFlags;
//! Add to current tab to column "column" string "name" with format "format" //! Add to current tab to column "column" string "name" with format "format"
void addString(const PIString & name, int column = 1, FormatFlags format = PIConsole::Normal); void addString(const PIString & name, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const PIString * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const PIString * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const char * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const char * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const bool * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const bool * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const short * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const short * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const int * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const int * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const long * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const long * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const llong * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const llong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const uchar * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const uchar * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ushort * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const ushort * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const uint * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const uint * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ulong * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const ulong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const ullong * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const ullong * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const float * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const float * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const double * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const double * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" variable with label "name", pointer "ptr" and format "format"
void addVariable(const PIString & name, const PISystemTime * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const PISystemTime * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
void addVariable(const PIString & name, const PIProtocol * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const PIProtocol * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
void addVariable(const PIString & name, const PIDiagnostics * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const PIDiagnostics * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
void addVariable(const PIString & name, const PISystemMonitor * ptr, int column = 1, FormatFlags format = PIConsole::Normal); void addVariable(const PIString & name, const PISystemMonitor * ptr, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" bits field with label "name", pointer "ptr" and format "format" //! Add to current tab to column "column" bits field with label "name", pointer "ptr" and format "format"
void addBitVariable(const PIString & name, const void * ptr, int fromBit, int bitsCount, int column = 1, FormatFlags format = PIConsole::Normal); void addBitVariable(const PIString & name, const void * ptr, int fromBit, int bitsCount, int column = 1, FormatFlags format = PIConsole::Normal);
//! Add to current tab to column "column" "count" empty lines //! Add to current tab to column "column" "count" empty lines
void addEmptyLine(int column = 1, uint count = 1); void addEmptyLine(int column = 1, uint count = 1);
PIString getString(int x, int y); PIString getString(int x, int y);
short getShort(int x, int y) {return getString(x, y).toShort();} short getShort(int x, int y) {return getString(x, y).toShort();}
int getInt(int x, int y) {return getString(x, y).toInt();} int getInt(int x, int y) {return getString(x, y).toInt();}
@@ -153,93 +153,93 @@ public:
int getInt(const PIString & name) {return getString(name).toInt();} int getInt(const PIString & name) {return getString(name).toInt();}
float getFloat(const PIString & name) {return getString(name).toFloat();} float getFloat(const PIString & name) {return getString(name).toFloat();}
double getDouble(const PIString & name) {return getString(name).toDouble();} double getDouble(const PIString & name) {return getString(name).toDouble();}
//! Returns tabs count //! Returns tabs count
uint tabsCount() const {return tabs.size();} uint tabsCount() const {return tabs.size();}
//! Returns current tab name //! Returns current tab name
PIString currentTab() const {return tabs[cur_tab].name;} PIString currentTab() const {return tabs[cur_tab].name;}
//! Returns current tab index //! Returns current tab index
int currentTabIndex() const {return cur_tab;} int currentTabIndex() const {return cur_tab;}
//! Add new tab with name "name", bind key "bind_key" and returns this tab index //! Add new tab with name "name", bind key "bind_key" and returns this tab index
int addTab(const PIString & name, char bind_key = 0); int addTab(const PIString & name, char bind_key = 0);
//! Remove tab with index "index" //! Remove tab with index "index"
void removeTab(uint index); void removeTab(uint index);
//! Remove tab with name "name" //! Remove tab with name "name"
void removeTab(const PIString & name); void removeTab(const PIString & name);
//! Clear content of tab with index "index" //! Clear content of tab with index "index"
void clearTab(uint index); void clearTab(uint index);
//! Clear content of tab with name "name" //! Clear content of tab with name "name"
void clearTab(const PIString & name); void clearTab(const PIString & name);
//! Set current tab to tab with index "index", returns if tab exists //! Set current tab to tab with index "index", returns if tab exists
bool setTab(uint index); bool setTab(uint index);
//! Set current tab to tab with name "name", returns if tab exists //! Set current tab to tab with name "name", returns if tab exists
bool setTab(const PIString & name); bool setTab(const PIString & name);
//! Set tab with index "index" bind key to "bind_key", returns if tab exists //! Set tab with index "index" bind key to "bind_key", returns if tab exists
bool setTabBindKey(uint index, char bind_key); bool setTabBindKey(uint index, char bind_key);
//! Set tab with name "name" bind key to "bind_key", returns if tab exists //! Set tab with name "name" bind key to "bind_key", returns if tab exists
bool setTabBindKey(const PIString & name, char bind_key); bool setTabBindKey(const PIString & name, char bind_key);
//! Remove all tabs and if "clearScreen" clear the screen //! Remove all tabs and if "clearScreen" clear the screen
void clearTabs(bool clearScreen = true) {if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();} tabs.clear();} void clearTabs(bool clearScreen = true) {if (clearScreen && isRunning()) {toUpperLeft(); clearScreenLower();} tabs.clear();}
//! Set custom status text of current tab to "str" //! Set custom status text of current tab to "str"
void addCustomStatus(const PIString & str) {tabs[cur_tab].status = str;} void addCustomStatus(const PIString & str) {tabs[cur_tab].status = str;}
//! Clear custom status text of current tab //! Clear custom status text of current tab
void clearCustomStatus() {tabs[cur_tab].status.clear();} void clearCustomStatus() {tabs[cur_tab].status.clear();}
//! Returns default alignment //! Returns default alignment
Alignment defaultAlignment() const {return def_align;} Alignment defaultAlignment() const {return def_align;}
//! Set default alignment to "align" //! Set default alignment to "align"
void setDefaultAlignment(Alignment align) {def_align = align;} void setDefaultAlignment(Alignment align) {def_align = align;}
//! Set column "col" alignment to "align" //! Set column "col" alignment to "align"
void setColumnAlignment(int col, Alignment align) {if (col < 0 || col >= columns().size_s()) return; column(col).alignment = align;} void setColumnAlignment(int col, Alignment align) {if (col < 0 || col >= columns().size_s()) return; column(col).alignment = align;}
//! Set all columns of all tabs alignment to "align" //! Set all columns of all tabs alignment to "align"
void setColumnAlignmentToAll(Alignment align) {piForeach (Tab & i, tabs) piForeach (Column & j, i.columns) j.alignment = align; fillLabels();} void setColumnAlignmentToAll(Alignment align) {piForeach (Tab & i, tabs) piForeach (Column & j, i.columns) j.alignment = align; fillLabels();}
//! Directly call function from \a PIKbdListener //! Directly call function from \a PIKbdListener
void enableExitCapture(char key = 'Q') {listener->enableExitCapture(key);} void enableExitCapture(char key = 'Q') {listener->enableExitCapture(key);}
//! Directly call function from \a PIKbdListener //! Directly call function from \a PIKbdListener
void disableExitCapture() {listener->disableExitCapture();} void disableExitCapture() {listener->disableExitCapture();}
//! Directly call function from \a PIKbdListener //! Directly call function from \a PIKbdListener
bool exitCaptured() const {return listener->exitCaptured();} bool exitCaptured() const {return listener->exitCaptured();}
//! Directly call function from \a PIKbdListener //! Directly call function from \a PIKbdListener
char exitKey() const {return listener->exitKey();} char exitKey() const {return listener->exitKey();}
int windowWidth() const {return width;} int windowWidth() const {return width;}
int windowHeight() const {return height;} int windowHeight() const {return height;}
PIString fstr(FormatFlags f); PIString fstr(FormatFlags f);
void update(); void update();
void pause(bool yes) {pause_ = yes;} void pause(bool yes) {pause_ = yes;}
// Server functions // Server functions
void startServer(const PIString & name); void startServer(const PIString & name);
void stopPeer(); void stopPeer();
bool isServerStarted() const {return peer != 0;} bool isServerStarted() const {return peer != 0;}
PIStringList clients() const; PIStringList clients() const;
// Client functions // Client functions
void listenServers(); void listenServers();
PIStringList availableServers() const; PIStringList availableServers() const;
@@ -271,44 +271,44 @@ public:
void hideCursor() {printf("\e[?25l");} void hideCursor() {printf("\e[?25l");}
void showCursor() {printf("\e[?25h");} void showCursor() {printf("\e[?25h");}
#endif #endif
EVENT_HANDLER0(void, clearVariables) {clearVariables(true);} EVENT_HANDLER0(void, clearVariables) {clearVariables(true);}
EVENT_HANDLER1(void, clearVariables, bool, clearScreen); EVENT_HANDLER1(void, clearVariables, bool, clearScreen);
EVENT_HANDLER0(void, waitForFinish) {WAIT_FOR_EXIT} EVENT_HANDLER0(void, waitForFinish) {WAIT_FOR_EXIT}
EVENT_HANDLER0(void, start) {start(false);} EVENT_HANDLER0(void, start) {start(false);}
EVENT_HANDLER1(void, start, bool, wait) {PIThread::start(40); if (wait) waitForFinish();} EVENT_HANDLER1(void, start, bool, wait) {PIThread::start(40); if (wait) waitForFinish();}
EVENT_HANDLER0(void, stop) {stop(false);} EVENT_HANDLER0(void, stop) {stop(false);}
EVENT_HANDLER1(void, stop, bool, clear); EVENT_HANDLER1(void, stop, bool, clear);
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void * , data) EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void * , data)
//! \handlers //! \handlers
//! \{ //! \{
//! \fn void waitForFinish() //! \fn void waitForFinish()
//! \brief block until finished (exit key will be pressed) //! \brief block until finished (exit key will be pressed)
//! \fn void clearVariables(bool clearScreen = true) //! \fn void clearVariables(bool clearScreen = true)
//! \brief Remove all columns at current tab and if "clearScreen" clear the screen //! \brief Remove all columns at current tab and if "clearScreen" clear the screen
//! \fn void start(bool wait = false) //! \fn void start(bool wait = false)
//! \brief Start console output and if "wait" block until finished (exit key will be pressed) //! \brief Start console output and if "wait" block until finished (exit key will be pressed)
//! \fn void stop(bool clear = false) //! \fn void stop(bool clear = false)
//! \brief Stop console output and if "clear" clear the screen //! \brief Stop console output and if "clear" clear the screen
//! \} //! \}
//! \events //! \events
//! \{ //! \{
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data) //! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object //! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
//! \} //! \}
private: private:
void begin(); void begin();
void run(); void run();
void fillLabels(); void fillLabels();
void status(); void status();
@@ -336,8 +336,8 @@ private:
struct Variable { struct Variable {
Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = Normal; remote = false; ptr = 0; id = 1;} Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = Normal; remote = false; ptr = 0; id = 1;}
Variable(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size; Variable(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size;
bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;} bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;}
bool isEmpty() const {return (remote ? false : ptr == 0);} bool isEmpty() const {return (remote ? false : ptr == 0);}
const void * data() {return (remote ? rdata.data() : ptr);} const void * data() {return (remote ? rdata.data() : ptr);}
void writeData(PIByteArray & ba) { void writeData(PIByteArray & ba) {
@@ -363,7 +363,7 @@ private:
void operator =(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size; void operator =(const Variable & src) {remote = src.remote; name = src.name; format = src.format; type = src.type; offset = src.offset; size = src.size;
bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;} bitFrom = src.bitFrom; bitCount = src.bitCount; ptr = src.ptr; nx = src.nx; ny = src.ny; rdata = src.rdata; id = src.id;}
}; };
struct VariableContent { struct VariableContent {
int id; int id;
PIByteArray rdata; PIByteArray rdata;
@@ -387,7 +387,7 @@ private:
PIString status; PIString status;
char key; char key;
}; };
enum ConnectedState {Disconnected, FetchingData, Committing, Connected}; enum ConnectedState {Disconnected, FetchingData, Committing, Connected};
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::VariableContent & v); friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::VariableContent & v);
@@ -401,7 +401,7 @@ private:
friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Tab & v); friend PIByteArray & operator <<(PIByteArray & ba, const PIConsole::Tab & v);
friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::Tab & v); friend PIByteArray & operator >>(PIByteArray & ba, PIConsole::Tab & v);
PIVector<Column> & columns() {return tabs[cur_tab].columns;} PIVector<Column> & columns() {return tabs[cur_tab].columns;}
Column & column(int index) {return tabs[cur_tab].columns[index - 1];} Column & column(int index) {return tabs[cur_tab].columns[index - 1];}
inline int couts(const PIString & v) {return printf("%s", v.data());} inline int couts(const PIString & v) {return printf("%s", v.data());}
@@ -420,9 +420,9 @@ private:
inline int couts(const float v); inline int couts(const float v);
inline int couts(const double v); inline int couts(const double v);
inline int couts(const PISystemTime & v); inline int couts(const PISystemTime & v);
struct RemoteClient; struct RemoteClient;
void serverSendInfo(); void serverSendInfo();
void serverSendData(); void serverSendData();
RemoteClient & remoteClient(const PIString & fname); RemoteClient & remoteClient(const PIString & fname);
@@ -442,14 +442,14 @@ private:
uint max_y; uint max_y;
int vid; int vid;
uint cur_tab, col_cnt; uint cur_tab, col_cnt;
PIPeer * peer; PIPeer * peer;
PITimer peer_timer; PITimer peer_timer;
PITimeMeasurer peer_tm; PITimeMeasurer peer_tm;
PIString server_name; PIString server_name;
bool server_mode, pause_; bool server_mode, pause_;
ConnectedState state; ConnectedState state;
/*struct RemoteData { /*struct RemoteData {
RemoteData() {msg_count = msg_rec = msg_send = 0;} RemoteData() {msg_count = msg_rec = msg_send = 0;}
void clear() {msg_count = msg_rec = msg_send = 0; data.clear();} void clear() {msg_count = msg_rec = msg_send = 0; data.clear();}
@@ -462,13 +462,13 @@ private:
int msg_rec; int msg_rec;
int msg_send; int msg_send;
};*/ };*/
struct RemoteClient { struct RemoteClient {
RemoteClient(const PIString & n = "") {name = n; state = Disconnected;} RemoteClient(const PIString & n = "") {name = n; state = Disconnected;}
PIString name; PIString name;
ConnectedState state; ConnectedState state;
}; };
PIVector<RemoteClient> remote_clients; PIVector<RemoteClient> remote_clients;
}; };

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Keyboard grabber for console Keyboard grabber for console
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pikbdlistener.h" #include "pikbdlistener.h"
@@ -31,8 +31,8 @@
* There is two ways to receive pressed key: * There is two ways to receive pressed key:
* * external static function with format "void func(char key, void * data_)" * * external static function with format "void func(char key, void * data_)"
* * event \a keyPressed() * * event \a keyPressed()
* *
* Also there is static variable \a exiting which by default is set to * Also there is static variable \a exiting which by default is set to
* \b false. If \a enableExitCapture() was called and listener was started * \b false. If \a enableExitCapture() was called and listener was started
* with function \a start(), this variable will be set to \b true if exit * with function \a start(), this variable will be set to \b true if exit
* key will be pressed. By default exit key is 'Q' = shift + 'q'. * key will be pressed. By default exit key is 'Q' = shift + 'q'.
@@ -142,7 +142,7 @@ PIKbdListener::PIKbdListener(KBFunc slot, void * _d, bool startNow): PIThread()
#endif #endif
is_active = true; is_active = true;
ret_func = slot; ret_func = slot;
kbddata_ = _d; kbddata_ = _d;
PIKbdListener::exiting = exit_enabled = false; PIKbdListener::exiting = exit_enabled = false;
if (startNow) start(); if (startNow) start();
} }
@@ -317,8 +317,8 @@ void PIKbdListener::readKeyboard() {
return; return;
} }
if (ret > 0) { if (ret > 0) {
keyPressed(ke, kbddata_); keyPressed(ke, kbddata_);
if (ret_func != 0) ret_func(ke, kbddata_); if (ret_func != 0) ret_func(ke, kbddata_);
} }
} }

View File

@@ -2,22 +2,22 @@
* \brief Keyboard console input listener * \brief Keyboard console input listener
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Keyboard grabber for console Keyboard grabber for console
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIKBDLISTENER_H #ifndef PIKBDLISTENER_H
@@ -34,7 +34,7 @@ class PIP_EXPORT PIKbdListener: public PIThread
friend class PIConsole; friend class PIConsole;
friend class PITerminal; friend class PITerminal;
public: public:
//! Special keyboard keys //! Special keyboard keys
enum SpecialKey { enum SpecialKey {
Tab /** Tab key */ = 0x09, Tab /** Tab key */ = 0x09,
@@ -65,7 +65,7 @@ public:
F11 /** F11 key */ = -21, F11 /** F11 key */ = -21,
F12 /** F12 key */ = -22 F12 /** F12 key */ = -22
}; };
//! Keyboard modifiers //! Keyboard modifiers
enum KeyModifier { enum KeyModifier {
Ctrl /** Control key */ = 0x1, Ctrl /** Control key */ = 0x1,
@@ -73,86 +73,86 @@ public:
Alt /** Alt key */ = 0x4 Alt /** Alt key */ = 0x4
//Meta /** Meta (windows) key */ = 0x8 //Meta /** Meta (windows) key */ = 0x8
}; };
typedef PIFlags<KeyModifier> KeyModifiers; typedef PIFlags<KeyModifier> KeyModifiers;
//! This struct contains information about pressed keyboard key //! This struct contains information about pressed keyboard key
struct KeyEvent { struct KeyEvent {
KeyEvent(int k = 0, KeyModifiers m = 0) {key = k; modifiers = m;} KeyEvent(int k = 0, KeyModifiers m = 0) {key = k; modifiers = m;}
//! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey) //! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey)
int key; int key;
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields //! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
KeyModifiers modifiers; KeyModifiers modifiers;
}; };
typedef void (*KBFunc)(KeyEvent, void * ); typedef void (*KBFunc)(KeyEvent, void * );
//! Constructs keyboard listener with external function "slot" and custom data "data" //! Constructs keyboard listener with external function "slot" and custom data "data"
explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true); explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true);
~PIKbdListener(); ~PIKbdListener();
//! Returns custom data //! Returns custom data
void * data() {return kbddata_;} void * data() {return kbddata_;}
//! Set custom data to "_data" //! Set custom data to "_data"
void setData(void * _data) {kbddata_ = _data;} void setData(void * _data) {kbddata_ = _data;}
//! Set external function to "slot" //! Set external function to "slot"
void setSlot(KBFunc slot) {ret_func = slot;} void setSlot(KBFunc slot) {ret_func = slot;}
//! Returns if exit key if awaiting //! Returns if exit key if awaiting
bool exitCaptured() const {return exit_enabled;} bool exitCaptured() const {return exit_enabled;}
//! Returns exit key, default 'Q' //! Returns exit key, default 'Q'
int exitKey() const {return exit_key;} int exitKey() const {return exit_key;}
void readKeyboard(); void readKeyboard();
//! Returns if keyboard listening is active (not running!) //! Returns if keyboard listening is active (not running!)
bool isActive() {return is_active;} bool isActive() {return is_active;}
EVENT_HANDLER( void, enableExitCapture) {enableExitCapture('Q');} EVENT_HANDLER( void, enableExitCapture) {enableExitCapture('Q');}
EVENT_HANDLER1(void, enableExitCapture, int, key) {exit_enabled = true; exit_key = key;} EVENT_HANDLER1(void, enableExitCapture, int, key) {exit_enabled = true; exit_key = key;}
EVENT_HANDLER(void, disableExitCapture) {exit_enabled = false;} EVENT_HANDLER(void, disableExitCapture) {exit_enabled = false;}
EVENT_HANDLER(void, setActive) {setActive(true);} EVENT_HANDLER(void, setActive) {setActive(true);}
EVENT_HANDLER1(void, setActive, bool, yes); EVENT_HANDLER1(void, setActive, bool, yes);
EVENT2(keyPressed, KeyEvent, key, void * , data) EVENT2(keyPressed, KeyEvent, key, void * , data)
//! \handlers //! \handlers
//! \{ //! \{
//! \fn void enableExitCapture(int key = 'Q') //! \fn void enableExitCapture(int key = 'Q')
//! \brief Enable exit key "key" awaiting //! \brief Enable exit key "key" awaiting
//! \fn void disableExitCapture() //! \fn void disableExitCapture()
//! \brief Disable exit key awaiting //! \brief Disable exit key awaiting
//! \fn void setActive(bool yes = true) //! \fn void setActive(bool yes = true)
//! \brief Set keyboard listening is active or not //! \brief Set keyboard listening is active or not
//! \} //! \}
//! \events //! \events
//! \{ //! \{
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data) //! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \brief Raise on key "key" pressed, "data" is custom data //! \brief Raise on key "key" pressed, "data" is custom data
//! \} //! \}
static bool exiting; static bool exiting;
static PIKbdListener * instance() {return _object;} static PIKbdListener * instance() {return _object;}
private: private:
void begin(); void begin();
void run() {readKeyboard();} void run() {readKeyboard();}
void end(); void end();
#ifndef WINDOWS #ifndef WINDOWS
struct EscSeq { struct EscSeq {
const char * seq; const char * seq;
@@ -164,17 +164,17 @@ private:
// 2 - alt // 2 - alt
// 4 - ctrl // 4 - ctrl
}; };
enum VTType { enum VTType {
vt_none, vt_none,
vt_xterm = 0x1, vt_xterm = 0x1,
vt_linux = 0x2, vt_linux = 0x2,
vt_all = 0xFF vt_all = 0xFF
}; };
static const EscSeq esc_seq[]; static const EscSeq esc_seq[];
#endif #endif
PRIVATE_DECLARATION PRIVATE_DECLARATION
#ifdef WINDOWS #ifdef WINDOWS
DWORD DWORD
@@ -185,7 +185,7 @@ private:
KBFunc ret_func; KBFunc ret_func;
int exit_key; int exit_key;
bool exit_enabled, is_active; bool exit_enabled, is_active;
void * kbddata_; void * kbddata_;
char rc[8]; char rc[8];
KeyEvent ke; KeyEvent ke;
static PIKbdListener * _object; static PIKbdListener * _object;

View File

@@ -1,25 +1,25 @@
/*! \file pideque.h /*! \file pideque.h
* \brief Dynamic array of any type * \brief Dynamic array of any type
* *
* This file declares PIDeque * This file declares PIDeque
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Dynamic array of any type Dynamic array of any type
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIDEQUE_H #ifndef PIDEQUE_H
@@ -38,7 +38,7 @@ public:
PIDeque(): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIDeque(): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) {
PIINTROSPECTION_CONTAINER_NEW() PIINTROSPECTION_CONTAINER_NEW()
//printf("new vector 1 %p (%s) ... !{\n", this, typeid(T).name()); //printf("new vector 1 %p (%s) ... !{\n", this, typeid(T).name());
//printf("(s=%d, d=%p) }!\n", int(pid_size), pid_data); //printf("(s=%d, d=%p) }!\n", int(pid_size), pid_data);
} }
PIDeque(const PIDeque<T> & other): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) { PIDeque(const PIDeque<T> & other): pid_data(0), pid_size(0), pid_rsize(0), pid_start(0) {
PIINTROSPECTION_CONTAINER_NEW() PIINTROSPECTION_CONTAINER_NEW()
@@ -278,7 +278,7 @@ public:
pid_size -= count; pid_size -= count;
return *this; return *this;
} }
void swap(PIDeque<T> & other) { void swap(PIDeque<T> & other) {
piSwap<T*>(pid_data, other.pid_data); piSwap<T*>(pid_data, other.pid_data);
piSwap<size_t>(pid_size, other.pid_size); piSwap<size_t>(pid_size, other.pid_size);
@@ -291,7 +291,7 @@ public:
PIDeque<T> & sort(CompareFunc compare = compare_func) {qsort(pid_data + pid_start, pid_size, sizeof(T), (int(*)(const void * , const void * ))compare); return *this;} PIDeque<T> & sort(CompareFunc compare = compare_func) {qsort(pid_data + pid_start, pid_size, sizeof(T), (int(*)(const void * , const void * ))compare); return *this;}
PIDeque<T> & enlarge(llong pid_size) {llong ns = size_s() + pid_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this;} PIDeque<T> & enlarge(llong pid_size) {llong ns = size_s() + pid_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this;}
PIDeque<T> & removeOne(const T & v) {for (size_t i = 0; i < pid_size; ++i) if (pid_data[i + pid_start] == v) {remove(i); return *this;} return *this;} PIDeque<T> & removeOne(const T & v) {for (size_t i = 0; i < pid_size; ++i) if (pid_data[i + pid_start] == v) {remove(i); return *this;} return *this;}
PIDeque<T> & removeAll(const T & v) {for (llong i = 0; i < pid_size; ++i) if (pid_data[i + pid_start] == v) {remove(i); --i;} return *this;} PIDeque<T> & removeAll(const T & v) {for (llong i = 0; i < pid_size; ++i) if (pid_data[i + pid_start] == v) {remove(i); --i;} return *this;}
@@ -310,13 +310,13 @@ public:
PIDeque<T> & pop_back() {if (pid_size == 0) return *this; resize(pid_size - 1); return *this;} PIDeque<T> & pop_back() {if (pid_size == 0) return *this; resize(pid_size - 1); return *this;}
PIDeque<T> & pop_front() {if (pid_size == 0) return *this; remove(0); return *this;} PIDeque<T> & pop_front() {if (pid_size == 0) return *this; remove(0); return *this;}
T take_back() {T t(back()); pop_back(); return t;} T take_back() {T t(back()); pop_back(); return t;}
T take_front() {T t(front()); pop_front(); return t;} T take_front() {T t(front()); pop_front(); return t;}
template <typename ST> template <typename ST>
PIDeque<ST> toType() const {PIDeque<ST> ret(pid_size); for (uint i = 0; i < pid_size; ++i) ret[i] = ST(pid_data[i + pid_start]); return ret;} PIDeque<ST> toType() const {PIDeque<ST> ret(pid_size); for (uint i = 0; i < pid_size; ++i) ret[i] = ST(pid_data[i + pid_start]); return ret;}
private: private:
void _reset() {pid_size = pid_rsize = pid_start = 0; pid_data = 0;} void _reset() {pid_size = pid_rsize = pid_start = 0; pid_data = 0;}
/*void * qmemmove(void * dst, void * src, size_t size) { /*void * qmemmove(void * dst, void * src, size_t size) {
@@ -457,7 +457,7 @@ private:
//checkMove(direction); //checkMove(direction);
//printf("%X alloc new start %d\n", this, pid_start); //printf("%X alloc new start %d\n", this, pid_start);
} }
T * pid_data; T * pid_data;
volatile size_t pid_size, pid_rsize; volatile size_t pid_size, pid_rsize;
volatile ssize_t pid_start; volatile ssize_t pid_start;

View File

@@ -1,25 +1,25 @@
/*! \file pivector.h /*! \file pivector.h
* \brief Dynamic array of any type * \brief Dynamic array of any type
* *
* This file declares PIVector * This file declares PIVector
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Dynamic array of any type Dynamic array of any type
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIVECTOR_H #ifndef PIVECTOR_H
@@ -258,7 +258,7 @@ public:
piv_size -= count; piv_size -= count;
return *this; return *this;
} }
void swap(PIVector<T> & other) { void swap(PIVector<T> & other) {
piSwap<T*>(piv_data, other.piv_data); piSwap<T*>(piv_data, other.piv_data);
piSwap<size_t>(piv_size, other.piv_size); piSwap<size_t>(piv_size, other.piv_size);
@@ -270,7 +270,7 @@ public:
PIVector<T> & sort(CompareFunc compare = compare_func) {qsort(piv_data, piv_size, sizeof(T), (int(*)(const void * , const void * ))compare); return *this;} PIVector<T> & sort(CompareFunc compare = compare_func) {qsort(piv_data, piv_size, sizeof(T), (int(*)(const void * , const void * ))compare); return *this;}
PIVector<T> & enlarge(llong piv_size) {llong ns = size_s() + piv_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this;} PIVector<T> & enlarge(llong piv_size) {llong ns = size_s() + piv_size; if (ns <= 0) clear(); else resize(size_t(ns)); return *this;}
PIVector<T> & removeOne(const T & v) {for (size_t i = 0; i < piv_size; ++i) if (piv_data[i] == v) {remove(i); return *this;} return *this;} PIVector<T> & removeOne(const T & v) {for (size_t i = 0; i < piv_size; ++i) if (piv_data[i] == v) {remove(i); return *this;} return *this;}
PIVector<T> & removeAll(const T & v) {for (llong i = 0; i < piv_size; ++i) if (piv_data[i] == v) {remove(i); --i;} return *this;} PIVector<T> & removeAll(const T & v) {for (llong i = 0; i < piv_size; ++i) if (piv_data[i] == v) {remove(i); --i;} return *this;}
@@ -289,13 +289,13 @@ public:
PIVector<T> & pop_back() {if (piv_size == 0) return *this; resize(piv_size - 1); return *this;} PIVector<T> & pop_back() {if (piv_size == 0) return *this; resize(piv_size - 1); return *this;}
PIVector<T> & pop_front() {if (piv_size == 0) return *this; remove(0); return *this;} PIVector<T> & pop_front() {if (piv_size == 0) return *this; remove(0); return *this;}
T take_back() {T t(back()); pop_back(); return t;} T take_back() {T t(back()); pop_back(); return t;}
T take_front() {T t(front()); pop_front(); return t;} T take_front() {T t(front()); pop_front(); return t;}
template <typename ST> template <typename ST>
PIVector<ST> toType() const {PIVector<ST> ret(piv_size); for (uint i = 0; i < piv_size; ++i) ret[i] = ST(piv_data[i]); return ret;} PIVector<ST> toType() const {PIVector<ST> ret(piv_size); for (uint i = 0; i < piv_size; ++i) ret[i] = ST(piv_data[i]); return ret;}
private: private:
void _reset() {piv_size = piv_rsize = 0; piv_data = 0;} void _reset() {piv_size = piv_rsize = 0; piv_data = 0;}
size_t asize(size_t s) { size_t asize(size_t s) {
@@ -354,7 +354,7 @@ private:
piv_size = new_size; piv_size = new_size;
size_t as = asize(new_size); size_t as = asize(new_size);
if (as == piv_rsize) return; if (as == piv_rsize) return;
//cout << std::hex << " ![("<<this<<")realloc " << piv_data << " data ... <\n" << endl; //cout << std::hex << " ![("<<this<<")realloc " << piv_data << " data ... <\n" << endl;
T * p_d = (T*)(realloc(piv_data, as*sizeof(T))); T * p_d = (T*)(realloc(piv_data, as*sizeof(T)));
assert(p_d); assert(p_d);
@@ -441,7 +441,7 @@ class PIP_EXPORT PIVector: public vector<T, Allocator> {
typedef PIVector<T, Allocator> _CVector; typedef PIVector<T, Allocator> _CVector;
typedef vector<T, Allocator> _stlc; typedef vector<T, Allocator> _stlc;
public: public:
PIVector() {piMonitor.containers++;} PIVector() {piMonitor.containers++;}
PIVector(uint size, const T & value = T()) {piMonitor.containers++; _stlc::resize(size, value);} PIVector(uint size, const T & value = T()) {piMonitor.containers++; _stlc::resize(size, value);}
~PIVector() {piMonitor.containers--;} ~PIVector() {piMonitor.containers--;}
@@ -454,17 +454,17 @@ public:
#ifdef DOXYGEN #ifdef DOXYGEN
uint size() const; uint size() const;
#endif #endif
int size_s() const {return static_cast<int>(_stlc::size());} int size_s() const {return static_cast<int>(_stlc::size());}
bool isEmpty() const {return _stlc::empty();} bool isEmpty() const {return _stlc::empty();}
bool has(const T & t) const {for (typename _stlc::const_iterator i = _stlc::begin(); i != _stlc::end(); ++i) if (t == *i) return true; return false;} bool has(const T & t) const {for (typename _stlc::const_iterator i = _stlc::begin(); i != _stlc::end(); ++i) if (t == *i) return true; return false;}
int etries(const T & t) const {int ec = 0; for (typename _stlc::const_iterator i = _stlc::begin(); i != _stlc::end(); ++i) if (t == *i) ++ec; return ec;} int etries(const T & t) const {int ec = 0; for (typename _stlc::const_iterator i = _stlc::begin(); i != _stlc::end(); ++i) if (t == *i) ++ec; return ec;}
typedef int (*CompareFunc)(const T * , const T * ); typedef int (*CompareFunc)(const T * , const T * );
static int compare_func(const T * t0, const T * t1) {return (*t0) == (*t1) ? 0 : ((*t0) < (*t1) ? -1 : 1);} static int compare_func(const T * t0, const T * t1) {return (*t0) == (*t1) ? 0 : ((*t0) < (*t1) ? -1 : 1);}
#ifdef DOXYGEN #ifdef DOXYGEN
void resize(uint size, const T & new_type = T()); void resize(uint size, const T & new_type = T());
PIVector<T, Allocator> & enlarge(uint size); PIVector<T, Allocator> & enlarge(uint size);
void clear(); void clear();
@@ -493,7 +493,7 @@ public:
bool operator ==(const PIVector<T, Allocator> & t) {for (uint i = 0; i < _stlc::size(); ++i) if (t[i] != at(i)) return false; return true;} bool operator ==(const PIVector<T, Allocator> & t) {for (uint i = 0; i < _stlc::size(); ++i) if (t[i] != at(i)) return false; return true;}
bool operator !=(const PIVector<T, Allocator> & t) {for (uint i = 0; i < _stlc::size(); ++i) if (t[i] != at(i)) return true; return false;} bool operator !=(const PIVector<T, Allocator> & t) {for (uint i = 0; i < _stlc::size(); ++i) if (t[i] != at(i)) return true; return false;}
bool contains(const T & v) const {for (uint i = 0; i < _stlc::size(); ++i) if (v == at(i)) return true; return false;} bool contains(const T & v) const {for (uint i = 0; i < _stlc::size(); ++i) if (v == at(i)) return true; return false;}
#else #else
_CVector & enlarge(int size_) {int ns = size_s() + size_; if (ns <= 0) _stlc::clear(); else _stlc::resize(ns); return *this;} _CVector & enlarge(int size_) {int ns = size_s() + size_; if (ns <= 0) _stlc::clear(); else _stlc::resize(ns); return *this;}
_CVector & sort(CompareFunc compare = compare_func) {qsort(&at(0), _stlc::size(), sizeof(T), (int(*)(const void * , const void * ))compare); return *this;} _CVector & sort(CompareFunc compare = compare_func) {qsort(&at(0), _stlc::size(), sizeof(T), (int(*)(const void * , const void * ))compare); return *this;}

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Byte array Byte array
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pibytearray.h" #include "pibytearray.h"
@@ -24,7 +24,7 @@
* \brief Byte array * \brief Byte array
* \details This class based on PIDeque<uchar> and provide some handle function * \details This class based on PIDeque<uchar> and provide some handle function
* to manipulate it. * to manipulate it.
* *
* \section PIByteArray_sec0 Usage * \section PIByteArray_sec0 Usage
* %PIByteArray can be used to store custom data and manipulate it. There are many * %PIByteArray can be used to store custom data and manipulate it. There are many
* stream operators to store/restore common types to byte array. Store operators * stream operators to store/restore common types to byte array. Store operators
@@ -33,27 +33,27 @@
* In addition there are Base 64 convertions and checksums: * In addition there are Base 64 convertions and checksums:
* * plain 8-bit * * plain 8-bit
* * plain 32-bit * * plain 32-bit
* *
* One of the major usage of %PIByteArray is stream functions. You can form binary * One of the major usage of %PIByteArray is stream functions. You can form binary
* packet from many types (also dynamic types, e.g. PIVector) with one line: * packet from many types (also dynamic types, e.g. PIVector) with one line:
* \snippet pibytearray.cpp 0 * \snippet pibytearray.cpp 0
* *
* Or you can descibe stream operator of your own type and store/restore vectors of * Or you can descibe stream operator of your own type and store/restore vectors of
* your type: * your type:
* \snippet pibytearray.cpp 1 * \snippet pibytearray.cpp 1
* *
* For store/restore custom data blocks there is PIByteArray::RawData class. Stream * For store/restore custom data blocks there is PIByteArray::RawData class. Stream
* operators of this class simply store/restore data block to/from byte array. * operators of this class simply store/restore data block to/from byte array.
* \snippet pibytearray.cpp 2 * \snippet pibytearray.cpp 2
* *
* \section PIByteArray_sec1 Attention * \section PIByteArray_sec1 Attention
* Stream operator of %PIByteArray store byte array as vector, not simply append * Stream operator of %PIByteArray store byte array as vector, not simply append
* content of byte array. This operators useful to transmit custom data as %PIByteArray * content of byte array. This operators useful to transmit custom data as %PIByteArray
* packed into parent byte array, e.g. to form packet from %PIByteArray. * packed into parent byte array, e.g. to form packet from %PIByteArray.
* To append one byte array to another use funtion \a append(). * To append one byte array to another use funtion \a append().
* \snippet pibytearray.cpp 3 * \snippet pibytearray.cpp 3
* *
* *
*/ */

View File

@@ -2,22 +2,22 @@
* \brief Byte array * \brief Byte array
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Byte array Byte array
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIBYTEARRAY_H #ifndef PIBYTEARRAY_H
@@ -37,17 +37,17 @@ class PIByteArray;
class PIP_EXPORT PIByteArray: public PIDeque<uchar> class PIP_EXPORT PIByteArray: public PIDeque<uchar>
{ {
public: public:
//! Constructs an empty byte array //! Constructs an empty byte array
PIByteArray() {;} PIByteArray() {;}
//! Constructs 0-filled byte array with size "size" //! Constructs 0-filled byte array with size "size"
PIByteArray(const uint size) {resize(size);} PIByteArray(const uint size) {resize(size);}
//! Constructs byte array from data "data" and size "size" //! Constructs byte array from data "data" and size "size"
PIByteArray(const void * data, const uint size): PIDeque<uchar>((const uchar*)data, size_t(size)) {/*for (uint i = 0; i < size; ++i) push_back(((uchar * )data)[i]);*/} PIByteArray(const void * data, const uint size): PIDeque<uchar>((const uchar*)data, size_t(size)) {/*for (uint i = 0; i < size; ++i) push_back(((uchar * )data)[i]);*/}
//! Help struct to store/restore custom blocks of data to/from PIByteArray //! Help struct to store/restore custom blocks of data to/from PIByteArray
struct RawData { struct RawData {
friend PIByteArray & operator <<(PIByteArray & s, const PIByteArray::RawData & v); friend PIByteArray & operator <<(PIByteArray & s, const PIByteArray::RawData & v);
@@ -55,27 +55,27 @@ public:
public: public:
//! Constructs data block //! Constructs data block
RawData(void * data = 0, int size = 0) {d = data; s = size;} RawData(void * data = 0, int size = 0) {d = data; s = size;}
RawData(const RawData & o) {d = o.d; s = o.s;} RawData(const RawData & o) {d = o.d; s = o.s;}
//! Constructs data block //! Constructs data block
RawData(const void * data, const int size) {d = const_cast<void * >(data); s = size;} RawData(const void * data, const int size) {d = const_cast<void * >(data); s = size;}
RawData & operator =(const RawData & o) {d = o.d; s = o.s; return *this;} RawData & operator =(const RawData & o) {d = o.d; s = o.s; return *this;}
private: private:
void * d; void * d;
int s; int s;
}; };
//! Return resized byte array //! Return resized byte array
PIByteArray resized(int new_size) const {PIByteArray tv(*this); tv.resize(new_size); return tv;} PIByteArray resized(int new_size) const {PIByteArray tv(*this); tv.resize(new_size); return tv;}
//! Convert data to Base 64 and return this byte array //! Convert data to Base 64 and return this byte array
PIByteArray & convertToBase64(); PIByteArray & convertToBase64();
//! Convert data from Base 64 and return this byte array //! Convert data from Base 64 and return this byte array
PIByteArray & convertFromBase64(); PIByteArray & convertFromBase64();
//! Return converted to Base 64 data //! Return converted to Base 64 data
PIByteArray toBase64() const; PIByteArray toBase64() const;
//! Return converted from Base 64 data //! Return converted from Base 64 data
PIByteArray & compressRLE(uchar threshold = 192); PIByteArray & compressRLE(uchar threshold = 192);
@@ -88,7 +88,7 @@ public:
//! Add to the end data "data" with size "size" //! Add to the end data "data" with size "size"
PIByteArray & append(const void * data_, int size_) {uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this;} PIByteArray & append(const void * data_, int size_) {uint ps = size(); enlarge(size_); memcpy(data(ps), data_, size_); return *this;}
//! Add to the end byte array "data" //! Add to the end byte array "data"
PIByteArray & append(const PIByteArray & data_) {uint ps = size(); enlarge(data_.size_s()); memcpy(data(ps), data_.data(), data_.size()); return *this;} PIByteArray & append(const PIByteArray & data_) {uint ps = size(); enlarge(data_.size_s()); memcpy(data(ps), data_.data(), data_.size()); return *this;}
/*PIByteArray & operator <<(short v) {for (uint i = 0; i < sizeof(v); ++i) push_back(((uchar*)(&v))[i]); return *this;} /*PIByteArray & operator <<(short v) {for (uint i = 0; i < sizeof(v); ++i) push_back(((uchar*)(&v))[i]); return *this;}
@@ -101,12 +101,12 @@ public:
//! Returns plain 8-bit checksum //! Returns plain 8-bit checksum
uchar checksumPlain8() const; uchar checksumPlain8() const;
//! Returns plain 32-bit checksum //! Returns plain 32-bit checksum
uint checksumPlain32() const; uint checksumPlain32() const;
void operator =(const PIDeque<uchar> & d) {resize(d.size()); memcpy(data(), d.data(), d.size());} void operator =(const PIDeque<uchar> & d) {resize(d.size()); memcpy(data(), d.data(), d.size());}
static PIByteArray fromString(PIString str); static PIByteArray fromString(PIString str);
static PIByteArray fromHex(PIString str); static PIByteArray fromHex(PIString str);
static PIByteArray fromBase64(const PIByteArray & base64); static PIByteArray fromBase64(const PIByteArray & base64);

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Universal output to console class Universal output to console class
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "picout.h" #include "picout.h"
@@ -27,21 +27,21 @@
/*! \class PICout /*! \class PICout
* \brief Class for formatted output similar std::cout * \brief Class for formatted output similar std::cout
* *
* \section PICout_sec0 Synopsis * \section PICout_sec0 Synopsis
* This class provide many stream operators for output with some features. * This class provide many stream operators for output with some features.
* Output to PICout is thread-sequential, i.e. doesn`t mixed from parallel * Output to PICout is thread-sequential, i.e. doesn`t mixed from parallel
* threads. * threads.
* *
* \section PICout_sec1 Features * \section PICout_sec1 Features
* - insertion spaces between entries * - insertion spaces between entries
* - insertion new line at the end of output * - insertion new line at the end of output
* - strings are quoted * - strings are quoted
* - custom output operator can be easily written * - custom output operator can be easily written
* *
* \section PICout_ex0 Usage * \section PICout_ex0 Usage
* \snippet picout.cpp 0 * \snippet picout.cpp 0
* *
* \section PICout_ex1 Writing your own output operator * \section PICout_ex1 Writing your own output operator
* \snippet picout.cpp own * \snippet picout.cpp own
*/ */
@@ -169,7 +169,7 @@ PICout PICout::operator <<(const PICoutAction v) {
/*GetConsoleCursorInfo(__Private__::hOut, &curinfo); /*GetConsoleCursorInfo(__Private__::hOut, &curinfo);
curinfo.bVisible = false; curinfo.bVisible = false;
SetConsoleCursorInfo(__Private__::hOut, &curinfo); SetConsoleCursorInfo(__Private__::hOut, &curinfo);
SetConsoleCursorPosition(__Private__::hOut, ulcoord); SetConsoleCursorPosition(__Private__::hOut, ulcoord);
FillConsoleOutputAttribute(__Private__::hOut, __Private__::dattr, width * (height + 1), ulcoord, &written); FillConsoleOutputAttribute(__Private__::hOut, __Private__::dattr, width * (height + 1), ulcoord, &written);
FillConsoleOutputCharacter(__Private__::hOut, ' ', width * (height + 1), ulcoord, &written);*/ FillConsoleOutputCharacter(__Private__::hOut, ' ', width * (height + 1), ulcoord, &written);*/

View File

@@ -2,22 +2,22 @@
* \brief Universal output to console class * \brief Universal output to console class
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Universal output to console class Universal output to console class
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PICOUT_H #ifndef PICOUT_H
@@ -43,7 +43,7 @@ extern PIString __PICout_string__;
//! \brief Namespace contains enums controlled PICout //! \brief Namespace contains enums controlled PICout
namespace PICoutManipulators { namespace PICoutManipulators {
//! \brief Enum contains special characters //! \brief Enum contains special characters
enum PIP_EXPORT PICoutSpecialChar { enum PIP_EXPORT PICoutSpecialChar {
Null /*! Null-character, '\\0' */, Null /*! Null-character, '\\0' */,
@@ -52,7 +52,7 @@ namespace PICoutManipulators {
Esc /*! Escape character, '\\e' */, Esc /*! Escape character, '\\e' */,
Quote /*! Quote character, '"' */ Quote /*! Quote character, '"' */
}; };
//! \brief Enum contains immediate action //! \brief Enum contains immediate action
enum PIP_EXPORT PICoutAction { enum PIP_EXPORT PICoutAction {
Flush /*! Flush the output */, Flush /*! Flush the output */,
@@ -64,7 +64,7 @@ namespace PICoutManipulators {
SaveContol /*! Save control flags, equivalent to \a saveControl() */, SaveContol /*! Save control flags, equivalent to \a saveControl() */,
RestoreControl /*! Restore control flags, equivalent to \a restoreControl() */ RestoreControl /*! Restore control flags, equivalent to \a restoreControl() */
}; };
//! \brief Enum contains control of PICout //! \brief Enum contains control of PICout
enum PIP_EXPORT PICoutControl { enum PIP_EXPORT PICoutControl {
AddNone /*! No controls */ = 0x0, AddNone /*! No controls */ = 0x0,
@@ -73,7 +73,7 @@ namespace PICoutManipulators {
AddQuotes /*! Each string will be quoted */ = 0x4, AddQuotes /*! Each string will be quoted */ = 0x4,
AddAll /*! All controls */ = 0xFFFFFFFF AddAll /*! All controls */ = 0xFFFFFFFF
}; };
//! \brief Enum contains output format //! \brief Enum contains output format
enum PIP_EXPORT PICoutFormat { enum PIP_EXPORT PICoutFormat {
Bin /*! Binary representation of integers */ = 0x01, Bin /*! Binary representation of integers */ = 0x01,
@@ -103,7 +103,7 @@ namespace PICoutManipulators {
BackWhite /*! White background */ = 0x2000000, BackWhite /*! White background */ = 0x2000000,
Default /*! Default format */ = 0x4000000 Default /*! Default format */ = 0x4000000
}; };
typedef PIFlags<PICoutControl> PICoutControls; typedef PIFlags<PICoutControl> PICoutControls;
}; };
@@ -114,66 +114,66 @@ class PIP_EXPORT PICout {
public: public:
//! Default constructor with default features (AddSpaces and AddNewLine) //! Default constructor with default features (AddSpaces and AddNewLine)
explicit PICout(PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces | PICoutManipulators::AddNewLine); explicit PICout(PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces | PICoutManipulators::AddNewLine);
PICout(const PICout & other); PICout(const PICout & other);
~PICout(); ~PICout();
//! Output operator for strings with <tt>"const char * "</tt> type //! Output operator for strings with <tt>"const char * "</tt> type
PICout operator <<(const char * v); PICout operator <<(const char * v);
//! Output operator for strings with <tt>"std::string"</tt> type //! Output operator for strings with <tt>"std::string"</tt> type
PICout operator <<(const std::string & v); PICout operator <<(const std::string & v);
//! Output operator for boolean values //! Output operator for boolean values
PICout operator <<(const bool v); PICout operator <<(const bool v);
//! Output operator for <tt>"char"</tt> values //! Output operator for <tt>"char"</tt> values
PICout operator <<(const char v); PICout operator <<(const char v);
//! Output operator for <tt>"unsigned char"</tt> values //! Output operator for <tt>"unsigned char"</tt> values
PICout operator <<(const uchar v); PICout operator <<(const uchar v);
//! Output operator for <tt>"short"</tt> values //! Output operator for <tt>"short"</tt> values
PICout operator <<(const short v); PICout operator <<(const short v);
//! Output operator for <tt>"unsigned short"</tt> values //! Output operator for <tt>"unsigned short"</tt> values
PICout operator <<(const ushort v); PICout operator <<(const ushort v);
//! Output operator for <tt>"int"</tt> values //! Output operator for <tt>"int"</tt> values
PICout operator <<(const int v); PICout operator <<(const int v);
//! Output operator for <tt>"unsigned int"</tt> values //! Output operator for <tt>"unsigned int"</tt> values
PICout operator <<(const uint v); PICout operator <<(const uint v);
//! Output operator for <tt>"long"</tt> values //! Output operator for <tt>"long"</tt> values
PICout operator <<(const long v); PICout operator <<(const long v);
//! Output operator for <tt>"unsigned long"</tt> values //! Output operator for <tt>"unsigned long"</tt> values
PICout operator <<(const ulong v); PICout operator <<(const ulong v);
//! Output operator for <tt>"long long"</tt> values //! Output operator for <tt>"long long"</tt> values
PICout operator <<(const llong v); PICout operator <<(const llong v);
//! Output operator for <tt>"unsigned long long"</tt> values //! Output operator for <tt>"unsigned long long"</tt> values
PICout operator <<(const ullong v); PICout operator <<(const ullong v);
//! Output operator for <tt>"float"</tt> values //! Output operator for <tt>"float"</tt> values
PICout operator <<(const float v); PICout operator <<(const float v);
//! Output operator for <tt>"double"</tt> values //! Output operator for <tt>"double"</tt> values
PICout operator <<(const double v); PICout operator <<(const double v);
//! Output operator for pointers //! Output operator for pointers
PICout operator <<(const void * v); PICout operator <<(const void * v);
//! Output operator for PIObject and ancestors //! Output operator for PIObject and ancestors
PICout operator <<(const PIObject * v); PICout operator <<(const PIObject * v);
//! Output operator for \a PICoutSpecialChar values //! Output operator for \a PICoutSpecialChar values
PICout operator <<(const PICoutManipulators::PICoutSpecialChar v); PICout operator <<(const PICoutManipulators::PICoutSpecialChar v);
//! Output operator for \a PIFlags<PICoutFormat> values //! Output operator for \a PIFlags<PICoutFormat> values
PICout operator <<(const PIFlags<PICoutManipulators::PICoutFormat> & v) { PICout operator <<(const PIFlags<PICoutManipulators::PICoutFormat> & v) {
if (v[PICoutManipulators::Bin]) cnb_ = 2; if (v[PICoutManipulators::Bin]) cnb_ = 2;
@@ -204,7 +204,7 @@ public:
if (v[PICoutManipulators::Default]) applyFormat(PICoutManipulators::Default); if (v[PICoutManipulators::Default]) applyFormat(PICoutManipulators::Default);
return *this; return *this;
} }
//! Output operator for \a PICoutFormat values //! Output operator for \a PICoutFormat values
PICout operator <<(const PICoutManipulators::PICoutFormat v) { PICout operator <<(const PICoutManipulators::PICoutFormat v) {
switch (v) { switch (v) {
@@ -216,45 +216,45 @@ public:
}; };
return *this; return *this;
} }
//! Do some action //! Do some action
PICout operator <<(const PICoutManipulators::PICoutAction v); PICout operator <<(const PICoutManipulators::PICoutAction v);
//! Set control flag "c" is "on" state //! Set control flag "c" is "on" state
PICout & setControl(PICoutManipulators::PICoutControl c, bool on = true) {co_.setFlag(c, on); return *this;} PICout & setControl(PICoutManipulators::PICoutControl c, bool on = true) {co_.setFlag(c, on); return *this;}
//! Set control flags "c" and if "save" exec \a saveControl() //! Set control flags "c" and if "save" exec \a saveControl()
PICout & setControl(PICoutManipulators::PICoutControls c, bool save = false) {if (save) saveControl(); co_ = c; return *this;} PICout & setControl(PICoutManipulators::PICoutControls c, bool save = false) {if (save) saveControl(); co_ = c; return *this;}
//! Save control flags to internal stack \sa \a restoreControl() //! Save control flags to internal stack \sa \a restoreControl()
PICout & saveControl(); PICout & saveControl();
//! Restore control flags from internal stack \sa \a saveControl() //! Restore control flags from internal stack \sa \a saveControl()
PICout & restoreControl(); PICout & restoreControl();
/*! \brief Conditional put space character to output /*! \brief Conditional put space character to output
* \details If it is not a first output and control \a AddSpaces is set * \details If it is not a first output and control \a AddSpaces is set
* space character is put \sa \a quote(), \a newLine() */ * space character is put \sa \a quote(), \a newLine() */
PICout & space(); PICout & space();
/*! \brief Conditional put quote character to output /*! \brief Conditional put quote character to output
* \details If control \a AddQuotes is set * \details If control \a AddQuotes is set
* quote character is put \sa \a space(), \a newLine() */ * quote character is put \sa \a space(), \a newLine() */
PICout & quote(); PICout & quote();
/*! \brief Conditional put new line character to output /*! \brief Conditional put new line character to output
* \details If control \a AddNewLine is set * \details If control \a AddNewLine is set
* new line character is put \sa \a space(), \a quote() */ * new line character is put \sa \a space(), \a quote() */
PICout & newLine(); PICout & newLine();
static bool setBufferActive(bool on, bool clear = false); static bool setBufferActive(bool on, bool clear = false);
static bool isBufferActive(); static bool isBufferActive();
static PIString buffer(bool clear = false); static PIString buffer(bool clear = false);
static void clearBuffer(); static void clearBuffer();
private: private:
void applyFormat(PICoutManipulators::PICoutFormat f); void applyFormat(PICoutManipulators::PICoutFormat f);
static bool buffer_; static bool buffer_;
PRIVATE_DECLARATION PRIVATE_DECLARATION
bool fo_, cc_, fc_; bool fo_, cc_, fc_;

View File

@@ -2,22 +2,22 @@
* \brief Base class for custom state machine * \brief Base class for custom state machine
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
State machine State machine
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PISTATEMACHINE_H #ifndef PISTATEMACHINE_H
@@ -26,13 +26,13 @@
#include "piobject.h" #include "piobject.h"
/*! \brief Base class for custom state machine /*! \brief Base class for custom state machine
* *
* \section PIStateMachine_synopsis Synopsis * \section PIStateMachine_synopsis Synopsis
* This class provide functionality of state machine. * This class provide functionality of state machine.
* You should inherit from this class, implement \a execution() * You should inherit from this class, implement \a execution()
* and \a transition() functions, set rules and periodically * and \a transition() functions, set rules and periodically
* call \a tick() function to proper work of machine. * call \a tick() function to proper work of machine.
* *
* \section PIStateMachine_prepare Prepare for work * \section PIStateMachine_prepare Prepare for work
* %State machine operates with "state", "rule" and "condition". * %State machine operates with "state", "rule" and "condition".
* * "State" is some class (by default \c int), associated name and * * "State" is some class (by default \c int), associated name and
@@ -40,13 +40,13 @@
* * "Rule" define rule of transition from one machine state to other. * * "Rule" define rule of transition from one machine state to other.
* It is also has optional "handler"; * It is also has optional "handler";
* * "Condition" is a part of rule and define possibility of transition. * * "Condition" is a part of rule and define possibility of transition.
* *
* First of all you should define states of your machine by function * First of all you should define states of your machine by function
* \a addState(). Then you should define transition rules for machine * \a addState(). Then you should define transition rules for machine
* by function \a addRule(). Finally you can set initial state by function * by function \a addRule(). Finally you can set initial state by function
* \a setInitialState() and provide periodically execution of function * \a setInitialState() and provide periodically execution of function
* \a tick(). * \a tick().
* *
* \section PIStateMachine_principle Principle of work * \section PIStateMachine_principle Principle of work
* At any time the state machine is in some state. You can ask machine * At any time the state machine is in some state. You can ask machine
* to enter in new state by function \a switchToState(). If all conditions * to enter in new state by function \a switchToState(). If all conditions
@@ -56,18 +56,18 @@
* function \a execution() with current state. On successfull transition * function \a execution() with current state. On successfull transition
* if rule "handler" is not null it execute. Every \a tick() if current * if rule "handler" is not null it execute. Every \a tick() if current
* state "handler" is not null it execute. * state "handler" is not null it execute.
* *
* \section PIStateMachine_conditions Conditions * \section PIStateMachine_conditions Conditions
* Each rule has transition condition. Condition is array of pairs * Each rule has transition condition. Condition is array of pairs
* (string, number). It means that every condition by name "string" * (string, number). It means that every condition by name "string"
* should be performed as least "number" times. Empty condition always * should be performed as least "number" times. Empty condition always
* permits transition. * permits transition.
* *
* %State machine have current performed conditions. You can read this * %State machine have current performed conditions. You can read this
* conditions by function \a currentConditions() and perform new * conditions by function \a currentConditions() and perform new
* conditions by functions \a performCondition() and \a performConditions(). * conditions by functions \a performCondition() and \a performConditions().
* Currend conditions can de erased by function \a resetConditions(). * Currend conditions can de erased by function \a resetConditions().
* *
* \section PIStateMachine_example Example * \section PIStateMachine_example Example
* This is simple example demonstrates all features: * This is simple example demonstrates all features:
* \snippet pistatemachine.cpp main * \snippet pistatemachine.cpp main
@@ -87,7 +87,7 @@ public:
//! %Rule of transition between states of machine //! %Rule of transition between states of machine
struct Rule { struct Rule {
//! Constuctor //! Constuctor
Rule() {handler = 0; from = to = Type(); autoTransition = resetAllConditions = false;} Rule() {handler = 0; from = to = Type(); autoTransition = resetAllConditions = false;}
//! Constuctor //! Constuctor
Rule(Type f, Type t, const PIStringList & c = PIStringList(), Handler h = 0, bool at = false, bool rac = false) { Rule(Type f, Type t, const PIStringList & c = PIStringList(), Handler h = 0, bool at = false, bool rac = false) {
from = f; from = f;
@@ -119,7 +119,7 @@ public:
//! %State of machine //! %State of machine
struct State { struct State {
//! Constuctor //! Constuctor
State() {handler = 0; value = Type();} State() {handler = 0; value = Type();}
//! Constuctor //! Constuctor
State(Type v, const PIString & n = "", Handler h = 0) {value = v; name = n; handler = h;} State(Type v, const PIString & n = "", Handler h = 0) {value = v; name = n; handler = h;}
//! %State value //! %State value
@@ -131,39 +131,39 @@ public:
bool operator ==(const State & other) const {return value == other.value;} bool operator ==(const State & other) const {return value == other.value;}
bool operator !=(const State & other) const {return value != other.value;} bool operator !=(const State & other) const {return value != other.value;}
}; };
void * parent() const {return parent_;} void * parent() const {return parent_;}
void setParent(void * parent) {parent_ = parent;} void setParent(void * parent) {parent_ = parent;}
//! Add state of machine //! Add state of machine
void addState(Type value, const PIString & name = "", Handler handler = 0) {if (states_.contains(State(value, name))) return; states_ << State(value, name, handler);} void addState(Type value, const PIString & name = "", Handler handler = 0) {if (states_.contains(State(value, name))) return; states_ << State(value, name, handler);}
//! States count //! States count
int statesCount() const {return states_.size_s();} int statesCount() const {return states_.size_s();}
//! Remove all states //! Remove all states
void clearStates() {states_.clear();} void clearStates() {states_.clear();}
//! Add rule of transition //! Add rule of transition
void addRule(Type from, Type to, const PIString & condition, Handler handler = 0, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, PIStringList(condition), handler, autoTransition, resetAllConditions);} void addRule(Type from, Type to, const PIString & condition, Handler handler = 0, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, PIStringList(condition), handler, autoTransition, resetAllConditions);}
//! Add rule of transition //! Add rule of transition
void addRule(Type from, Type to, Handler handler, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, PIStringList(), handler, autoTransition, resetAllConditions);} void addRule(Type from, Type to, Handler handler, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, PIStringList(), handler, autoTransition, resetAllConditions);}
//! Add rule of transition //! Add rule of transition
void addRule(Type from, Type to, const PIStringList & conditions = PIStringList(), Handler handler = 0, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, conditions, handler, autoTransition, resetAllConditions);} void addRule(Type from, Type to, const PIStringList & conditions = PIStringList(), Handler handler = 0, bool autoTransition = false, bool resetAllConditions = false) {if (rules_.contains(Rule(from, to))) return; rules_ << Rule(from, to, conditions, handler, autoTransition, resetAllConditions);}
//! Add rule of transition //! Add rule of transition
void addRule(const Rule & rule) {if (rules_.contains(rule)) return; rules_ << rule;} void addRule(const Rule & rule) {if (rules_.contains(rule)) return; rules_ << rule;}
//! Rules count //! Rules count
int rulesCount() const {return rules_.size_s();} int rulesCount() const {return rules_.size_s();}
//! Remove all rules //! Remove all rules
void clearRules() {rules_.clear();} void clearRules() {rules_.clear();}
//! Setup initial state. \a reset() will set machine state to "value" //! Setup initial state. \a reset() will set machine state to "value"
void setInitialState(Type value) { void setInitialState(Type value) {
for (int i = 0; i < states_.size_s(); ++i) for (int i = 0; i < states_.size_s(); ++i)
@@ -172,7 +172,7 @@ public:
return; return;
} }
} }
/** \brief Try to switch machine state to state "to" /** \brief Try to switch machine state to state "to"
* \details If there is rule of transition exists and this rule conditions * \details If there is rule of transition exists and this rule conditions
* is performed then machine switched to new state immediately. Otherwise machine * is performed then machine switched to new state immediately. Otherwise machine
@@ -193,17 +193,17 @@ public:
} }
return false; return false;
} }
//! Reset machine state to initial and clear all conditions //! Reset machine state to initial and clear all conditions
void reset() {state_ = init_; resetConditions();} void reset() {state_ = init_; resetConditions();}
//! Returns current state of machine //! Returns current state of machine
const State & currentState() const {return state_;} const State & currentState() const {return state_;}
//! Reset all performed conditions //! Reset all performed conditions
void resetConditions() {cond.clear(); cond_count = 0;} void resetConditions() {cond.clear(); cond_count = 0;}
//! Reset performed condition with name "name" //! Reset performed condition with name "name"
void resetCondition(const PIString & name) { void resetCondition(const PIString & name) {
for (int i = 0; i < cond.size_s(); ++i) for (int i = 0; i < cond.size_s(); ++i)
@@ -212,7 +212,7 @@ public:
i--; i--;
} }
} }
//! Perform condition with name "name" "times" times. //! Perform condition with name "name" "times" times.
void performCondition(const PIString & name, int times = 1) { void performCondition(const PIString & name, int times = 1) {
if (times <= 0) return; if (times <= 0) return;
@@ -223,7 +223,7 @@ public:
} }
cond << Condition(name, times); cond << Condition(name, times);
} }
//! Perform every condition with name from "names" one time. //! Perform every condition with name from "names" one time.
void performConditions(const PIStringList & names) { void performConditions(const PIStringList & names) {
bool ok; bool ok;
@@ -240,22 +240,22 @@ public:
cond << Condition(names[n], 1); cond << Condition(names[n], 1);
} }
} }
//! Returns all current performed conditions //! Returns all current performed conditions
const PIVector<Condition> & currentConditions() const {return cond;} const PIVector<Condition> & currentConditions() const {return cond;}
Type * currentState_ptr() {return &state_.value;} Type * currentState_ptr() {return &state_.value;}
int * conditionsCount_ptr() {cond_count = cond.size_s(); return &cond_count;} int * conditionsCount_ptr() {cond_count = cond.size_s(); return &cond_count;}
//! \handlers //! \handlers
//! \{ //! \{
//! \fn void tick() //! \fn void tick()
//! \brief Main function of machine. Execute \a execution() and check if need to switch state //! \brief Main function of machine. Execute \a execution() and check if need to switch state
//! \fn void tick(void * data, int delim) //! \fn void tick(void * data, int delim)
//! \brief Main function of machine. Execute \a execution() and check if need to switch state //! \brief Main function of machine. Execute \a execution() and check if need to switch state
//! \} //! \}
EVENT_HANDLER(void, tick) {tick(0, 0);} EVENT_HANDLER(void, tick) {tick(0, 0);}
@@ -275,10 +275,10 @@ public:
} }
protected: protected:
//! Reimplement this function to process current state of machine //! Reimplement this function to process current state of machine
virtual void execution(const State & state) {;} virtual void execution(const State & state) {;}
//! Reimplement this function to process switching current state of machine //! Reimplement this function to process switching current state of machine
virtual void transition(const State & from, const State & to) {;} virtual void transition(const State & from, const State & to) {;}

View File

@@ -54,16 +54,16 @@ PIMap<PIString, __PIVariantInfo__ * > * __PIVariantInfoStorage__::map = 0;
PIVariant::PIVariant() { PIVariant::PIVariant() {
_type = PIVariant::pivInvalid; _type = PIVariant::pivInvalid;
_info = 0; _info = 0;
} }
PIVariant::PIVariant(const PIVariant &v) { PIVariant::PIVariant(const PIVariant &v) {
_type = v._type; _type = v._type;
_content = v._content; _content = v._content;
#ifdef CUSTOM_PIVARIANT #ifdef CUSTOM_PIVARIANT
_info = v._info; _info = v._info;
#endif #endif
} }

View File

@@ -162,7 +162,7 @@ public:
//! Empty constructor, \a type() will be set to \a Invalid //! Empty constructor, \a type() will be set to \a Invalid
PIVariant(); PIVariant();
PIVariant(const PIVariant & v); PIVariant(const PIVariant & v);
//! Constructs variant from string //! Constructs variant from string
PIVariant(const char * v) {initType(PIString(v));} PIVariant(const char * v) {initType(PIString(v));}

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Config parser Config parser
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "piconfig.h" #include "piconfig.h"
@@ -24,13 +24,13 @@
/*! \class PIConfig /*! \class PIConfig
* \brief Configuration file * \brief Configuration file
* \details This class provide handle access to configuration file. * \details This class provide handle access to configuration file.
* *
* \section PIConfig_sec0 Synopsis * \section PIConfig_sec0 Synopsis
* PIConfig reads configuration file and create internal dendritic * PIConfig reads configuration file and create internal dendritic
* representation of all entries of this file. You can easily read * representation of all entries of this file. You can easily read
* some values and write new. * some values and write new.
* \image html piconfig.png * \image html piconfig.png
* *
* %PIConfig supports also INI-style files with sections "[section]". * %PIConfig supports also INI-style files with sections "[section]".
* In this case line with section name interpret as prefix to the next * In this case line with section name interpret as prefix to the next
* lines. For example, these configs are equal: * lines. For example, these configs are equal:
@@ -46,12 +46,12 @@
* [] * []
* debug = true * debug = true
* \endcode * \endcode
* *
* \section PIConfig_sec1 Concepts * \section PIConfig_sec1 Concepts
* Each node of internal tree has type PIConfig::Entry. %PIConfig * Each node of internal tree has type PIConfig::Entry. %PIConfig
* has one root element \a rootEntry(). Any entry of configuration file is a * has one root element \a rootEntry(). Any entry of configuration file is a
* child of this element. * child of this element.
* *
*/ */
/*! \class PIConfig::Entry /*! \class PIConfig::Entry
@@ -63,7 +63,7 @@
* * value * * value
* * type * * type
* * comment * * comment
* *
* Each property is a PIString. These properties forms from text line with * Each property is a PIString. These properties forms from text line with
* format: \code{.cpp} <name> = <value> #<type> <comment> \endcode * format: \code{.cpp} <name> = <value> #<type> <comment> \endcode
* Type and comment are optional fields. Type is a single letter immediately * Type and comment are optional fields. Type is a single letter immediately
@@ -75,14 +75,14 @@
* \a PIConfig::Branch. If there is no suitable entry to return, reference to * \a PIConfig::Branch. If there is no suitable entry to return, reference to
* internal instance of %PIConfig::Entry with "default" value will be returned. * internal instance of %PIConfig::Entry with "default" value will be returned.
* \snippet piconfig.cpp PIConfig::Entry * \snippet piconfig.cpp PIConfig::Entry
* *
*/ */
/*! \class PIConfig::Branch /*! \class PIConfig::Branch
* \brief %Branch is a list of entries of configuration file * \brief %Branch is a list of entries of configuration file
* \details %Branch provides some features to get entries lists. * \details %Branch provides some features to get entries lists.
* \snippet piconfig.cpp PIConfig::Branch * \snippet piconfig.cpp PIConfig::Branch
* *
*/ */
@@ -735,7 +735,7 @@ void PIConfig::parse() {
type = "s"; type = "s";
comm = ""; comm = "";
} }
//name = str.left(ind).trimmed(); //name = str.left(ind).trimmed();
tree = (prefix + str.left(ind).trimmed()).split(delim); tree = (prefix + str.left(ind).trimmed()).split(delim);
if (tree.front() == "include") { if (tree.front() == "include") {

View File

@@ -2,22 +2,22 @@
* \brief Configuration parser and writer * \brief Configuration parser and writer
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Configuration parser and writer Configuration parser and writer
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PICONFIG_H #ifndef PICONFIG_H
@@ -57,21 +57,21 @@ class PIP_EXPORT PIConfig
friend class Entry; friend class Entry;
friend class Branch; friend class Branch;
public: public:
//! Contructs and read configuration file at path "path" in mode "mode" //! Contructs and read configuration file at path "path" in mode "mode"
PIConfig(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite); PIConfig(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
//! Contructs and read configuration string "string" in mode "mode" //! Contructs and read configuration string "string" in mode "mode"
PIConfig(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite); PIConfig(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
//! Contructs and read configuration from custom device "device" in mode "mode" //! Contructs and read configuration from custom device "device" in mode "mode"
PIConfig(PIIODevice * device = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite); PIConfig(PIIODevice * device = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
~PIConfig(); ~PIConfig();
class Entry; class Entry;
class PIP_EXPORT Branch: public PIVector<Entry * > { class PIP_EXPORT Branch: public PIVector<Entry * > {
friend class PIConfig; friend class PIConfig;
friend class Entry; friend class Entry;
@@ -79,11 +79,11 @@ public:
friend PICout operator <<(PICout s, const Branch & v); friend PICout operator <<(PICout s, const Branch & v);
public: public:
Branch() {;} Branch() {;}
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0); Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<Branch * >(this)->getValue(vname, def, exists);} Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<Branch * >(this)->getValue(vname, def, exists);}
PICONFIG_GET_VALUE PICONFIG_GET_VALUE
Branch allLeaves(); Branch allLeaves();
Branch getValues(const PIString & name); Branch getValues(const PIString & name);
Branch getLeaves(); Branch getLeaves();
@@ -91,212 +91,212 @@ public:
Branch & filter(const PIString & f); Branch & filter(const PIString & f);
bool isEntryExists(const PIString & name) const {piForeachC (Entry * i, *this) if (entryExists(i, name)) return true; return false;} bool isEntryExists(const PIString & name) const {piForeachC (Entry * i, *this) if (entryExists(i, name)) return true; return false;}
int indexOf(const Entry * e) {for (int i = 0; i < size_s(); ++i) if (at(i) == e) return i; return -1;} int indexOf(const Entry * e) {for (int i = 0; i < size_s(); ++i) if (at(i) == e) return i; return -1;}
//void clear() {piForeach (Entry * i, *this) delete i; PIVector<Entry * >::clear();} //void clear() {piForeach (Entry * i, *this) delete i; PIVector<Entry * >::clear();}
private: private:
bool entryExists(const Entry * e, const PIString & name) const; bool entryExists(const Entry * e, const PIString & name) const;
void allLeaves(Branch & b, Entry * e) {piForeach (Entry * i, e->_children) {if (i->isLeaf()) b << i; else allLeaves(b, i);}} void allLeaves(Branch & b, Entry * e) {piForeach (Entry * i, e->_children) {if (i->isLeaf()) b << i; else allLeaves(b, i);}}
void coutt(std::ostream & s, const PIString & p) const {piForeachC (Entry * i, *this) i->coutt(s, p);} void coutt(std::ostream & s, const PIString & p) const {piForeachC (Entry * i, *this) i->coutt(s, p);}
void piCoutt(PICout s, const PIString & p) const {piForeachC (Entry * i, *this) i->piCoutt(s, p);} void piCoutt(PICout s, const PIString & p) const {piForeachC (Entry * i, *this) i->piCoutt(s, p);}
static Entry _empty; static Entry _empty;
PIString delim; PIString delim;
}; };
class PIP_EXPORT Entry { class PIP_EXPORT Entry {
friend class PIConfig; friend class PIConfig;
friend class Branch; friend class Branch;
public: public:
Entry() {_parent = 0; _line = -1;} Entry() {_parent = 0; _line = -1;}
//! Returns parent entry, or 0 if there is no parent (root of default value) //! Returns parent entry, or 0 if there is no parent (root of default value)
Entry * parent() const {return _parent;} Entry * parent() const {return _parent;}
//! Returns children count //! Returns children count
int childCount() const {return _children.size_s();} int childCount() const {return _children.size_s();}
//! Returns children as \a PIConfig::Branch //! Returns children as \a PIConfig::Branch
Branch & children() const {_children.delim = delim; return _children;} Branch & children() const {_children.delim = delim; return _children;}
//! Returns child at index "index" //! Returns child at index "index"
Entry * child(const int index) const {return _children[index];} Entry * child(const int index) const {return _children[index];}
//! Returns first child with name "name" //! Returns first child with name "name"
Entry * findChild(const PIString & name) {piForeach (Entry * i, _children) if (i->_name == name) return i; return 0;} Entry * findChild(const PIString & name) {piForeach (Entry * i, _children) if (i->_name == name) return i; return 0;}
//! Returns first child with name "name" //! Returns first child with name "name"
const Entry * findChild(const PIString & name) const {piForeachC (Entry * i, _children) if (i->_name == name) return i; return 0;} const Entry * findChild(const PIString & name) const {piForeachC (Entry * i, _children) if (i->_name == name) return i; return 0;}
//! Returns \b true if there is no children //! Returns \b true if there is no children
bool isLeaf() const {return _children.isEmpty();} bool isLeaf() const {return _children.isEmpty();}
//! Returns name //! Returns name
const PIString & name() const {return _name;} const PIString & name() const {return _name;}
//! Returns value //! Returns value
const PIString & value() const {return _value;} const PIString & value() const {return _value;}
//! Returns type //! Returns type
const PIString & type() const {return _type;} const PIString & type() const {return _type;}
//! Returns comment //! Returns comment
const PIString & comment() const {return _comment;} const PIString & comment() const {return _comment;}
/** \brief Returns full name, i.e. name as it looks in file /** \brief Returns full name, i.e. name as it looks in file
* \details In case of default entry full name always is empty * \details In case of default entry full name always is empty
* \snippet piconfig.cpp fullName */ * \snippet piconfig.cpp fullName */
const PIString & fullName() const {return _full_name;} const PIString & fullName() const {return _full_name;}
//! Set name to "value" and returns this //! Set name to "value" and returns this
Entry & setName(const PIString & value) {_name = value; return *this;} Entry & setName(const PIString & value) {_name = value; return *this;}
//! Set type to "value" and returns this //! Set type to "value" and returns this
Entry & setType(const PIString & value) {_type = value; return *this;} Entry & setType(const PIString & value) {_type = value; return *this;}
//! Set comment to "value" and returns this //! Set comment to "value" and returns this
Entry & setComment(const PIString & value) {_comment = value; return *this;} Entry & setComment(const PIString & value) {_comment = value; return *this;}
//! Set value to "value" and returns this //! Set value to "value" and returns this
Entry & setValue(const PIString & value) {_value = value; return *this;} Entry & setValue(const PIString & value) {_value = value; return *this;}
//! Set value to "value" and returns this. Type is set to "l" //! Set value to "value" and returns this. Type is set to "l"
Entry & setValue(const PIStringList & value) {setValue(value.join("%|%")); setType("l"); return *this;} Entry & setValue(const PIStringList & value) {setValue(value.join("%|%")); setType("l"); return *this;}
//! Set value to "value" and returns this. Type is set to "s" //! Set value to "value" and returns this. Type is set to "s"
Entry & setValue(const char * value) {setValue(PIString(value)); setType("s"); return *this;} Entry & setValue(const char * value) {setValue(PIString(value)); setType("s"); return *this;}
//! Set value to "value" and returns this. Type is set to "b" //! Set value to "value" and returns this. Type is set to "b"
Entry & setValue(const bool value) {setValue(PIString::fromBool(value)); setType("b"); return *this;} Entry & setValue(const bool value) {setValue(PIString::fromBool(value)); setType("b"); return *this;}
//! Set value to "value" and returns this. Type is set to "s" //! Set value to "value" and returns this. Type is set to "s"
Entry & setValue(const char value) {setValue(PIString(1, value)); setType("s"); return *this;} Entry & setValue(const char value) {setValue(PIString(1, value)); setType("s"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const short value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const short value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const int value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const int value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const long value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const long value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const uchar value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const uchar value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const ushort value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const ushort value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const uint value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const uint value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "n" //! Set value to "value" and returns this. Type is set to "n"
Entry & setValue(const ulong value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;} Entry & setValue(const ulong value) {setValue(PIString::fromNumber(value)); setType("n"); return *this;}
//! Set value to "value" and returns this. Type is set to "f" //! Set value to "value" and returns this. Type is set to "f"
Entry & setValue(const float value) {setValue(PIString::fromNumber(value)); setType("f"); return *this;} Entry & setValue(const float value) {setValue(PIString::fromNumber(value)); setType("f"); return *this;}
//! Set value to "value" and returns this. Type is set to "f" //! Set value to "value" and returns this. Type is set to "f"
Entry & setValue(const double value) {setValue(PIString::fromNumber(value)); setType("f"); return *this;} Entry & setValue(const double value) {setValue(PIString::fromNumber(value)); setType("f"); return *this;}
/** \brief Returns entry with name "vname" and default value "def" /** \brief Returns entry with name "vname" and default value "def"
* \details If there is no suitable entry found, reference to default internal entry with * \details If there is no suitable entry found, reference to default internal entry with
* value = "def" will be returned, and if "exists" not null it will be set to \b false */ * value = "def" will be returned, and if "exists" not null it will be set to \b false */
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0); Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<Entry * >(this)->getValue(vname, def, exists);} Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<Entry * >(this)->getValue(vname, def, exists);}
PICONFIG_GET_VALUE PICONFIG_GET_VALUE
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
//! \brief Returns entry with name "vname" and default value "def" //! \brief Returns entry with name "vname" and default value "def"
//! Find all entries with names with substrings "vname" and returns them as \a PIConfig::Branch //! Find all entries with names with substrings "vname" and returns them as \a PIConfig::Branch
Branch getValues(const PIString & vname); Branch getValues(const PIString & vname);
//! If there is no children returns if name == "name". Else returns if any child has name == "name" //! If there is no children returns if name == "name". Else returns if any child has name == "name"
bool isEntryExists(const PIString & name) const {return entryExists(this, name);} bool isEntryExists(const PIString & name) const {return entryExists(this, name);}
//! Convertion to boolean //! Convertion to boolean
operator bool() {return _value.toBool();} operator bool() {return _value.toBool();}
//! Convertion to char //! Convertion to char
operator char() {return (_value.isEmpty() ? 0 : _value[0].toAscii());} operator char() {return (_value.isEmpty() ? 0 : _value[0].toAscii());}
//! Convertion to short //! Convertion to short
operator short() {return _value.toShort();} operator short() {return _value.toShort();}
//! Convertion to int //! Convertion to int
operator int() {return _value.toInt();} operator int() {return _value.toInt();}
//! Convertion to long //! Convertion to long
operator long() {return _value.toLong();} operator long() {return _value.toLong();}
//! Convertion to uchar //! Convertion to uchar
operator uchar() {return _value.toInt();} operator uchar() {return _value.toInt();}
//! Convertion to ushort //! Convertion to ushort
operator ushort() {return _value.toShort();} operator ushort() {return _value.toShort();}
//! Convertion to uint //! Convertion to uint
operator uint() {return _value.toInt();} operator uint() {return _value.toInt();}
//! Convertion to ulong //! Convertion to ulong
operator ulong() {return _value.toLong();} operator ulong() {return _value.toLong();}
//! Convertion to float //! Convertion to float
operator float() {return _value.toFloat();} operator float() {return _value.toFloat();}
//! Convertion to double //! Convertion to double
operator double() {return _value.toDouble();} operator double() {return _value.toDouble();}
//! Convertion to PIString //! Convertion to PIString
operator PIString() {return _value;} operator PIString() {return _value;}
//! Convertion to PIStringList //! Convertion to PIStringList
operator PIStringList() {return _value.split("%|%");} operator PIStringList() {return _value.split("%|%");}
private: private:
typedef PIConfig::Entry * EntryPtr; typedef PIConfig::Entry * EntryPtr;
static int compare(const EntryPtr * f, const EntryPtr * s) {return (*f)->_line == (*s)->_line ? 0 : (*f)->_line < (*s)->_line ? -1 : 1;} static int compare(const EntryPtr * f, const EntryPtr * s) {return (*f)->_line == (*s)->_line ? 0 : (*f)->_line < (*s)->_line ? -1 : 1;}
@@ -306,7 +306,7 @@ public:
void coutt(std::ostream & s, const PIString & p) const {PIString nl = p + " "; if (!_value.isEmpty()) s << p << _name << " = " << _value << std::endl; else std::cout << p << _name << std::endl; piForeachC (Entry * i, _children) i->coutt(s, nl);} void coutt(std::ostream & s, const PIString & p) const {PIString nl = p + " "; if (!_value.isEmpty()) s << p << _name << " = " << _value << std::endl; else std::cout << p << _name << std::endl; piForeachC (Entry * i, _children) i->coutt(s, nl);}
void piCoutt(PICout s, const PIString & p) const {PIString nl = p + " "; if (!_value.isEmpty()) s << p << _name << " = " << _value << PICoutManipulators::NewLine; else std::cout << p << _name << std::endl; piForeachC (Entry * i, _children) i->piCoutt(s, nl);} void piCoutt(PICout s, const PIString & p) const {PIString nl = p + " "; if (!_value.isEmpty()) s << p << _name << " = " << _value << PICoutManipulators::NewLine; else std::cout << p << _name << std::endl; piForeachC (Entry * i, _children) i->piCoutt(s, nl);}
void deleteBranch() {piForeach (Entry * i, _children) {i->deleteBranch(); delete i;}} void deleteBranch() {piForeach (Entry * i, _children) {i->deleteBranch(); delete i;}}
static Entry _empty; static Entry _empty;
Entry * _parent; Entry * _parent;
mutable Branch _children; mutable Branch _children;
@@ -320,151 +320,151 @@ public:
PIString delim; PIString delim;
int _line; int _line;
}; };
//! Read configuration file at path "path" in mode "mode" //! Read configuration file at path "path" in mode "mode"
bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite); bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
//! Read configuration string "string" in mode "mode" //! Read configuration string "string" in mode "mode"
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);\ bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);\
bool isOpened() const; bool isOpened() const;
//! Returns top-level entry with name "vname", if doesn`t exists return entry with value "def" and set *exist to false //! Returns top-level entry with name "vname", if doesn`t exists return entry with value "def" and set *exist to false
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0); Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<PIConfig * >(this)->getValue(vname, def, exists);} Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {return const_cast<PIConfig * >(this)->getValue(vname, def, exists);}
PICONFIG_GET_VALUE PICONFIG_GET_VALUE
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0) //! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
//! \brief Returns top-level entry with name "vname" and default value "def" //! \brief Returns top-level entry with name "vname" and default value "def"
//! Returns top-level entries with names with substrings "vname" //! Returns top-level entries with names with substrings "vname"
Branch getValues(const PIString & vname); Branch getValues(const PIString & vname);
//! Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true); void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
//! Set top-level entry with name "name" value to "value", type to "l" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "l" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const PIStringList & value, bool write = true) {setValue(name, value.join("%|%"), "l", write);} void setValue(const PIString & name, const PIStringList & value, bool write = true) {setValue(name, value.join("%|%"), "l", write);}
//! Set top-level entry with name "name" value to "value", type to "s" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "s" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const char * value, bool write = true) {setValue(name, PIString(value), "s", write);} void setValue(const PIString & name, const char * value, bool write = true) {setValue(name, PIString(value), "s", write);}
//! Set top-level entry with name "name" value to "value", type to "b" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "b" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const bool value, bool write = true) {setValue(name, PIString::fromBool(value), "b", write);} void setValue(const PIString & name, const bool value, bool write = true) {setValue(name, PIString::fromBool(value), "b", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const short value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const short value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const int value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const int value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const long value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const long value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const uchar value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const uchar value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const ushort value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const ushort value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const uint value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const uint value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const ulong value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);} void setValue(const PIString & name, const ulong value, bool write = true) {setValue(name, PIString::fromNumber(value), "n", write);}
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const float value, bool write = true) {setValue(name, PIString::fromNumber(value), "f", write);} void setValue(const PIString & name, const float value, bool write = true) {setValue(name, PIString::fromNumber(value), "f", write);}
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is no suitable exists //! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is no suitable exists
void setValue(const PIString & name, const double value, bool write = true) {setValue(name, PIString::fromNumber(value), "f", write);} void setValue(const PIString & name, const double value, bool write = true) {setValue(name, PIString::fromNumber(value), "f", write);}
//! Returns root entry //! Returns root entry
Entry & rootEntry() {return root;} Entry & rootEntry() {return root;}
//! Returns top-level entries count //! Returns top-level entries count
int entriesCount() const {return childCount(&root);} int entriesCount() const {return childCount(&root);}
//! Returns if top-level entry with name "name" exists //! Returns if top-level entry with name "name" exists
bool isEntryExists(const PIString & name) const {return entryExists(&root, name);} bool isEntryExists(const PIString & name) const {return entryExists(&root, name);}
//! Returns all top-level entries //! Returns all top-level entries
Branch allTree() {Branch b; piForeach (Entry * i, root._children) b << i; b.delim = delim; return b;} Branch allTree() {Branch b; piForeach (Entry * i, root._children) b << i; b.delim = delim; return b;}
//! Returns all entries without children //! Returns all entries without children
Branch allLeaves() {Branch b; allLeaves(b, &root); b.sort(Entry::compare); b.delim = delim; return b;} Branch allLeaves() {Branch b; allLeaves(b, &root); b.sort(Entry::compare); b.delim = delim; return b;}
int entryIndex(const PIString & name); int entryIndex(const PIString & name);
PIString getName(uint number) {return entryByIndex(number)._name;} PIString getName(uint number) {return entryByIndex(number)._name;}
PIString getValue(uint number) {return entryByIndex(number)._value;} PIString getValue(uint number) {return entryByIndex(number)._value;}
PIChar getType(uint number) {return entryByIndex(number)._type[0];} PIChar getType(uint number) {return entryByIndex(number)._type[0];}
PIString getComment(uint number) {return entryByIndex(number)._comment;} PIString getComment(uint number) {return entryByIndex(number)._comment;}
void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true); void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
void setName(uint number, const PIString & name, bool write = true); void setName(uint number, const PIString & name, bool write = true);
void setValue(uint number, const PIString & value, bool write = true); void setValue(uint number, const PIString & value, bool write = true);
void setType(uint number, const PIString & type, bool write = true); void setType(uint number, const PIString & type, bool write = true);
void setComment(uint number, const PIString & comment, bool write = true); void setComment(uint number, const PIString & comment, bool write = true);
void removeEntry(const PIString & name, bool write = true); void removeEntry(const PIString & name, bool write = true);
void removeEntry(uint number, bool write = true); void removeEntry(uint number, bool write = true);
//! Remove all tree and device content //! Remove all tree and device content
void clear(); void clear();
//! Parse device and build internal tree //! Parse device and build internal tree
void readAll(); void readAll();
//! Write all internal tree to device //! Write all internal tree to device
void writeAll(); void writeAll();
//! Returns current tree delimiter, default "." //! Returns current tree delimiter, default "."
const PIString & delimiter() const {return delim;} const PIString & delimiter() const {return delim;}
//! Set current tree delimiter //! Set current tree delimiter
void setDelimiter(const PIString & d) {delim = d; setEntryDelim(&root, d); readAll();} void setDelimiter(const PIString & d) {delim = d; setEntryDelim(&root, d); readAll();}
private: private:
PIConfig(const PIString & path, PIStringList dirs); PIConfig(const PIString & path, PIStringList dirs);
void _init(); void _init();
@@ -486,7 +486,7 @@ private:
void updateIncludes(); void updateIncludes();
PIString parseLine(PIString v); PIString parseLine(PIString v);
void parse(); void parse();
bool own_dev, internal; bool own_dev, internal;
PIVector<PIConfig * > includes, inc_devs; PIVector<PIConfig * > includes, inc_devs;
Branch all_includes; Branch all_includes;
@@ -524,7 +524,7 @@ T readDeviceSetting(const PIString & name, const T & def, const PIConfig::Entry
return ret; return ret;
} }
return em->getValue(name, def); return em->getValue(name, def);
} }
#endif // PICONFIG_H #endif // PICONFIG_H

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
File File
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pifile.h" #include "pifile.h"
@@ -64,14 +64,14 @@
/*! \class PIFile /*! \class PIFile
* \brief Local file * \brief Local file
* *
* \section PIFile_sec0 Synopsis * \section PIFile_sec0 Synopsis
* This class provide access to local file. You can manipulate * This class provide access to local file. You can manipulate
* binary content or use this class as text stream. To binary * binary content or use this class as text stream. To binary
* access there are function \a read(), \a write(), and many * access there are function \a read(), \a write(), and many
* \a writeBinary() functions. For write variables to file in * \a writeBinary() functions. For write variables to file in
* their text representation threr are many "<<" operators. * their text representation threr are many "<<" operators.
* *
* \section PIFile_sec1 Position * \section PIFile_sec1 Position
* Each opened file has a read/write position - logical position * Each opened file has a read/write position - logical position
* in the file content you read from or you write to. You can * in the file content you read from or you write to. You can
@@ -79,10 +79,10 @@
* \a seek(llong position) move position to position "position", * \a seek(llong position) move position to position "position",
* \a seekToBegin() move position to the begin of file, * \a seekToBegin() move position to the begin of file,
* \a seekToEnd() move position to the end of file. * \a seekToEnd() move position to the end of file.
* *
*/ */
REGISTER_DEVICE(PIFile); REGISTER_DEVICE(PIFile)
PIString PIFile::FileInfo::name() const { PIString PIFile::FileInfo::name() const {
@@ -122,14 +122,14 @@ PIString PIFile::FileInfo::dir() const {
PIFile::PIFile(): PIIODevice() { PIFile::PIFile(): PIIODevice() {
fd = 0; fd = 0;
fdi = -1; fdi = -1;
setPrecision(5); setPrecision(5);
} }
PIFile::PIFile(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode) { PIFile::PIFile(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode) {
fd = 0; fd = 0;
fdi = -1; fdi = -1;
setPrecision(5); setPrecision(5);
if (!path.isEmpty()) if (!path.isEmpty())
@@ -138,8 +138,8 @@ PIFile::PIFile(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(p
PIFile::PIFile(const PIFile & other) { PIFile::PIFile(const PIFile & other) {
fd = 0; fd = 0;
fdi = -1; fdi = -1;
setPrecision(other.prec_); setPrecision(other.prec_);
setPath(other.path()); setPath(other.path());
mode_ = other.mode_; mode_ = other.mode_;
@@ -477,7 +477,7 @@ PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
_stat_call_(path.data(), &fs); _stat_call_(path.data(), &fs);
int mode = fs.st_mode; int mode = fs.st_mode;
ret.size = fs.st_size; ret.size = fs.st_size;
ret.id_user = fs.st_uid; ret.id_user = fs.st_uid;
ret.id_group = fs.st_gid; ret.id_group = fs.st_gid;
#ifdef ANDROID #ifdef ANDROID
ret.time_access = PIDateTime::fromSystemTime(PISystemTime(fs.st_atime, fs.st_atime_nsec)); ret.time_access = PIDateTime::fromSystemTime(PISystemTime(fs.st_atime, fs.st_atime_nsec));

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Packets extractor Packets extractor
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pipacketextractor.h" #include "pipacketextractor.h"
@@ -27,14 +27,14 @@
* This class implements packet recognition by various algorithms and custom * This class implements packet recognition by various algorithms and custom
* validating from data stream. Stream is formed from child %PIIODevice * validating from data stream. Stream is formed from child %PIIODevice
* passed from contructor or with function \a setDevice(). * passed from contructor or with function \a setDevice().
* *
* \section PIPacketExtractor_work Principle of work * \section PIPacketExtractor_work Principle of work
* %PIPacketExtractor works with child %PIIODevice. \a read and \a write * %PIPacketExtractor works with child %PIIODevice. \a read and \a write
* functions directly call child device functions. You should start threaded * functions directly call child device functions. You should start threaded
* read of \b extractor (not child device) to proper work. Extractor read data * read of \b extractor (not child device) to proper work. Extractor read data
* from child device, try to detect packet from readed data and raise * from child device, try to detect packet from readed data and raise
* \a packetReceived() event on success. * \a packetReceived() event on success.
* *
* \section PIPacketExtractor_algorithms Algorithms * \section PIPacketExtractor_algorithms Algorithms
* There are 6 algorithms: \n * There are 6 algorithms: \n
* * PIPacketExtractor::None \n * * PIPacketExtractor::None \n
@@ -63,13 +63,13 @@
* * PIPacketExtractor::Timeout \n * * PIPacketExtractor::Timeout \n
* Wait for first read, then read for \a timeout() milliseconds and raise * Wait for first read, then read for \a timeout() milliseconds and raise
* \a packetReceived() event. \n * \a packetReceived() event. \n
* *
* \section PIPacketExtractor_control Control validating * \section PIPacketExtractor_control Control validating
* There are three parameters: * There are three parameters:
* * header content * * header content
* * header size * * header size
* * payload size * * payload size
* *
* Extractor can detect packet with compare your header with readed data. * Extractor can detect packet with compare your header with readed data.
* It is default implementation of function \a packetHeaderValidate(). * It is default implementation of function \a packetHeaderValidate().
* If header validating passed, function \a packetValidate() will be called. * If header validating passed, function \a packetValidate() will be called.
@@ -77,10 +77,10 @@
* and takes next header. If both functions returns \b true extractor shifts * and takes next header. If both functions returns \b true extractor shifts
* by whole packet size. * by whole packet size.
* \image html packet_detection.png * \image html packet_detection.png
* *
* */ * */
REGISTER_DEVICE(PIPacketExtractor); REGISTER_DEVICE(PIPacketExtractor)
PIPacketExtractor::PIPacketExtractor(PIIODevice * device_, PIPacketExtractor::SplitMode mode) { PIPacketExtractor::PIPacketExtractor(PIIODevice * device_, PIPacketExtractor::SplitMode mode) {

View File

@@ -2,22 +2,22 @@
* \brief Packets extractor * \brief Packets extractor
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Packets extractor Packets extractor
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
@@ -34,7 +34,7 @@ class PIP_EXPORT PIPacketExtractor: public PIIODevice
PIIODEVICE(PIPacketExtractor) PIIODEVICE(PIPacketExtractor)
friend class PIConnection; friend class PIConnection;
public: public:
//! Extract algorithms //! Extract algorithms
enum SplitMode { enum SplitMode {
None /** No data processing */ , None /** No data processing */ ,
@@ -44,91 +44,91 @@ public:
Size /** Detect packets with \a packetSize() */ , Size /** Detect packets with \a packetSize() */ ,
Timeout /** Wait for first read, then read for \a timeout() milliseconds */ Timeout /** Wait for first read, then read for \a timeout() milliseconds */
}; };
//! Contructs extractor with child device "device_" and extract algorithm "mode" //! Contructs extractor with child device "device_" and extract algorithm "mode"
PIPacketExtractor(PIIODevice * device_ = 0, SplitMode mode = None); PIPacketExtractor(PIIODevice * device_ = 0, SplitMode mode = None);
virtual ~PIPacketExtractor() {stop();} virtual ~PIPacketExtractor() {stop();}
//! Returns child %device //! Returns child %device
PIIODevice * device() {return dev;} PIIODevice * device() {return dev;}
//! Set child %device to "device_" //! Set child %device to "device_"
void setDevice(PIIODevice * device_); void setDevice(PIIODevice * device_);
//! Returns buffer size //! Returns buffer size
int bufferSize() const {return buffer_size;} int bufferSize() const {return buffer_size;}
//! Set buffer size to "new_size" bytes, should be at least greater than whole packet size //! Set buffer size to "new_size" bytes, should be at least greater than whole packet size
void setBufferSize(int new_size) {buffer_size = new_size; buffer.resize(buffer_size); memset(buffer.data(), 0, buffer.size());} void setBufferSize(int new_size) {buffer_size = new_size; buffer.resize(buffer_size); memset(buffer.data(), 0, buffer.size());}
void setHeaderCheckSlot(PacketExtractorCheckFunc f) {ret_func_header = f;} void setHeaderCheckSlot(PacketExtractorCheckFunc f) {ret_func_header = f;}
void setFooterCheckSlot(PacketExtractorCheckFunc f) {ret_func_footer = f;} void setFooterCheckSlot(PacketExtractorCheckFunc f) {ret_func_footer = f;}
void setPayloadCheckSlot(ReadRetFunc f) {ret_func_ = f;} void setPayloadCheckSlot(ReadRetFunc f) {ret_func_ = f;}
//! Set extract algorithm //! Set extract algorithm
void setSplitMode(SplitMode mode) {setProperty("splitMode", int(mode)); mode_ = mode;} void setSplitMode(SplitMode mode) {setProperty("splitMode", int(mode)); mode_ = mode;}
//! Set payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms //! Set payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms
void setPayloadSize(int size); void setPayloadSize(int size);
//! Set header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms //! Set header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms
void setHeader(const PIByteArray & data); void setHeader(const PIByteArray & data);
//! Set footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms //! Set footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms
void setFooter(const PIByteArray & data); void setFooter(const PIByteArray & data);
//! Set packet size, used for PIPacketExtractor::Size algorithm //! Set packet size, used for PIPacketExtractor::Size algorithm
void setPacketSize(int size) {setProperty("packetSize", size); packetSize_ = size;} void setPacketSize(int size) {setProperty("packetSize", size); packetSize_ = size;}
//! Set timeout in milliseconds, used for PIPacketExtractor::Timeout algorithm //! Set timeout in milliseconds, used for PIPacketExtractor::Timeout algorithm
void setTimeout(double msecs) {setProperty("timeout", msecs); time_ = msecs;} void setTimeout(double msecs) {setProperty("timeout", msecs); time_ = msecs;}
//! Returns current extract algorithm //! Returns current extract algorithm
SplitMode splitMode() const {return (SplitMode)(property("splitMode").toInt());} SplitMode splitMode() const {return (SplitMode)(property("splitMode").toInt());}
//! Returns current payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms //! Returns current payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms
int payloadSize() const {return property("payloadSize").toInt();} int payloadSize() const {return property("payloadSize").toInt();}
//! Returns current header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms //! Returns current header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms
PIByteArray header() const {return src_header;} PIByteArray header() const {return src_header;}
//! Returns current footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms //! Returns current footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms
PIByteArray footer() const {return src_footer;} PIByteArray footer() const {return src_footer;}
//! Returns current packet size, used for PIPacketExtractor::Size algorithm //! Returns current packet size, used for PIPacketExtractor::Size algorithm
int packetSize() const {return property("packetSize").toInt();} int packetSize() const {return property("packetSize").toInt();}
//! Returns current timeout in milliseconds, used for PIPacketExtractor::Timeout algorithm //! Returns current timeout in milliseconds, used for PIPacketExtractor::Timeout algorithm
double timeout() const {return property("timeout").toDouble();} double timeout() const {return property("timeout").toDouble();}
//! Returns missed by validating functions bytes count //! Returns missed by validating functions bytes count
ullong missedBytes() const {return missed;} ullong missedBytes() const {return missed;}
// //! Returns missed by validating functions packets count, = missedBytes() / packetSize // //! Returns missed by validating functions packets count, = missedBytes() / packetSize
ullong missedPackets() const {/*if (packetSize_hf == 0) return missed; return missed / packetSize_hf*/; return missed_packets;} ullong missedPackets() const {/*if (packetSize_hf == 0) return missed; return missed / packetSize_hf*/; return missed_packets;}
//! Returns pointer to \a missedBytes() count. Useful for output to PIConsole //! Returns pointer to \a missedBytes() count. Useful for output to PIConsole
const ullong * missedBytes_ptr() const {return &missed;} const ullong * missedBytes_ptr() const {return &missed;}
// //! Returns pointer to \a missedPackets() count. Useful for output to PIConsole // //! Returns pointer to \a missedPackets() count. Useful for output to PIConsole
const ullong * missedPackets_ptr() const {return &missed_packets;} const ullong * missedPackets_ptr() const {return &missed_packets;}
//! Directly call \a read() function of child %device //! Directly call \a read() function of child %device
int read(void * read_to, int max_size) {if (dev == 0) return -1; return dev->read(read_to, max_size);} int read(void * read_to, int max_size) {if (dev == 0) return -1; return dev->read(read_to, max_size);}
//! Directly call \a write() function of child %device //! Directly call \a write() function of child %device
int write(const void * data, int max_size) {if (dev == 0) return -1; return dev->write(data, max_size);} int write(const void * data, int max_size) {if (dev == 0) return -1; return dev->write(data, max_size);}
PIString constructFullPath() const; PIString constructFullPath() const;
EVENT2(packetReceived, uchar * , data, int, size) EVENT2(packetReceived, uchar * , data, int, size)
//! \events //! \events
//! \{ //! \{
@@ -138,7 +138,7 @@ public:
//! \} //! \}
protected: protected:
/** \brief Function to validate header /** \brief Function to validate header
* \param src Your header content * \param src Your header content
* \param rec Received header * \param rec Received header
@@ -152,7 +152,7 @@ protected:
* \param size Footer size * \param size Footer size
* \details Default implementation returns by-byte "src" with "rec" compare result */ * \details Default implementation returns by-byte "src" with "rec" compare result */
virtual bool validateFooter(uchar * src, uchar * rec, int size) {if (ret_func_footer != 0) return ret_func_footer(ret_data_, src, rec, size); for (int i = 0; i < size; ++i) if (src[i] != rec[i]) return false; return true;} virtual bool validateFooter(uchar * src, uchar * rec, int size) {if (ret_func_footer != 0) return ret_func_footer(ret_data_, src, rec, size); for (int i = 0; i < size; ++i) if (src[i] != rec[i]) return false; return true;}
/** \brief Function to validate payload /** \brief Function to validate payload
* \param rec Received payload * \param rec Received payload
* \param size payload size * \param size payload size

View File

@@ -124,7 +124,7 @@
* *
*/ */
REGISTER_DEVICE(PISerial); REGISTER_DEVICE(PISerial)
PRIVATE_DEFINITION_START(PISerial) PRIVATE_DEFINITION_START(PISerial)

View File

@@ -2,14 +2,14 @@
#include "piconfig.h" #include "piconfig.h"
#ifdef PIP_USB #ifdef PIP_USB
# ifdef WINDOWS # ifdef WINDOWS
# include <lusb0_usb.h> # include <lusb0_usb.h>
# else # else
# include <usb.h> # include <usb.h>
# endif # endif
#endif #endif
REGISTER_DEVICE(PIUSB); REGISTER_DEVICE(PIUSB)
PIUSB::PIUSB(ushort vid, ushort pid): PIIODevice("", ReadWrite) { PIUSB::PIUSB(ushort vid, ushort pid): PIIODevice("", ReadWrite) {
@@ -218,7 +218,7 @@ bool PIUSB::openDevice() {
} }
if (!desc_.configurations.isEmpty()) if (!desc_.configurations.isEmpty())
conf_ = desc_.configurations.front(); conf_ = desc_.configurations.front();
struct usb_interface_descriptor * is = dev->config->interface->altsetting; struct usb_interface_descriptor * is = dev->config->interface->altsetting;
int epn = is->bNumEndpoints; int epn = is->bNumEndpoints;
eps.clear(); eps.clear();
@@ -229,7 +229,7 @@ bool PIUSB::openDevice() {
if (eps.back().direction == Endpoint::Write && (eps.back().address == ep_write.address || ep_write.address == 0)) ep_write = eps.back(); if (eps.back().direction == Endpoint::Write && (eps.back().address == ep_write.address || ep_write.address == 0)) ep_write = eps.back();
if (eps.back().direction == Endpoint::Read && (eps.back().address == ep_read.address || ep_read.address == 0)) ep_read = eps.back(); if (eps.back().direction == Endpoint::Read && (eps.back().address == ep_read.address || ep_read.address == 0)) ep_read = eps.back();
} }
//piCoutObj << "Device found at address:" << "Bus: " << dev->bus->dirname << ", Device: " << dev->filename; //piCoutObj << "Device found at address:" << "Bus: " << dev->bus->dirname << ", Device: " << dev->filename;
found = true; found = true;
break; break;
@@ -249,7 +249,7 @@ bool PIUSB::openDevice() {
return false; return false;
}// else piCoutObj << "ok"; }// else piCoutObj << "ok";
//usb_reset(hdev); //usb_reset(hdev);
//usb_set_configuration(hdev, 1); //usb_set_configuration(hdev, 1);
//usb_set_altinterface(hdev, 0); //usb_set_altinterface(hdev, 0);
@@ -272,7 +272,7 @@ bool PIUSB::openDevice() {
return false; return false;
} // else piCoutObj << "ok"; } // else piCoutObj << "ok";
interface_claimed = intefrace_; interface_claimed = intefrace_;
return true; return true;
#else #else
return false; return false;

View File

@@ -2,22 +2,22 @@
* \brief USB device * \brief USB device
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
USB, based on libusb USB, based on libusb
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIUSB_H #ifndef PIUSB_H
@@ -33,18 +33,18 @@ class PIP_EXPORT PIUSB: public PIIODevice
public: public:
PIUSB(ushort vid = 0, ushort pid = 0); PIUSB(ushort vid = 0, ushort pid = 0);
~PIUSB() {closeDevice();} ~PIUSB() {closeDevice();}
struct Endpoint { struct Endpoint {
Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {address = a; attributes = at; max_packet_size = mps; parse();} Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {address = a; attributes = at; max_packet_size = mps; parse();}
enum Direction {Write = 0, Read = 1}; enum Direction {Write = 0, Read = 1};
enum TransferType {Control = 0, Isochronous = 1, Bulk = 2, Interrupt = 3}; enum TransferType {Control = 0, Isochronous = 1, Bulk = 2, Interrupt = 3};
enum SynchronisationType {NoSynchonisation= 0, Asynchronous = 2, Adaptive = 1, Synchronous = 3}; enum SynchronisationType {NoSynchonisation= 0, Asynchronous = 2, Adaptive = 1, Synchronous = 3};
enum UsageType {DataEndpoint = 0, FeedbackEndpoint = 2, ExplicitFeedbackDataEndpoint = 1}; enum UsageType {DataEndpoint = 0, FeedbackEndpoint = 2, ExplicitFeedbackDataEndpoint = 1};
void parse(); void parse();
bool isNull() const {return address == 0;} bool isNull() const {return address == 0;}
uchar address; uchar address;
uchar attributes; uchar attributes;
ushort max_packet_size; ushort max_packet_size;
@@ -53,7 +53,7 @@ public:
SynchronisationType synchronisation_type; SynchronisationType synchronisation_type;
UsageType usage_type; UsageType usage_type;
}; };
struct Interface { struct Interface {
Interface() {index = value_to_select = class_code = subclass_code = protocol_code = 0;} Interface() {index = value_to_select = class_code = subclass_code = protocol_code = 0;}
uchar index; uchar index;
@@ -74,7 +74,7 @@ public:
bool remote_wakeup; bool remote_wakeup;
PIVector<PIUSB::Interface> interfaces; PIVector<PIUSB::Interface> interfaces;
}; };
struct Descriptor { struct Descriptor {
Descriptor() {memset(this, 0, sizeof(Descriptor));} Descriptor() {memset(this, 0, sizeof(Descriptor));}
ushort usb_spec_number; ushort usb_spec_number;
@@ -90,45 +90,45 @@ public:
uchar index_serial; uchar index_serial;
PIVector<PIUSB::Configuration> configurations; PIVector<PIUSB::Configuration> configurations;
}; };
const PIUSB::Descriptor & currentDescriptor() const {return desc_;} const PIUSB::Descriptor & currentDescriptor() const {return desc_;}
const PIUSB::Configuration & currentConfiguration() const {return conf_;} const PIUSB::Configuration & currentConfiguration() const {return conf_;}
const PIUSB::Interface & currentInterface() const {return iface_;} const PIUSB::Interface & currentInterface() const {return iface_;}
ushort vendorID() const {return vid_;} ushort vendorID() const {return vid_;}
ushort productID() const {return pid_;} ushort productID() const {return pid_;}
int deviceNumber() const {return property("deviceNumber").toInt();} int deviceNumber() const {return property("deviceNumber").toInt();}
int timeoutRead() const {return property("timeoutRead").toInt();} int timeoutRead() const {return property("timeoutRead").toInt();}
int timeoutWrite() const {return property("timeoutWrite").toInt();} int timeoutWrite() const {return property("timeoutWrite").toInt();}
const PIUSB::Endpoint & endpointRead() const {return ep_read;} const PIUSB::Endpoint & endpointRead() const {return ep_read;}
const PIUSB::Endpoint & endpointWrite() const {return ep_write;} const PIUSB::Endpoint & endpointWrite() const {return ep_write;}
const PIVector<PIUSB::Endpoint> & endpoints() const {return eps;} const PIVector<PIUSB::Endpoint> & endpoints() const {return eps;}
PIVector<PIUSB::Endpoint> endpointsRead(); PIVector<PIUSB::Endpoint> endpointsRead();
PIVector<PIUSB::Endpoint> endpointsWrite(); PIVector<PIUSB::Endpoint> endpointsWrite();
PIUSB::Endpoint getEndpointByAddress(uchar address); PIUSB::Endpoint getEndpointByAddress(uchar address);
void setVendorID(ushort vid) {vid_ = vid; setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0"));} void setVendorID(ushort vid) {vid_ = vid; setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0"));}
void setProductID(ushort pid) {pid_ = pid; setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0"));} void setProductID(ushort pid) {pid_ = pid; setPath(PIString::fromNumber(vid_, 16).expandLeftTo(4, "0") + ":" + PIString::fromNumber(pid_, 16).expandLeftTo(4, "0"));}
bool setConfiguration(uchar value); bool setConfiguration(uchar value);
bool setInterface(uchar value); bool setInterface(uchar value);
void setEndpointRead(const PIUSB::Endpoint & ep) {ep_read = ep;} void setEndpointRead(const PIUSB::Endpoint & ep) {ep_read = ep;}
void setEndpointWrite(const PIUSB::Endpoint & ep) {ep_write = ep;} void setEndpointWrite(const PIUSB::Endpoint & ep) {ep_write = ep;}
void setDeviceNumber(int dn) {setProperty("deviceNumber", dn);} void setDeviceNumber(int dn) {setProperty("deviceNumber", dn);}
void setTimeoutRead(int t) {setProperty("timeoutRead", t);} void setTimeoutRead(int t) {setProperty("timeoutRead", t);}
void setTimeoutWrite(int t) {setProperty("timeoutWrite", t);} void setTimeoutWrite(int t) {setProperty("timeoutWrite", t);}
int read(void * read_to, int max_size); int read(void * read_to, int max_size);
int write(const void * data, int max_size); int write(const void * data, int max_size);
int controlWrite(const void * data, int max_size); int controlWrite(const void * data, int max_size);
void flush(); void flush();
PIString constructFullPath() const; PIString constructFullPath() const;
protected: protected:
PIString fullPathPrefix() const {return "usb";} PIString fullPathPrefix() const {return "usb";}
void configureFromFullPath(const PIString & full_path); void configureFromFullPath(const PIString & full_path);
@@ -136,7 +136,7 @@ protected:
//bool init(); //bool init();
bool openDevice(); bool openDevice();
bool closeDevice(); bool closeDevice();
PIVector<PIUSB::Endpoint> eps; PIVector<PIUSB::Endpoint> eps;
ushort vid_, pid_; ushort vid_, pid_;
int intefrace_, timeout_r, timeout_w; int intefrace_, timeout_r, timeout_w;
@@ -146,7 +146,7 @@ protected:
Configuration conf_; Configuration conf_;
Interface iface_; Interface iface_;
usb_dev_handle * hdev; usb_dev_handle * hdev;
}; };
PICout operator <<(PICout s, const PIUSB::Endpoint & v); PICout operator <<(PICout s, const PIUSB::Endpoint & v);

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Evaluator designed for stream computing Evaluator designed for stream computing
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "pievaluator.h" #include "pievaluator.h"
@@ -22,7 +22,7 @@
/*! \class PIEvaluator /*! \class PIEvaluator
* \brief This class provide mathematical evaluations of custom expression * \brief This class provide mathematical evaluations of custom expression
* *
* \section PIEvaluator_sec0 Synopsis * \section PIEvaluator_sec0 Synopsis
* %PIEvaluator developed for stream evaluations of once set expression. * %PIEvaluator developed for stream evaluations of once set expression.
* It`s create internal list of instructions on function \a check() and * It`s create internal list of instructions on function \a check() and
@@ -40,7 +40,7 @@
* you can get processed expression with function \a expression() and * you can get processed expression with function \a expression() and
* evaluate it with function \a evaluate(). You can change variable values * evaluate it with function \a evaluate(). You can change variable values
* without rechecking expression. * without rechecking expression.
* *
* \section PIEvaluator_sec2 Functions * \section PIEvaluator_sec2 Functions
* %PIEvaluator supports arithmetical operations with complex numbers, this * %PIEvaluator supports arithmetical operations with complex numbers, this
* is their list in priority order: * is their list in priority order:
@@ -50,7 +50,7 @@
* * % (residue) * * % (residue)
* * + (add) * * + (add)
* * - (subtract) * * - (subtract)
* *
* In addition there are compare and logical operations: * In addition there are compare and logical operations:
* * == (equal) * * == (equal)
* * != (not equal) * * != (not equal)
@@ -60,9 +60,9 @@
* * <= (smaller or equal) * * <= (smaller or equal)
* * && (and) * * && (and)
* * || (or) * * || (or)
* *
* Compare and logical functions works with real operators part and returns 0 or 1. * Compare and logical functions works with real operators part and returns 0 or 1.
* *
* Mathematical functions: * Mathematical functions:
* * sin(x) - sine * * sin(x) - sine
* * cos(x) - cosine * * cos(x) - cosine
@@ -104,14 +104,14 @@
* * clamp(x, a, b) - trim x on range [a, b] * * clamp(x, a, b) - trim x on range [a, b]
* * step(x, s) - 0 if x < s, else 1 * * step(x, s) - 0 if x < s, else 1
* * mix(x, a, b) - interpolate between a and b linear for x (a * (1 - x) + b * x) * * mix(x, a, b) - interpolate between a and b linear for x (a * (1 - x) + b * x)
* *
* There are some built-in constans: * There are some built-in constans:
* * i (imaginary 1) * * i (imaginary 1)
* * e * * e
* * pi * * pi
* *
* All trigonometric functions takes angle in radians. * All trigonometric functions takes angle in radians.
* *
* \section PIEvaluator_sec3 Example * \section PIEvaluator_sec3 Example
* \snippet pievaluator.cpp main * \snippet pievaluator.cpp main
*/ */

View File

@@ -2,22 +2,22 @@
* \brief Mathematic expressions calculator * \brief Mathematic expressions calculator
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Evaluator designed for stream calculations Evaluator designed for stream calculations
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#ifndef PIEVALUATOR_H #ifndef PIEVALUATOR_H
@@ -30,7 +30,7 @@ typedef complexd (*FuncFunc)(void * , int, complexd * );
namespace PIEvaluatorTypes { namespace PIEvaluatorTypes {
static const int operationCount = 14; static const int operationCount = 14;
enum eType {etNumber, etOperator, etVariable, etFunction}; enum eType {etNumber, etOperator, etVariable, etFunction};
enum Operation {oNone, oAdd, oSubtract, oMultiply, oDivide, oResidue, oPower, enum Operation {oNone, oAdd, oSubtract, oMultiply, oDivide, oResidue, oPower,
oEqual, oNotEqual, oGreater, oSmaller, oGreaterEqual, oSmallerEqual, oEqual, oNotEqual, oGreater, oSmaller, oGreaterEqual, oSmallerEqual,
@@ -47,9 +47,9 @@ namespace PIEvaluatorTypes {
bfClamp, bfStep, bfMix, bfDefined, bfClamp, bfStep, bfMix, bfDefined,
bfCustom = 0xFFFF bfCustom = 0xFFFF
}; };
struct Instruction { struct Instruction {
Instruction() {out = -1; function = -1; operation = oNone;} Instruction() {out = -1; function = -1; operation = oNone;}
Instruction(Operation oper, PIVector<int> opers, int out_ind, int func = -1) { Instruction(Operation oper, PIVector<int> opers, int out_ind, int func = -1) {
operation = oper; operators = opers; out = out_ind; function = func;} operation = oper; operators = opers; out = out_ind; function = func;}
Operation operation; Operation operation;
@@ -58,7 +58,7 @@ namespace PIEvaluatorTypes {
int function; int function;
}; };
struct Element { struct Element {
Element() {num = 0; var_num = -1; type = etNumber;} Element() {num = 0; var_num = -1; type = etNumber;}
Element(eType new_type, int new_num, int new_var_num = -1) {set(new_type, new_num, new_var_num);} Element(eType new_type, int new_num, int new_var_num = -1) {set(new_type, new_num, new_var_num);}
void set(eType new_type, int new_num, int new_var_num = -1) {type = new_type; num = new_num; var_num = new_var_num;} void set(eType new_type, int new_num, int new_var_num = -1) {type = new_type; num = new_num; var_num = new_var_num;}
eType type; eType type;
@@ -95,7 +95,7 @@ class PIP_EXPORT PIEvaluatorContent
public: public:
PIEvaluatorContent(); PIEvaluatorContent();
~PIEvaluatorContent() {;} ~PIEvaluatorContent() {;}
void addFunction(const PIString & name, int args = 1) {functions.push_back(PIEvaluatorTypes::Function(name, args, getBaseFunction(name)));} void addFunction(const PIString & name, int args = 1) {functions.push_back(PIEvaluatorTypes::Function(name, args, getBaseFunction(name)));}
void addVariable(const PIString & name, const complexd & val = 0.) {variables.push_back(PIEvaluatorTypes::Variable(name, val)); sortVariables();} void addVariable(const PIString & name, const complexd & val = 0.) {variables.push_back(PIEvaluatorTypes::Variable(name, val)); sortVariables();}
void addCustomFunction(const PIString & name, int args_count, FuncFunc func) {functions << PIEvaluatorTypes::Function(name, args_count, func);} void addCustomFunction(const PIString & name, int args_count, FuncFunc func) {functions << PIEvaluatorTypes::Function(name, args_count, func);}
@@ -118,38 +118,38 @@ public:
void clearCustomVariables(); void clearCustomVariables();
void sortVariables(); void sortVariables();
PIEvaluatorTypes::BaseFunctions getBaseFunction(const PIString & name); PIEvaluatorTypes::BaseFunctions getBaseFunction(const PIString & name);
private: private:
PIVector<PIEvaluatorTypes::Function> functions; PIVector<PIEvaluatorTypes::Function> functions;
PIVector<PIEvaluatorTypes::Variable> variables; PIVector<PIEvaluatorTypes::Variable> variables;
int cv_count; int cv_count;
}; };
class PIP_EXPORT PIEvaluator class PIP_EXPORT PIEvaluator
{ {
public: public:
//! Constructs an empty evaluator //! Constructs an empty evaluator
PIEvaluator() {correct = false; data_ = 0;} PIEvaluator() {correct = false; data_ = 0;}
~PIEvaluator() {;} ~PIEvaluator() {;}
//! Returns custom data //! Returns custom data
void * data() {return data_;} void * data() {return data_;}
//! Set custom data to "_data" //! Set custom data to "_data"
void setData(void * _data) {data_ = _data;} void setData(void * _data) {data_ = _data;}
//! Check mathematical expression and parse it to list of instructions //! Check mathematical expression and parse it to list of instructions
bool check(const PIString & string); bool check(const PIString & string);
//! Returns true if expression was checked succesfully //! Returns true if expression was checked succesfully
bool isCorrect() const {return correct;} bool isCorrect() const {return correct;}
//! Set variable value with name "name" to value "value". Add variable if it doesn`t exists //! Set variable value with name "name" to value "value". Add variable if it doesn`t exists
int setVariable(const PIString & name, complexd value = 0.) {if (content.findVariable(name) < 0) content.addVariable(name, value); else content.setVariableValue(name, value); return content.findVariable(name);} int setVariable(const PIString & name, complexd value = 0.) {if (content.findVariable(name) < 0) content.addVariable(name, value); else content.setVariableValue(name, value); return content.findVariable(name);}
@@ -172,21 +172,21 @@ public:
//! Returns index of variable with name "name" //! Returns index of variable with name "name"
int variableIndex(const PIString & name) const {return content.findVariable(name);} int variableIndex(const PIString & name) const {return content.findVariable(name);}
//! Returns all unknown variables founded in last expression passed to \a check() function //! Returns all unknown variables founded in last expression passed to \a check() function
const PIStringList & unknownVariables() const {return unknownVars;} const PIStringList & unknownVariables() const {return unknownVars;}
//! Returns processed last expression passed to \a check() function //! Returns processed last expression passed to \a check() function
const PIString & expression() const {return currentString;} const PIString & expression() const {return currentString;}
//! Returns last error description occured in \a check() function //! Returns last error description occured in \a check() function
const PIString & error() const {return lastError;} const PIString & error() const {return lastError;}
//! Returns last result of \a evaluate() //! Returns last result of \a evaluate()
const complexd & lastResult() const {return out;} const complexd & lastResult() const {return out;}
PIEvaluatorContent content; PIEvaluatorContent content;
private: private:
const PIString & prepare(const PIString & string); const PIString & prepare(const PIString & string);
const PIString & preprocess(const PIString & string); const PIString & preprocess(const PIString & string);
@@ -210,7 +210,7 @@ private:
complexd value(const int & index) {if (index < 0) return tmpvars[-index - 1].value; else return kvars->at(index).value;} complexd value(const int & index) {if (index < 0) return tmpvars[-index - 1].value; else return kvars->at(index).value;}
inline complexd residue(const complexd & f, const complexd & s); inline complexd residue(const complexd & f, const complexd & s);
inline void execFunction(const PIEvaluatorTypes::Instruction & ci); inline void execFunction(const PIEvaluatorTypes::Instruction & ci);
PIVector<PIEvaluatorTypes::Element> elements; PIVector<PIEvaluatorTypes::Element> elements;
PIVector<PIEvaluatorTypes::Variable> currentVariables, variables, tmpvars, * kvars; PIVector<PIEvaluatorTypes::Variable> currentVariables, variables, tmpvars, * kvars;
PIVector<PIEvaluatorTypes::Instruction> instructions; PIVector<PIEvaluatorTypes::Instruction> instructions;

View File

@@ -41,7 +41,7 @@ public:
fp & operator =(const float &v) {val = PIFixedPoint(v).val; return *this;} fp & operator =(const float &v) {val = PIFixedPoint(v).val; return *this;}
fp & operator =(const double &v) {val = PIFixedPoint(v).val; return *this;} fp & operator =(const double &v) {val = PIFixedPoint(v).val; return *this;}
fp & operator =(const long double &v) {val = PIFixedPoint(v).val; return *this;} fp & operator =(const long double &v) {val = PIFixedPoint(v).val; return *this;}
fp operator -() {fp p = fp(*this); p.val = -val; return p;} fp operator -() {fp p = fp(*this); p.val = -val; return p;}
bool operator ==(const fp & v) const {return val == v.val;} bool operator ==(const fp & v) const {return val == v.val;}
bool operator !=(const fp & v) const {return val != v.val;} bool operator !=(const fp & v) const {return val != v.val;}

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Process Process
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "piprocess.h" #include "piprocess.h"
@@ -39,7 +39,7 @@ PIProcess::PIProcess(): PIThread() {
is_exec = false; is_exec = false;
g_in = g_out = g_err = false; g_in = g_out = g_err = false;
t_in = t_out = t_err = false; t_in = t_out = t_err = false;
tf_in = tf_out = tf_err = 0; tf_in = tf_out = tf_err = 0;
env = PIProcess::currentEnvironment(); env = PIProcess::currentEnvironment();
} }
@@ -181,7 +181,7 @@ void PIProcess::startProc(bool detached) {
is_exec = false; is_exec = false;
for (int i = 0; i < env.size_s(); ++i) for (int i = 0; i < env.size_s(); ++i)
delete e[i]; delete e[i];
delete[] e; delete[] e;
#ifdef WINDOWS #ifdef WINDOWS
delete a; delete a;
#else #else

View File

@@ -67,7 +67,7 @@ public:
void clearEnvironment() {env.clear();} void clearEnvironment() {env.clear();}
void removeEnvironmentVariable(const PIString & variable); void removeEnvironmentVariable(const PIString & variable);
void setEnvironmentVariable(const PIString & variable, const PIString & value); void setEnvironmentVariable(const PIString & variable, const PIString & value);
EVENT_HANDLER1(void, exec, const PIString & , program) {args.clear(); args << program; exec_();} EVENT_HANDLER1(void, exec, const PIString & , program) {args.clear(); args << program; exec_();}
EVENT_HANDLER2(void, exec, const PIString & , program, const PIString & , arg) {args.clear(); args << program << arg; exec_();} EVENT_HANDLER2(void, exec, const PIString & , program, const PIString & , arg) {args.clear(); args << program << arg; exec_();}
EVENT_HANDLER2(void, exec, const PIString & , program, const PIStringList & , args_) {args << program << args_; exec_();} EVENT_HANDLER2(void, exec, const PIString & , program, const PIStringList & , args_) {args << program << args_; exec_();}

View File

@@ -1,20 +1,20 @@
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Code model generator Code model generator
Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru Copyright (C) 2016 Ivan Pelipenko peri4ko@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or the Free Software Foundation, either version 3 of the License, or
(at your option) any later version. (at your option) any later version.
This program is distributed in the hope that it will be useful, This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details. GNU General Public License for more details.
You should have received a copy of the GNU General Public License You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
#include "picli.h" #include "picli.h"
@@ -156,12 +156,12 @@ void makeClassStreamHeader(PIFile & f, const PICodeParser::Entity * e) {
void writeModel(PICodeParser & parser, const PIString out, bool meta, bool enums, bool streams, bool texts) { void writeModel(PICodeParser & parser, const PIString out, bool meta, bool enums, bool streams, bool texts) {
PIVector<const PICodeParser::Entity * > ventities; PIVector<const PICodeParser::Entity * > ventities;
PIString defname = out.replaceAll(".", "_").replaceAll("/", "_").replaceAll(":", "_").replaceAll("-", "_").toUpperCase() + "_H"; PIString defname = out.replaceAll(".", "_").replaceAll("/", "_").replaceAll(":", "_").replaceAll("-", "_").toUpperCase() + "_H";
PISet<PIString> inc_files; PISet<PIString> inc_files;
piForeachC (PICodeParser::Entity * e, parser.entities) piForeachC (PICodeParser::Entity * e, parser.entities)
if (e->name.find("::") < 0 && !e->name.startsWith("_PI")) if (e->name.find("::") < 0 && !e->name.startsWith("_PI"))
inc_files << e->file; inc_files << e->file;
PIFile f(out + ".cpp"); PIFile f(out + ".cpp");
f.clear(); f.clear();
f.open(PIIODevice::WriteOnly); f.open(PIIODevice::WriteOnly);
@@ -252,10 +252,10 @@ void writeModel(PICodeParser & parser, const PIString out, bool meta, bool enums
makeClassStream(f, e); makeClassStream(f, e);
} }
} }
f.close(); f.close();
f.setPath(out + ".h"); f.setPath(out + ".h");
f.clear(); f.clear();
f.open(PIIODevice::WriteOnly); f.open(PIIODevice::WriteOnly);
@@ -331,7 +331,7 @@ int main(int argc, char * argv[]) {
piDebug = true; piDebug = true;
PIStringList pf(parser.parsedFiles()); PIStringList pf(parser.parsedFiles());
piForeachC (PIString & f, pf) { piForeachC (PIString & f, pf) {
if (!womain || (f != parser.mainFile())) if (!womain || (f != parser.mainFile()))
piCout << f; piCout << f;
} }
} }