code format
This commit is contained in:
@@ -1,2 +1 @@
|
||||
#include "pip.h"
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
#include "picloudbase.h"
|
||||
|
||||
|
||||
PICloudBase::PICloudBase() : eth(PIEthernet::TCP_Client), streampacker(ð), tcp(&streampacker) {
|
||||
PICloudBase::PICloudBase(): eth(PIEthernet::TCP_Client), streampacker(ð), tcp(&streampacker) {
|
||||
eth.setDebug(false);
|
||||
}
|
||||
|
||||
|
||||
@@ -18,38 +18,42 @@
|
||||
*/
|
||||
|
||||
#include "picloudclient.h"
|
||||
|
||||
#include "picloudtcp.h"
|
||||
|
||||
|
||||
PICloudClient::PICloudClient(const PIString & path, PIIODevice::DeviceMode mode) : PIIODevice(path, mode), PICloudBase() {
|
||||
PICloudClient::PICloudClient(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode), PICloudBase() {
|
||||
tcp.setRole(PICloud::TCP::Client);
|
||||
setThreadedReadBufferSize(eth.threadedReadBufferSize());
|
||||
setName("cloud_client");
|
||||
is_connected = false;
|
||||
is_deleted = false;
|
||||
// setReopenEnabled(false);
|
||||
CONNECTL(ð, connected, [this](){opened_ = true; tcp.sendStart();});
|
||||
// setReopenEnabled(false);
|
||||
CONNECTL(ð, connected, [this]() {
|
||||
opened_ = true;
|
||||
tcp.sendStart();
|
||||
});
|
||||
CONNECT1(void, PIByteArray, &streampacker, packetReceiveEvent, this, _readed);
|
||||
CONNECTL(ð, disconnected, [this](bool){
|
||||
CONNECTL(ð, disconnected, [this](bool) {
|
||||
if (is_deleted) return;
|
||||
bool need_disconn = is_connected;
|
||||
//piCoutObj << "eth disconnected";
|
||||
// piCoutObj << "eth disconnected";
|
||||
eth.stop();
|
||||
opened_ = false;
|
||||
internalDisconnect();
|
||||
if (need_disconn) disconnected();
|
||||
//piCoutObj << "eth disconnected done";
|
||||
// piCoutObj << "eth disconnected done";
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
PICloudClient::~PICloudClient() {
|
||||
//piCoutObj << "~PICloudClient() ..." << this;
|
||||
// piCoutObj << "~PICloudClient() ..." << this;
|
||||
is_deleted = true;
|
||||
stopAndWait();
|
||||
close();
|
||||
internalDisconnect();
|
||||
//piCoutObj << "~PICloudClient() done" << this;
|
||||
// piCoutObj << "~PICloudClient() done" << this;
|
||||
}
|
||||
|
||||
|
||||
@@ -71,14 +75,14 @@ void PICloudClient::interrupt() {
|
||||
|
||||
|
||||
bool PICloudClient::openDevice() {
|
||||
//piCoutObj << "open";// << path();
|
||||
// piCoutObj << "open";// << path();
|
||||
bool op = eth.connect(PIEthernet::Address::resolve(path()), false);
|
||||
if (op) {
|
||||
mutex_connect.lock();
|
||||
eth.startThreadedRead();
|
||||
//piCoutObj << "connecting...";
|
||||
// piCoutObj << "connecting...";
|
||||
bool conn_ok = cond_connect.waitFor(mutex_connect, (int)eth.readTimeout());
|
||||
//piCoutObj << "conn_ok" << conn_ok << is_connected;
|
||||
// piCoutObj << "conn_ok" << conn_ok << is_connected;
|
||||
mutex_connect.unlock();
|
||||
if (!conn_ok) {
|
||||
mutex_connect.lock();
|
||||
@@ -88,14 +92,14 @@ bool PICloudClient::openDevice() {
|
||||
}
|
||||
return is_connected;
|
||||
} else {
|
||||
//eth.close();
|
||||
// eth.close();
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
bool PICloudClient::closeDevice() {
|
||||
//PIThread::stop();
|
||||
// PIThread::stop();
|
||||
if (is_connected) {
|
||||
internalDisconnect();
|
||||
}
|
||||
@@ -107,7 +111,7 @@ bool PICloudClient::closeDevice() {
|
||||
|
||||
ssize_t PICloudClient::readDevice(void * read_to, ssize_t max_size) {
|
||||
if (is_deleted || max_size <= 0) return -1;
|
||||
//piCoutObj << "readDevice ...";
|
||||
// piCoutObj << "readDevice ...";
|
||||
if (!is_connected && eth.isClosed()) openDevice();
|
||||
ssize_t sz = -1;
|
||||
mutex_buff.lock();
|
||||
@@ -123,20 +127,20 @@ ssize_t PICloudClient::readDevice(void * read_to, ssize_t max_size) {
|
||||
}
|
||||
mutex_buff.unlock();
|
||||
if (!is_connected) opened_ = false;
|
||||
//piCoutObj << "readDevice done" << sz;
|
||||
// piCoutObj << "readDevice done" << sz;
|
||||
return sz;
|
||||
}
|
||||
|
||||
|
||||
ssize_t PICloudClient::writeDevice(const void * data, ssize_t size) {
|
||||
if (is_deleted || !is_connected) return -1;
|
||||
//piCoutObj << "writeDevice" << size;
|
||||
// piCoutObj << "writeDevice" << size;
|
||||
return tcp.sendData(PIByteArray(data, size));
|
||||
}
|
||||
|
||||
|
||||
void PICloudClient::internalDisconnect() {
|
||||
//piCoutObj << "internalDisconnect";
|
||||
// piCoutObj << "internalDisconnect";
|
||||
is_connected = false;
|
||||
cond_buff.notifyOne();
|
||||
cond_connect.notifyOne();
|
||||
@@ -148,7 +152,7 @@ void PICloudClient::internalDisconnect() {
|
||||
void PICloudClient::_readed(PIByteArray & ba) {
|
||||
if (is_deleted) return;
|
||||
PIPair<PICloud::TCP::Type, PICloud::TCP::Role> hdr = tcp.parseHeader(ba);
|
||||
//piCoutObj << "_readed" << ba.size() << hdr.first << hdr.second;
|
||||
// piCoutObj << "_readed" << ba.size() << hdr.first << hdr.second;
|
||||
if (hdr.second == tcp.role()) {
|
||||
switch (hdr.first) {
|
||||
case PICloud::TCP::Connect:
|
||||
@@ -178,10 +182,9 @@ void PICloudClient::_readed(PIByteArray & ba) {
|
||||
cond_buff.notifyOne();
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
//piCoutObj << "readed" << ba.toHex();
|
||||
// piCoutObj << "readed" << ba.toHex();
|
||||
}
|
||||
//piCoutObj << "_readed done";
|
||||
// piCoutObj << "_readed done";
|
||||
}
|
||||
|
||||
@@ -20,8 +20,8 @@
|
||||
#include "picloudserver.h"
|
||||
|
||||
|
||||
PICloudServer::PICloudServer(const PIString & path, PIIODevice::DeviceMode mode) : PIIODevice(path, mode), PICloudBase() {
|
||||
PIString server_name = "PCS_" + PIString::fromNumber(randomi()%1000);
|
||||
PICloudServer::PICloudServer(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode), PICloudBase() {
|
||||
PIString server_name = "PCS_" + PIString::fromNumber(randomi() % 1000);
|
||||
tcp.setRole(PICloud::TCP::Server);
|
||||
tcp.setServerName(server_name);
|
||||
setName("cloud_server__" + server_name);
|
||||
@@ -29,19 +29,19 @@ PICloudServer::PICloudServer(const PIString & path, PIIODevice::DeviceMode mode)
|
||||
eth.setReopenEnabled(false);
|
||||
setThreadedReadBufferSize(eth.threadedReadBufferSize());
|
||||
CONNECT1(void, PIByteArray, &streampacker, packetReceiveEvent, this, _readed);
|
||||
CONNECTL(ð, connected, [this](){
|
||||
CONNECTL(ð, connected, [this]() {
|
||||
open_mutex.lock();
|
||||
opened_ = true;
|
||||
cvar.notifyOne();
|
||||
open_mutex.unlock();
|
||||
//piCoutObj << "connected";
|
||||
// piCoutObj << "connected";
|
||||
tcp.sendStart();
|
||||
});
|
||||
CONNECTL(ð, disconnected, [this](bool){
|
||||
CONNECTL(ð, disconnected, [this](bool) {
|
||||
if (is_deleted) return;
|
||||
//piCoutObj << "disconnected";
|
||||
// piCoutObj << "disconnected";
|
||||
clients_mutex.lock();
|
||||
for (auto c : clients_) {
|
||||
for (auto c: clients_) {
|
||||
c->is_connected = false;
|
||||
c->close();
|
||||
}
|
||||
@@ -55,24 +55,24 @@ PICloudServer::PICloudServer(const PIString & path, PIIODevice::DeviceMode mode)
|
||||
open_mutex.unlock();
|
||||
ping_timer.stop();
|
||||
});
|
||||
CONNECTL(&ping_timer, tickEvent, [this] (void *, int){
|
||||
CONNECTL(&ping_timer, tickEvent, [this](void *, int) {
|
||||
if (eth.isConnected()) tcp.sendPing();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
PICloudServer::~PICloudServer() {
|
||||
//piCoutObj << "~PICloudServer ..." << this;
|
||||
// piCoutObj << "~PICloudServer ..." << this;
|
||||
is_deleted = true;
|
||||
stop();
|
||||
close();
|
||||
waitThreadedReadFinished();
|
||||
//piCout << "wait";
|
||||
while(removed_clients_.isNotEmpty()) {
|
||||
// piCout << "wait";
|
||||
while (removed_clients_.isNotEmpty()) {
|
||||
Client * c = removed_clients_.take_back();
|
||||
delete c;
|
||||
}
|
||||
//piCoutObj << "~PICloudServer done" << this;
|
||||
// piCoutObj << "~PICloudServer done" << this;
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ PIVector<PICloudServer::Client *> PICloudServer::clients() const {
|
||||
|
||||
|
||||
bool PICloudServer::openDevice() {
|
||||
//piCout << "PICloudServer open device" << path();
|
||||
// piCout << "PICloudServer open device" << path();
|
||||
if (is_deleted) return false;
|
||||
bool op = eth.connect(PIEthernet::Address::resolve(path()), false);
|
||||
if (op) {
|
||||
@@ -105,13 +105,13 @@ bool PICloudServer::openDevice() {
|
||||
|
||||
|
||||
bool PICloudServer::closeDevice() {
|
||||
//piCoutObj << "closeDevice" << this;
|
||||
// piCoutObj << "closeDevice" << this;
|
||||
eth.stopAndWait();
|
||||
ping_timer.stop();
|
||||
eth.close();
|
||||
cvar.notifyOne();
|
||||
clients_mutex.lock();
|
||||
for (auto c : clients_) {
|
||||
for (auto c: clients_) {
|
||||
c->is_connected = false;
|
||||
c->close();
|
||||
}
|
||||
@@ -125,18 +125,18 @@ bool PICloudServer::closeDevice() {
|
||||
|
||||
ssize_t PICloudServer::readDevice(void * read_to, ssize_t max_size) {
|
||||
if (is_deleted) return -1;
|
||||
//piCoutObj << "readDevice";
|
||||
// piCoutObj << "readDevice";
|
||||
open_mutex.lock();
|
||||
if (isOpened()) cvar.wait(open_mutex);
|
||||
open_mutex.unlock();
|
||||
//piCoutObj << "opened_ = " << opened_;
|
||||
//else piMSleep(eth.readTimeout());
|
||||
// piCoutObj << "opened_ = " << opened_;
|
||||
// else piMSleep(eth.readTimeout());
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
ssize_t PICloudServer::writeDevice(const void * data, ssize_t max_size) {
|
||||
//piCoutObj << "writeDevice";
|
||||
// piCoutObj << "writeDevice";
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -158,7 +158,7 @@ int PICloudServer::sendData(const PIByteArray & data, uint client_id) {
|
||||
}
|
||||
|
||||
|
||||
PICloudServer::Client::Client(PICloudServer * srv, uint id) : server(srv), client_id(id) {
|
||||
PICloudServer::Client::Client(PICloudServer * srv, uint id): server(srv), client_id(id) {
|
||||
setMode(PIIODevice::ReadWrite);
|
||||
setReopenEnabled(false);
|
||||
setThreadedReadBufferSize(server->threadedReadBufferSize());
|
||||
@@ -167,10 +167,10 @@ PICloudServer::Client::Client(PICloudServer * srv, uint id) : server(srv), clien
|
||||
|
||||
|
||||
PICloudServer::Client::~Client() {
|
||||
//piCoutObj << "~PICloudServer::Client..." << this;
|
||||
// piCoutObj << "~PICloudServer::Client..." << this;
|
||||
close();
|
||||
stopAndWait();
|
||||
//piCoutObj << "~PICloudServer::Client done" << this;
|
||||
// piCoutObj << "~PICloudServer::Client done" << this;
|
||||
}
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ bool PICloudServer::Client::openDevice() {
|
||||
|
||||
|
||||
bool PICloudServer::Client::closeDevice() {
|
||||
//piCoutObj << "closeDevice" << this;
|
||||
// piCoutObj << "closeDevice" << this;
|
||||
if (is_connected) {
|
||||
server->clientDisconnect(client_id);
|
||||
is_connected = false;
|
||||
@@ -249,7 +249,7 @@ void PICloudServer::_readed(PIByteArray & ba) {
|
||||
tcp.sendDisconnected(id);
|
||||
} else {
|
||||
Client * c = new Client(this, id);
|
||||
//piCoutObj << "new Client" << id << c;
|
||||
// piCoutObj << "new Client" << id << c;
|
||||
CONNECT1(void, PIObject *, c, deleted, this, clientDeleted);
|
||||
clients_mutex.lock();
|
||||
clients_ << c;
|
||||
@@ -260,7 +260,7 @@ void PICloudServer::_readed(PIByteArray & ba) {
|
||||
} break;
|
||||
case PICloud::TCP::Disconnect: {
|
||||
uint id = tcp.parseDisconnect(ba);
|
||||
//piCoutObj << "Close on logic";
|
||||
// piCoutObj << "Close on logic";
|
||||
clients_mutex.lock();
|
||||
Client * oc = index_clients.take(id, nullptr);
|
||||
clients_.removeOne(oc);
|
||||
@@ -270,7 +270,7 @@ void PICloudServer::_readed(PIByteArray & ba) {
|
||||
oc->is_connected = false;
|
||||
oc->close();
|
||||
removed_clients_ << oc;
|
||||
//delete oc;
|
||||
// delete oc;
|
||||
}
|
||||
} break;
|
||||
case PICloud::TCP::Data: {
|
||||
@@ -278,7 +278,7 @@ void PICloudServer::_readed(PIByteArray & ba) {
|
||||
clients_mutex.lock();
|
||||
Client * oc = index_clients.value(d.first, nullptr);
|
||||
clients_mutex.unlock();
|
||||
//piCoutObj << "data for" << d.first << d.second.size();
|
||||
// piCoutObj << "data for" << d.first << d.second.size();
|
||||
if (oc && !d.second.isEmpty()) oc->pushBuffer(d.second);
|
||||
} break;
|
||||
default: break;
|
||||
@@ -288,8 +288,8 @@ void PICloudServer::_readed(PIByteArray & ba) {
|
||||
|
||||
|
||||
void PICloudServer::clientDeleted(PIObject * o) {
|
||||
PICloudServer::Client * c = (PICloudServer::Client*)o;
|
||||
//piCoutObj << "clientDeleted" << c;
|
||||
PICloudServer::Client * c = (PICloudServer::Client *)o;
|
||||
// piCoutObj << "clientDeleted" << c;
|
||||
clients_mutex.lock();
|
||||
clients_.removeOne(c);
|
||||
removed_clients_.removeAll(c);
|
||||
|
||||
@@ -18,8 +18,9 @@
|
||||
*/
|
||||
|
||||
#include "picloudtcp.h"
|
||||
#include "picrypt.h"
|
||||
|
||||
#include "pichunkstream.h"
|
||||
#include "picrypt.h"
|
||||
#include "piethernet.h"
|
||||
#include "pistreampacker.h"
|
||||
|
||||
@@ -32,8 +33,8 @@ PICloud::TCP::Header::Header() {
|
||||
}
|
||||
|
||||
|
||||
PICloud::TCP::TCP(PIStreamPacker * s) : streampacker(s) {
|
||||
streampacker->setMaxPacketSize(63*1024);
|
||||
PICloud::TCP::TCP(PIStreamPacker * s): streampacker(s) {
|
||||
streampacker->setMaxPacketSize(63 * 1024);
|
||||
}
|
||||
|
||||
void PICloud::TCP::setRole(PICloud::TCP::Role r) {
|
||||
@@ -43,7 +44,8 @@ void PICloud::TCP::setRole(PICloud::TCP::Role r) {
|
||||
|
||||
void PICloud::TCP::setServerName(const PIString & server_name_) {
|
||||
server_name = server_name_;
|
||||
suuid = PICrypt::hash(PIByteArray(server_name_.data(), server_name_.size()), (const unsigned char *)hash_cloud_key, sizeof(hash_cloud_key));
|
||||
suuid =
|
||||
PICrypt::hash(PIByteArray(server_name_.data(), server_name_.size()), (const unsigned char *)hash_cloud_key, sizeof(hash_cloud_key));
|
||||
}
|
||||
|
||||
|
||||
@@ -53,7 +55,7 @@ PIString PICloud::TCP::serverName() const {
|
||||
|
||||
|
||||
void PICloud::TCP::sendStart() {
|
||||
//piCout << "sendStart";
|
||||
// piCout << "sendStart";
|
||||
if (suuid.size() != PICrypt::sizeHash()) {
|
||||
piCout << "PICloud ERROR, server not set, invoke setServerName first";
|
||||
return;
|
||||
@@ -62,9 +64,9 @@ void PICloud::TCP::sendStart() {
|
||||
PIByteArray ba;
|
||||
ba << header;
|
||||
ba.append(suuid);
|
||||
//mutex_send.lock();
|
||||
// mutex_send.lock();
|
||||
streampacker->send(ba);
|
||||
//mutex_send.unlock();
|
||||
// mutex_send.unlock();
|
||||
}
|
||||
|
||||
|
||||
@@ -72,9 +74,9 @@ void PICloud::TCP::sendConnected(uint client_id) {
|
||||
header.type = PICloud::TCP::Connect;
|
||||
PIByteArray ba;
|
||||
ba << header << client_id;
|
||||
// mutex_send.lock();
|
||||
// mutex_send.lock();
|
||||
streampacker->send(ba);
|
||||
// mutex_send.unlock();
|
||||
// mutex_send.unlock();
|
||||
}
|
||||
|
||||
|
||||
@@ -82,9 +84,9 @@ void PICloud::TCP::sendDisconnected(uint client_id) {
|
||||
header.type = PICloud::TCP::Disconnect;
|
||||
PIByteArray ba;
|
||||
ba << header << client_id;
|
||||
// mutex_send.lock();
|
||||
// mutex_send.lock();
|
||||
streampacker->send(ba);
|
||||
// mutex_send.unlock();
|
||||
// mutex_send.unlock();
|
||||
}
|
||||
|
||||
|
||||
@@ -93,7 +95,7 @@ int PICloud::TCP::sendData(const PIByteArray & data) {
|
||||
PIByteArray ba;
|
||||
ba << header;
|
||||
ba.append(data);
|
||||
// piCout << "[PICloud::TCP] sendData" << ba.toHex();
|
||||
// piCout << "[PICloud::TCP] sendData" << ba.toHex();
|
||||
mutex_send.lock();
|
||||
streampacker->send(ba);
|
||||
mutex_send.unlock();
|
||||
@@ -132,7 +134,8 @@ PIPair<PICloud::TCP::Type, PICloud::TCP::Role> PICloud::TCP::parseHeader(PIByteA
|
||||
PICloud::TCP::Header hdr;
|
||||
ba >> hdr;
|
||||
if (hdr.version != header.version) {
|
||||
piCout << "[PICloud]" << "invalid PICloud::TCP version!";
|
||||
piCout << "[PICloud]"
|
||||
<< "invalid PICloud::TCP version!";
|
||||
return ret;
|
||||
}
|
||||
ret.first = (Type)hdr.type;
|
||||
|
||||
@@ -38,14 +38,16 @@ PIByteArray piCompress(const PIByteArray & ba, int level) {
|
||||
ulong sz = zba.size();
|
||||
ret = compress2(zba.data(), &sz, ba.data(), ba.size(), level);
|
||||
if (ret != Z_OK) {
|
||||
piCout << "[PICompress]" << "Error: invalid input or not enought memory";
|
||||
piCout << "[PICompress]"
|
||||
<< "Error: invalid input or not enought memory";
|
||||
return ba;
|
||||
}
|
||||
zba.resize(sz);
|
||||
zba << ullong(ba.size());
|
||||
return zba;
|
||||
#else
|
||||
piCout << "[PICompress]" << "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library";
|
||||
piCout << "[PICompress]"
|
||||
<< "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library";
|
||||
#endif
|
||||
return ba;
|
||||
}
|
||||
@@ -55,7 +57,8 @@ PIByteArray piDecompress(const PIByteArray & zba) {
|
||||
#ifdef PIP_COMPRESS
|
||||
ullong sz = 0;
|
||||
if (zba.size() < sizeof(ullong)) {
|
||||
piCout << "[PICompress]" << "Error: invalid input";
|
||||
piCout << "[PICompress]"
|
||||
<< "Error: invalid input";
|
||||
return zba;
|
||||
}
|
||||
PIByteArray ba(zba.data(zba.size() - sizeof(ullong)), sizeof(ullong));
|
||||
@@ -65,12 +68,14 @@ PIByteArray piDecompress(const PIByteArray & zba) {
|
||||
ulong s = sz;
|
||||
ret = uncompress(ba.data(), &s, zba.data(), zba.size());
|
||||
if (ret != Z_OK) {
|
||||
piCout << "[PICompress]" << "Error: invalid input or not enought memory";
|
||||
piCout << "[PICompress]"
|
||||
<< "Error: invalid input or not enought memory";
|
||||
return zba;
|
||||
}
|
||||
return ba;
|
||||
#else
|
||||
piCout << "[PICompress]" << "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library";
|
||||
piCout << "[PICompress]"
|
||||
<< "Warning: PICompress is disabled, to enable install zlib library and build pip_compress library";
|
||||
#endif
|
||||
return zba;
|
||||
}
|
||||
|
||||
@@ -22,21 +22,14 @@
|
||||
using namespace PIScreenTypes;
|
||||
|
||||
|
||||
TileVars::TileVars(const PIString &n) : PIScreenTile(n) {
|
||||
TileVars::TileVars(const PIString & n): PIScreenTile(n) {
|
||||
alignment = Left;
|
||||
}
|
||||
|
||||
|
||||
void TileVars::sizeHint(int &w, int &h) const {
|
||||
void TileVars::sizeHint(int & w, int & h) const {}
|
||||
|
||||
}
|
||||
|
||||
void TileVars::drawEvent(PIScreenDrawer *d) {
|
||||
|
||||
}
|
||||
void TileVars::drawEvent(PIScreenDrawer * d) {}
|
||||
|
||||
|
||||
PIScreenConsoleTile::PIScreenConsoleTile() {
|
||||
|
||||
}
|
||||
|
||||
PIScreenConsoleTile::PIScreenConsoleTile() {}
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
using namespace PIScreenTypes;
|
||||
|
||||
|
||||
PIScreenDrawer::PIScreenDrawer(PIVector<PIVector<Cell> > & c): cells(c) {
|
||||
PIScreenDrawer::PIScreenDrawer(PIVector<PIVector<Cell>> & c): cells(c) {
|
||||
arts_[LineVertical] =
|
||||
#ifdef USE_UNICODE
|
||||
PIChar::fromUTF8("│");
|
||||
@@ -117,26 +117,24 @@ void PIScreenDrawer::drawLine(int x0, int y0, int x1, int y1, const PIChar & c,
|
||||
float dy = (y1 - y0) / float(piAbsi(x1 - x0)), cy = y0;
|
||||
int dx = x0 < x1 ? 1 : -1;
|
||||
for (int i = x0; i != x1; i += dx) {
|
||||
x = i; y = piRound(cy);
|
||||
if (x >= 0 && x < width && y >= 0 && y < height)
|
||||
cells[y][x] = cc;
|
||||
x = i;
|
||||
y = piRound(cy);
|
||||
if (x >= 0 && x < width && y >= 0 && y < height) cells[y][x] = cc;
|
||||
cy += dy;
|
||||
}
|
||||
y = piRound(cy);
|
||||
if (x1 >= 0 && x1 < width && y >= 0 && y < height)
|
||||
cells[y][x1] = cc;
|
||||
if (x1 >= 0 && x1 < width && y >= 0 && y < height) cells[y][x1] = cc;
|
||||
} else {
|
||||
float dx = (x1 - x0) / float(piAbsi(y1 - y0)), cx = x0;
|
||||
int dy = y0 < y1 ? 1 : -1;
|
||||
for (int i = y0; i != y1; i += dy) {
|
||||
x = piRound(cx); y = i;
|
||||
if (x >= 0 && x < width && y >= 0 && y < height)
|
||||
cells[y][x] = cc;
|
||||
x = piRound(cx);
|
||||
y = i;
|
||||
if (x >= 0 && x < width && y >= 0 && y < height) cells[y][x] = cc;
|
||||
cx += dx;
|
||||
}
|
||||
x = piRound(cx);
|
||||
if (x >= 0 && x < width && y1 >= 0 && y1 < height)
|
||||
cells[y1][x] = cc;
|
||||
if (x >= 0 && x < width && y1 >= 0 && y1 < height) cells[y1][x] = cc;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,19 +155,16 @@ void PIScreenDrawer::drawRect(int x0, int y0, int x1, int y1, const PIChar & c,
|
||||
if (j >= 0 && j < height) {
|
||||
PIVector<Cell> & cv(cells[j]);
|
||||
for (int i = x0; i != x1; i += dx)
|
||||
if (i >= 0 && i < width)
|
||||
cv[i] = cc;
|
||||
if (i >= 0 && i < width) cv[i] = cc;
|
||||
}
|
||||
j = xs[k];
|
||||
if (j >= 0 && j < width) {
|
||||
for (int i = y0; i != y1; i += dy)
|
||||
if (i >= 0 && i < height)
|
||||
cells[i][j] = cc;
|
||||
if (i >= 0 && i < height) cells[i][j] = cc;
|
||||
}
|
||||
}
|
||||
int i = x1, j = y1;
|
||||
if (i >= 0 && i < width && j >= 0 && j < height)
|
||||
cells[j][i] = cc;
|
||||
if (i >= 0 && i < width && j >= 0 && j < height) cells[j][i] = cc;
|
||||
}
|
||||
|
||||
|
||||
@@ -189,24 +184,26 @@ void PIScreenDrawer::drawFrame(int x0, int y0, int x1, int y1, Color col_char, C
|
||||
PIVector<Cell> & cv(cells[j]);
|
||||
cc.symbol = artChar(LineHorizontal);
|
||||
for (int i = x0 + 1; i != x1; i += dx)
|
||||
if (i >= 0 && i < width)
|
||||
cv[i] = cc;
|
||||
if (i >= 0 && i < width) cv[i] = cc;
|
||||
}
|
||||
j = xs[k];
|
||||
if (j >= 0 && j < width) {
|
||||
cc.symbol = artChar(LineVertical);
|
||||
for (int i = y0 + 1; i != y1; i += dy)
|
||||
if (i >= 0 && i < height)
|
||||
cells[i][j] = cc;
|
||||
if (i >= 0 && i < height) cells[i][j] = cc;
|
||||
}
|
||||
}
|
||||
int i = x0, j = y0; cc.symbol = artChar(CornerTopLeft);
|
||||
int i = x0, j = y0;
|
||||
cc.symbol = artChar(CornerTopLeft);
|
||||
if (i >= 0 && i < width && j >= 0 && j < height) cells[j][i] = cc;
|
||||
i = x1, j = y0; cc.symbol = artChar(CornerTopRight);
|
||||
i = x1, j = y0;
|
||||
cc.symbol = artChar(CornerTopRight);
|
||||
if (i >= 0 && i < width && j >= 0 && j < height) cells[j][i] = cc;
|
||||
i = x0, j = y1; cc.symbol = artChar(CornerBottomLeft);
|
||||
i = x0, j = y1;
|
||||
cc.symbol = artChar(CornerBottomLeft);
|
||||
if (i >= 0 && i < width && j >= 0 && j < height) cells[j][i] = cc;
|
||||
i = x1, j = y1; cc.symbol = artChar(CornerBottomRight);
|
||||
i = x1, j = y1;
|
||||
cc.symbol = artChar(CornerBottomRight);
|
||||
if (i >= 0 && i < width && j >= 0 && j < height) cells[j][i] = cc;
|
||||
}
|
||||
|
||||
@@ -224,13 +221,12 @@ void PIScreenDrawer::fillRect(int x0, int y0, int x1, int y1, const PIChar & c,
|
||||
if (j >= 0 && j < height) {
|
||||
PIVector<Cell> & cv(cells[j]);
|
||||
for (int i = x0; i != x1; i += dx)
|
||||
if (i >= 0 && i < width)
|
||||
cv[i] = cc;
|
||||
if (i >= 0 && i < width) cv[i] = cc;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void PIScreenDrawer::fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<Cell> > & content) {
|
||||
void PIScreenDrawer::fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<Cell>> & content) {
|
||||
if (x0 > x1) piSwap(x0, x1);
|
||||
if (y0 > y1) piSwap(y0, y1);
|
||||
int w = x1 - x0;
|
||||
@@ -241,14 +237,13 @@ void PIScreenDrawer::fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<
|
||||
PIVector<Cell> & cv(cells[y0 + j]);
|
||||
PIVector<Cell> & contv(content[j]);
|
||||
for (int i = 0; i < piMini(w, contv.size_s()); ++i)
|
||||
if ((i + x0) >= 0 && (i + x0) < width)
|
||||
cv[x0 + i] = contv[i];
|
||||
if ((i + x0) >= 0 && (i + x0) < width) cv[x0 + i] = contv[i];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void PIScreenDrawer::clear(PIVector<PIVector<Cell> > & cells) {
|
||||
void PIScreenDrawer::clear(PIVector<PIVector<Cell>> & cells) {
|
||||
for (int i = 0; i < cells.size_s(); ++i)
|
||||
cells[i].fill(Cell());
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
#include "piscreentile.h"
|
||||
|
||||
#include "piscreendrawer.h"
|
||||
|
||||
|
||||
@@ -40,9 +41,8 @@ PIScreenTile::PIScreenTile(const PIString & n, Direction d, SizePolicy p): PIObj
|
||||
|
||||
|
||||
PIScreenTile::~PIScreenTile() {
|
||||
//piCout << this << "~";
|
||||
if (screen)
|
||||
screen->tileRemovedInternal(this);
|
||||
// piCout << this << "~";
|
||||
if (screen) screen->tileRemovedInternal(this);
|
||||
setScreen(0);
|
||||
deleteChildren();
|
||||
if (!parent) return;
|
||||
@@ -76,20 +76,18 @@ void PIScreenTile::removeTile(PIScreenTile * t) {
|
||||
}
|
||||
|
||||
|
||||
PIVector<PIScreenTile * > PIScreenTile::children(bool only_visible) {
|
||||
PIVector<PIScreenTile * > ret;
|
||||
piForeach (PIScreenTile * t, tiles)
|
||||
if (t->visible || !only_visible)
|
||||
ret << t << t->children(only_visible);
|
||||
PIVector<PIScreenTile *> PIScreenTile::children(bool only_visible) {
|
||||
PIVector<PIScreenTile *> ret;
|
||||
piForeach(PIScreenTile * t, tiles)
|
||||
if (t->visible || !only_visible) ret << t << t->children(only_visible);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
PIScreenTile * PIScreenTile::childUnderMouse(int x, int y) {
|
||||
piForeach (PIScreenTile * t, tiles) {
|
||||
piForeach(PIScreenTile * t, tiles) {
|
||||
if (!t->visible) continue;
|
||||
if (x >= t->x_ && (x - t->x_) < t->width_ &&
|
||||
y >= t->y_ && (y - t->y_) < t->height_) {
|
||||
if (x >= t->x_ && (x - t->x_) < t->width_ && y >= t->y_ && (y - t->y_) < t->height_) {
|
||||
return t;
|
||||
}
|
||||
}
|
||||
@@ -105,13 +103,13 @@ void PIScreenTile::raiseEvent(TileEvent e) {
|
||||
|
||||
void PIScreenTile::setScreen(PIScreenBase * s) {
|
||||
screen = s;
|
||||
piForeach (PIScreenTile * t, tiles)
|
||||
piForeach(PIScreenTile * t, tiles)
|
||||
t->setScreen(s);
|
||||
}
|
||||
|
||||
|
||||
void PIScreenTile::deleteChildren() {
|
||||
piForeach (PIScreenTile * t, tiles) {
|
||||
piForeach(PIScreenTile * t, tiles) {
|
||||
t->parent = 0;
|
||||
delete t;
|
||||
}
|
||||
@@ -129,9 +127,16 @@ void PIScreenTile::drawEventInternal(PIScreenDrawer * d) {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
d->fillRect(x_, y_, x_ + width_, y_ + height_, back_symbol, (Color)back_format.color_char, (Color)back_format.color_back, back_format.flags);
|
||||
d->fillRect(x_,
|
||||
y_,
|
||||
x_ + width_,
|
||||
y_ + height_,
|
||||
back_symbol,
|
||||
(Color)back_format.color_char,
|
||||
(Color)back_format.color_back,
|
||||
back_format.flags);
|
||||
drawEvent(d);
|
||||
piForeach (PIScreenTile * t, tiles)
|
||||
piForeach(PIScreenTile * t, tiles)
|
||||
t->drawEventInternal(d);
|
||||
}
|
||||
|
||||
@@ -141,18 +146,22 @@ void PIScreenTile::sizeHint(int & w, int & h) const {
|
||||
h = 0;
|
||||
if (tiles.isEmpty()) return;
|
||||
int sl = spacing * (tiles.size_s() - 1);
|
||||
if (direction == Horizontal) w += sl;
|
||||
else h += sl;
|
||||
piForeachC (PIScreenTile * t, tiles) {
|
||||
if (direction == Horizontal)
|
||||
w += sl;
|
||||
else
|
||||
h += sl;
|
||||
piForeachC(PIScreenTile * t, tiles) {
|
||||
if (!t->visible) continue;
|
||||
int cw(0), ch(0);
|
||||
t->sizeHint(cw, ch);
|
||||
cw = piClampi(cw, t->minimumWidth, t->maximumWidth);
|
||||
ch = piClampi(ch, t->minimumHeight, t->maximumHeight);
|
||||
if (direction == Horizontal) {
|
||||
w += cw; h = piMaxi(h, ch);
|
||||
w += cw;
|
||||
h = piMaxi(h, ch);
|
||||
} else {
|
||||
h += ch; w = piMaxi(w, cw);
|
||||
h += ch;
|
||||
w = piMaxi(w, cw);
|
||||
}
|
||||
}
|
||||
w += marginLeft + marginRight;
|
||||
@@ -210,8 +219,7 @@ void PIScreenTile::layout() {
|
||||
for (int j = 0; j < tiles.size_s(); ++j) {
|
||||
if (i == j) continue;
|
||||
if (max_tl[j]) continue;
|
||||
if (tiles[j]->size_policy == pol && tiles[j]->visible && tiles[j]->needLayout())
|
||||
asizes[j] += pas;
|
||||
if (tiles[j]->size_policy == pol && tiles[j]->visible && tiles[j]->needLayout()) asizes[j] += pas;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -241,8 +249,7 @@ void PIScreenTile::layout() {
|
||||
t->height_ = hints[i];
|
||||
cy += hints[i] + spacing;
|
||||
}
|
||||
if (t->pw != t->width_ || t->ph != t->height_)
|
||||
t->resizeEvent(t->width_, t->height_);
|
||||
if (t->pw != t->width_ || t->ph != t->height_) t->resizeEvent(t->width_, t->height_);
|
||||
t->pw = t->width_;
|
||||
t->ph = t->height_;
|
||||
t->layout();
|
||||
|
||||
@@ -16,17 +16,19 @@
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "piincludes_p.h"
|
||||
#include "piterminal.h"
|
||||
|
||||
#include "piincludes_p.h"
|
||||
#include "pisharedmemory.h"
|
||||
#ifndef MICRO_PIP
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
# include <wincon.h>
|
||||
# include <windows.h>
|
||||
# include <wingdi.h>
|
||||
# include <wincon.h>
|
||||
# include <winuser.h>
|
||||
#else
|
||||
# else
|
||||
# include "piprocess.h"
|
||||
|
||||
# include <csignal>
|
||||
# include <fcntl.h>
|
||||
# include <sys/ioctl.h>
|
||||
@@ -46,12 +48,12 @@
|
||||
# else
|
||||
# define HAS_FORKPTY
|
||||
# endif
|
||||
#endif
|
||||
# endif
|
||||
|
||||
|
||||
//extern PIMutex PICout::__mutex__;
|
||||
// extern PIMutex PICout::__mutex__;
|
||||
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
# define PIPE_BUFFER_SIZE 1024
|
||||
enum PITerminalAuxMessageType {
|
||||
mtKey = 1,
|
||||
@@ -65,22 +67,22 @@ struct PITerminalAuxData {
|
||||
int size_y;
|
||||
int cells_size;
|
||||
};
|
||||
#else
|
||||
# else
|
||||
# define BUFFER_SIZE 4096
|
||||
enum DECType {
|
||||
CKM = 1
|
||||
};
|
||||
#endif
|
||||
# endif
|
||||
|
||||
|
||||
PRIVATE_DEFINITION_START(PITerminal)
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
PISharedMemory * shm;
|
||||
HANDLE hConBuf;
|
||||
STARTUPINFOA si;
|
||||
PROCESS_INFORMATION pi;
|
||||
HANDLE pipe;
|
||||
#else
|
||||
# else
|
||||
PIString shell;
|
||||
PIByteArray read_buf, tmp_buf;
|
||||
PIScreenTypes::CellFormat cur_format, line_format;
|
||||
@@ -92,21 +94,21 @@ PRIVATE_DEFINITION_START(PITerminal)
|
||||
PIString esc_seq;
|
||||
bool is_esc_seq, last_read;
|
||||
PIMap<int, bool> DEC;
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > cells_save;
|
||||
#endif
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> cells_save;
|
||||
# endif
|
||||
PRIVATE_DEFINITION_END(PITerminal)
|
||||
|
||||
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
int writePipe(HANDLE pipe, const PIByteArray & ba) {
|
||||
DWORD wrote[2];
|
||||
int sz = ba.size_s();
|
||||
WriteFile(pipe, &sz, 4, &(wrote[0]), 0);
|
||||
WriteFile(pipe, ba.data(), ba.size_s(), &(wrote[1]), 0);
|
||||
//piCout << "send" << ba.size_s();
|
||||
// piCout << "send" << ba.size_s();
|
||||
return int(wrote[0] + wrote[1]);
|
||||
}
|
||||
#endif
|
||||
# endif
|
||||
|
||||
|
||||
PITerminal::PITerminal(): PIThread() {
|
||||
@@ -116,40 +118,39 @@ PITerminal::PITerminal(): PIThread() {
|
||||
cursor_x = cursor_y = 0;
|
||||
dsize_x = 80;
|
||||
dsize_y = 24;
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
PRIVATE->shm = 0;
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
PITerminal::~PITerminal() {
|
||||
if (isRunning())
|
||||
stop();
|
||||
if (isRunning()) stop();
|
||||
PIThread::waitForFinish(10);
|
||||
destroy();
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
if (PRIVATE->shm) delete PRIVATE->shm;
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
void PITerminal::write(const PIByteArray & d) {
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
PIByteArray msg;
|
||||
PIVector<PIKbdListener::KeyEvent> ke;
|
||||
for (int i = 0; i < d.size_s(); ++i)
|
||||
ke << PIKbdListener::KeyEvent(d[i]);
|
||||
msg << int(mtKey) << ke;
|
||||
writePipe(PRIVATE->pipe, msg);
|
||||
#else
|
||||
# else
|
||||
# ifdef HAS_FORKPTY
|
||||
if (PRIVATE->fd == 0) return;
|
||||
//ssize_t wrote = 0;
|
||||
//wrote =
|
||||
// ssize_t wrote = 0;
|
||||
// wrote =
|
||||
::write(PRIVATE->fd, d.data(), d.size_s());
|
||||
//piCout << "wrote" << wrote << d;
|
||||
// piCout << "wrote" << wrote << d;
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
cursor_tm.reset();
|
||||
cursor_blink = true;
|
||||
}
|
||||
@@ -157,15 +158,16 @@ void PITerminal::write(const PIByteArray & d) {
|
||||
|
||||
void PITerminal::write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m) {
|
||||
PIByteArray ba;
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
switch (k) {
|
||||
case PIKbdListener::Tab: ba << uchar('\t'); break;
|
||||
case PIKbdListener::Return: ba << uchar('\r') << uchar('\n'); break;
|
||||
case PIKbdListener::Space: ba << uchar(' '); break;
|
||||
default: break;
|
||||
}
|
||||
//piCout << "write" << ba.size();
|
||||
if (!ba.isEmpty()) write(ba);
|
||||
// piCout << "write" << ba.size();
|
||||
if (!ba.isEmpty())
|
||||
write(ba);
|
||||
else {
|
||||
PIByteArray msg;
|
||||
PIVector<PIKbdListener::KeyEvent> ke;
|
||||
@@ -173,7 +175,7 @@ void PITerminal::write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers
|
||||
msg << int(mtKey) << ke;
|
||||
writePipe(PRIVATE->pipe, msg);
|
||||
}
|
||||
#else
|
||||
# else
|
||||
int term = PRIVATE->term_type;
|
||||
int flags = 0;
|
||||
switch (k) {
|
||||
@@ -185,7 +187,8 @@ void PITerminal::write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers
|
||||
case PIKbdListener::UpArrow:
|
||||
case PIKbdListener::DownArrow:
|
||||
case PIKbdListener::RightArrow:
|
||||
case PIKbdListener::LeftArrow: if (PRIVATE->DEC.value(CKM, false)) flags = 1;
|
||||
case PIKbdListener::LeftArrow:
|
||||
if (PRIVATE->DEC.value(CKM, false)) flags = 1;
|
||||
/*case PIKbdListener::Home: //break;
|
||||
case PIKbdListener::End: //break;
|
||||
case PIKbdListener::PageUp: //ba << uchar('\e') << uchar('[') << uchar('5') << uchar('~'); break;
|
||||
@@ -206,18 +209,18 @@ void PITerminal::write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers
|
||||
case PIKbdListener::F12: //break;
|
||||
*/
|
||||
default: {
|
||||
//piCout << flags;
|
||||
//int mod = 0;
|
||||
// piCout << flags;
|
||||
// int mod = 0;
|
||||
if (m[PIKbdListener::Shift]) m |= 1;
|
||||
if (m[PIKbdListener::Alt]) m |= 2;
|
||||
if (m[PIKbdListener::Ctrl]) m |= 4;
|
||||
for (int i = 0; ; ++i) {
|
||||
for (int i = 0;; ++i) {
|
||||
const PIKbdListener::EscSeq & e(PIKbdListener::esc_seq[i]);
|
||||
if (!e.seq) break;
|
||||
//piCout << "search" << rc[1] << esc_seq[i].seq;
|
||||
// piCout << "search" << rc[1] << esc_seq[i].seq;
|
||||
if (e.key == k && e.mod == m) {
|
||||
if (((e.vt & term) == term) || (((e.flags & flags) == flags) && (flags != 0))) {
|
||||
//piCout << "found key" << PIString(e.seq).replaceAll("\e", "\\e");
|
||||
// piCout << "found key" << PIString(e.seq).replaceAll("\e", "\\e");
|
||||
PIByteArray d = ("\e" + PIString(e.seq)).toByteArray();
|
||||
write(d);
|
||||
break;
|
||||
@@ -226,35 +229,35 @@ void PITerminal::write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers
|
||||
}
|
||||
} break;
|
||||
}
|
||||
//piCout << "write" << ba.size();
|
||||
// piCout << "write" << ba.size();
|
||||
if (!ba.isEmpty()) write(ba);
|
||||
#endif
|
||||
# endif
|
||||
cursor_tm.reset();
|
||||
cursor_blink = true;
|
||||
}
|
||||
|
||||
|
||||
void PITerminal::write(PIKbdListener::KeyEvent ke) {
|
||||
if (isSpecialKey(ke.key)) write((PIKbdListener::SpecialKey)ke.key, ke.modifiers);
|
||||
if (isSpecialKey(ke.key))
|
||||
write((PIKbdListener::SpecialKey)ke.key, ke.modifiers);
|
||||
else {
|
||||
PIByteArray ba;
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
ba << uchar(PIChar((ushort)ke.key).toConsole1Byte());
|
||||
#else
|
||||
# else
|
||||
ba = PIString(PIChar((ushort)ke.key)).toUTF8();
|
||||
#endif
|
||||
# endif
|
||||
write(ba);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > PITerminal::content() {
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> PITerminal::content() {
|
||||
readConsole();
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > ret = cells;
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> ret = cells;
|
||||
if (cursor_blink && cursor_visible)
|
||||
if (cursor_x >= 0 && cursor_x < size_x)
|
||||
if (cursor_y >= 0 && cursor_y < size_y)
|
||||
ret[cursor_y][cursor_x].format.flags ^= PIScreenTypes::Inverse;
|
||||
if (cursor_y >= 0 && cursor_y < size_y) ret[cursor_y][cursor_x].format.flags ^= PIScreenTypes::Inverse;
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -295,11 +298,11 @@ bool PITerminal::isSpecialKey(int k) {
|
||||
|
||||
|
||||
void PITerminal::initPrivate() {
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
PRIVATE->hConBuf = INVALID_HANDLE_VALUE;
|
||||
PRIVATE->pipe = INVALID_HANDLE_VALUE;
|
||||
PRIVATE->pi.hProcess = 0;
|
||||
#else
|
||||
# else
|
||||
PRIVATE->shell = "/bin/bash";
|
||||
PRIVATE->read_buf.reserve(BUFFER_SIZE);
|
||||
PRIVATE->read_buf.fill(0);
|
||||
@@ -311,14 +314,14 @@ void PITerminal::initPrivate() {
|
||||
PRIVATE->last_read = true;
|
||||
PRIVATE->esc_seq.clear();
|
||||
PRIVATE->cur_format = PIScreenTypes::CellFormat();
|
||||
#endif
|
||||
# endif
|
||||
cursor_blink = cursor_visible = true;
|
||||
size_x = size_y = 0;
|
||||
}
|
||||
|
||||
|
||||
void PITerminal::readConsole() {
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
if (!PRIVATE->shm) return;
|
||||
PITerminalAuxData data;
|
||||
PRIVATE->shm->read(&data, sizeof(data));
|
||||
@@ -331,20 +334,20 @@ void PITerminal::readConsole() {
|
||||
ba.resize(data.cells_size);
|
||||
PRIVATE->shm->read(ba.data(), ba.size_s(), sizeof(data));
|
||||
ba >> cells;
|
||||
#endif
|
||||
//piCout << cursor_x << cursor_y;
|
||||
# endif
|
||||
// piCout << cursor_x << cursor_y;
|
||||
}
|
||||
|
||||
|
||||
void PITerminal::getCursor(int & x, int & y) {
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
if (!PRIVATE->shm) return;
|
||||
int sz = 0;
|
||||
PRIVATE->shm->read(&sz, 4);
|
||||
#else
|
||||
# else
|
||||
x = PRIVATE->cur_x;
|
||||
y = PRIVATE->cur_y;
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
@@ -370,7 +373,7 @@ void PITerminal::run() {
|
||||
cursor_tm.reset();
|
||||
cursor_blink = !cursor_blink;
|
||||
}
|
||||
#ifndef WINDOWS
|
||||
# ifndef WINDOWS
|
||||
# ifdef HAS_FORKPTY
|
||||
if (PRIVATE->fd == 0) return;
|
||||
PRIVATE->tmp_buf.resize(BUFFER_SIZE);
|
||||
@@ -378,8 +381,8 @@ void PITerminal::run() {
|
||||
bool used = false;
|
||||
if (readed > 0) {
|
||||
PRIVATE->last_read = true;
|
||||
//piCoutObj << "readed" << readed << PIString(PRIVATE->tmp_buf.resized(readed)).replaceAll("\e", "\\e");
|
||||
//piCoutObj << "readed" << readed << (PRIVATE->tmp_buf.resized(readed));
|
||||
// piCoutObj << "readed" << readed << PIString(PRIVATE->tmp_buf.resized(readed)).replaceAll("\e", "\\e");
|
||||
// piCoutObj << "readed" << readed << (PRIVATE->tmp_buf.resized(readed));
|
||||
PRIVATE->read_buf.append(PRIVATE->tmp_buf.resized(readed));
|
||||
for (;;) {
|
||||
int ind = -1;
|
||||
@@ -395,13 +398,12 @@ void PITerminal::run() {
|
||||
}
|
||||
bool parse = PRIVATE->read_buf.size_s() >= BUFFER_SIZE;
|
||||
if (PRIVATE->read_buf.size_s() == 1)
|
||||
if (PRIVATE->read_buf[0] < 0x80)
|
||||
parse = true;
|
||||
if (PRIVATE->read_buf[0] < 0x80) parse = true;
|
||||
if (parse) {
|
||||
parseInput(PIString(PRIVATE->read_buf));
|
||||
PRIVATE->read_buf.clear();
|
||||
}
|
||||
//printf("%s", PRIVATE->read_buf.data());
|
||||
// printf("%s", PRIVATE->read_buf.data());
|
||||
}
|
||||
if (!used && !PRIVATE->last_read && !PRIVATE->read_buf.isEmpty()) {
|
||||
parseInput(PIString(PRIVATE->read_buf));
|
||||
@@ -409,14 +411,14 @@ void PITerminal::run() {
|
||||
}
|
||||
PRIVATE->last_read = false;
|
||||
# endif
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
#ifndef WINDOWS
|
||||
# ifndef WINDOWS
|
||||
void PITerminal::parseInput(const PIString & s) {
|
||||
//piCoutObj << s.replaceAll("\e", "\\e");
|
||||
//printf("%s", s.data());
|
||||
// piCoutObj << s.replaceAll("\e", "\\e");
|
||||
// printf("%s", s.data());
|
||||
for (int i = 0; i < s.size_s(); ++i) {
|
||||
if (s[i].unicode16Code() == 0) break;
|
||||
if (PRIVATE->is_esc_seq) {
|
||||
@@ -429,7 +431,7 @@ void PITerminal::parseInput(const PIString & s) {
|
||||
if (isCompleteEscSeq(PRIVATE->esc_seq)) {
|
||||
PRIVATE->is_esc_seq = false;
|
||||
applyEscSeq(PRIVATE->esc_seq);
|
||||
//piCoutObj << PRIVATE->esc_seq;
|
||||
// piCoutObj << PRIVATE->esc_seq;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
@@ -444,14 +446,15 @@ void PITerminal::parseInput(const PIString & s) {
|
||||
}
|
||||
if (s[i] == '\r') continue;
|
||||
if (s[i] == '\n') {
|
||||
//piCoutObj << "new line";
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i) cells[PRIVATE->cur_y][i].format = PRIVATE->cur_format;
|
||||
// piCoutObj << "new line";
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i)
|
||||
cells[PRIVATE->cur_y][i].format = PRIVATE->cur_format;
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
PRIVATE->cur_x = 0;
|
||||
moveCursor(0, 1);
|
||||
continue;
|
||||
}
|
||||
//piCoutObj << "char" << s[i] << s[i].unicode16Code() << "at" << PRIVATE->cur_x << PRIVATE->cur_y;
|
||||
// piCoutObj << "char" << s[i] << s[i].unicode16Code() << "at" << PRIVATE->cur_x << PRIVATE->cur_y;
|
||||
cells[PRIVATE->cur_y][PRIVATE->cur_x].symbol = s[i];
|
||||
cells[PRIVATE->cur_y][PRIVATE->cur_x].format = PRIVATE->cur_format;
|
||||
moveCursor(1, 0);
|
||||
@@ -475,7 +478,7 @@ bool PITerminal::isCompleteEscSeq(const PIString & es) {
|
||||
void PITerminal::applyEscSeq(PIString es) {
|
||||
piCoutObj << es;
|
||||
if (es.size_s() < 2) return;
|
||||
// PIScreenTypes::Cell line_cell = PIScreenTypes::Cell(' ', PRIVATE->line_format);
|
||||
// PIScreenTypes::Cell line_cell = PIScreenTypes::Cell(' ', PRIVATE->line_format);
|
||||
PIScreenTypes::Cell def_cell = PIScreenTypes::Cell(' ', PRIVATE->cur_format);
|
||||
if (es[1] == '?' && es.size_s() >= 2) {
|
||||
char a = es.takeRight(1)[0].toAscii();
|
||||
@@ -498,7 +501,8 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
case 1047:
|
||||
if (val) {
|
||||
PRIVATE->cells_save = cells;
|
||||
for (int i = 0; i < size_y; ++i) cells[i].fill(def_cell);
|
||||
for (int i = 0; i < size_y; ++i)
|
||||
cells[i].fill(def_cell);
|
||||
} else {
|
||||
cells = PRIVATE->cells_save;
|
||||
}
|
||||
@@ -513,7 +517,7 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
return;
|
||||
}
|
||||
PIStringList args = es.split(";");
|
||||
piForeachC (PIString & a, args) {
|
||||
piForeachC(PIString & a, args) {
|
||||
int av = a.toInt();
|
||||
switch (av) {
|
||||
case 0: PRIVATE->cur_format = PIScreenTypes::CellFormat(); break;
|
||||
@@ -524,8 +528,14 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
default: {
|
||||
bool col = false, target = false;
|
||||
int cid = av % 10;
|
||||
if (av >= 30 && av <= 37) {col = true; target = false;}
|
||||
if (av >= 40 && av <= 47) {col = true; target = true;}
|
||||
if (av >= 30 && av <= 37) {
|
||||
col = true;
|
||||
target = false;
|
||||
}
|
||||
if (av >= 40 && av <= 47) {
|
||||
col = true;
|
||||
target = true;
|
||||
}
|
||||
if (col) {
|
||||
int cfl = 0;
|
||||
switch (cid) {
|
||||
@@ -579,32 +589,36 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
int x(0), y(0);
|
||||
if (!args[0].isEmpty()) y = args[0].toInt() - 1;
|
||||
if (!args[1].isEmpty()) x = args[1].toInt() - 1;
|
||||
//piCoutObj << x << y;
|
||||
// piCoutObj << x << y;
|
||||
PRIVATE->cur_x = piClamp(x, 0, size_x - 1);
|
||||
PRIVATE->cur_y = piClamp(y, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'A') { // cursor up
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_y = piClamp(PRIVATE->cur_y - v, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'B') { // cursor down
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_y = piClamp(PRIVATE->cur_y + v, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'C' || es.back() == 'a') { // cursor forward, next column
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_x = piClamp(PRIVATE->cur_x + v, 0, size_x - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'D') { // cursor back
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_x = piClamp(PRIVATE->cur_x - v, 0, size_x - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
@@ -616,66 +630,92 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
}
|
||||
if (es.back() == 'd') { // goto line
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_x = 0;
|
||||
PRIVATE->cur_y = piClamp(v - 1, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'E' || es.back() == 'e') { // next line
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_x = 0;
|
||||
PRIVATE->cur_y = piClamp(PRIVATE->cur_y + v, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'F') { // previous line
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
PRIVATE->cur_x = 0;
|
||||
PRIVATE->cur_y = piClamp(PRIVATE->cur_y - v, 0, size_y - 1);
|
||||
PRIVATE->line_format = PRIVATE->cur_format;
|
||||
}
|
||||
if (es.back() == 'L') { // insert lines
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
for (int i = piClamp(size_y - 1, PRIVATE->win_y0, PRIVATE->win_y1); i >= piClamp(PRIVATE->cur_y + v, PRIVATE->win_y0, PRIVATE->win_y1); --i) cells[i] = cells[i - v];
|
||||
for (int j = piClamp(PRIVATE->cur_y, PRIVATE->win_y0, PRIVATE->win_y1); j < piClamp(PRIVATE->cur_y + v, PRIVATE->win_y0, PRIVATE->win_y1); ++j)
|
||||
for (int i = 0; i < PRIVATE->cur_x; ++i) cells[j][i] = def_cell;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
for (int i = piClamp(size_y - 1, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
i >= piClamp(PRIVATE->cur_y + v, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
--i)
|
||||
cells[i] = cells[i - v];
|
||||
for (int j = piClamp(PRIVATE->cur_y, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
j < piClamp(PRIVATE->cur_y + v, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
++j)
|
||||
for (int i = 0; i < PRIVATE->cur_x; ++i)
|
||||
cells[j][i] = def_cell;
|
||||
}
|
||||
if (es.back() == 'M') { // delete lines
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
for (int i = piClamp(PRIVATE->cur_y, PRIVATE->win_y0, PRIVATE->win_y1); i < piClamp(size_y - v, PRIVATE->win_y0, PRIVATE->win_y1); ++i) cells[i] = cells[i + v];
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
for (int i = piClamp(PRIVATE->cur_y, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
i < piClamp(size_y - v, PRIVATE->win_y0, PRIVATE->win_y1);
|
||||
++i)
|
||||
cells[i] = cells[i + v];
|
||||
for (int j = piClamp(size_y - v, PRIVATE->win_y0, PRIVATE->win_y1); j < piClamp(size_y, PRIVATE->win_y0, PRIVATE->win_y1); ++j)
|
||||
for (int i = 0; i < PRIVATE->cur_x; ++i) cells[j][i] = def_cell;
|
||||
for (int i = 0; i < PRIVATE->cur_x; ++i)
|
||||
cells[j][i] = def_cell;
|
||||
}
|
||||
if (es.back() == 'P') { // delete characters
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
for (int i = PRIVATE->cur_x; i < size_x - v; ++i) cells[PRIVATE->cur_y][i] = cells[PRIVATE->cur_y][i + v];
|
||||
for (int i = size_x - v; i < size_x; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
for (int i = PRIVATE->cur_x; i < size_x - v; ++i)
|
||||
cells[PRIVATE->cur_y][i] = cells[PRIVATE->cur_y][i + v];
|
||||
for (int i = size_x - v; i < size_x; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
}
|
||||
if (es.back() == '@') { // delete characters
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt(); if (v == 0) v = 1;
|
||||
for (int i = size_x - 1; i >= PRIVATE->cur_x + v; --i) cells[PRIVATE->cur_y][i] = cells[PRIVATE->cur_y][i - v];
|
||||
for (int i = PRIVATE->cur_x; i < PRIVATE->cur_x + v; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
int v = es.toInt();
|
||||
if (v == 0) v = 1;
|
||||
for (int i = size_x - 1; i >= PRIVATE->cur_x + v; --i)
|
||||
cells[PRIVATE->cur_y][i] = cells[PRIVATE->cur_y][i - v];
|
||||
for (int i = PRIVATE->cur_x; i < PRIVATE->cur_x + v; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
}
|
||||
if (es.back() == 'J') { // erase data
|
||||
es.cutLeft(1).cutRight(1);
|
||||
int v = es.toInt();
|
||||
switch (v) {
|
||||
case 0:
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
for (int i = PRIVATE->cur_y + 1; i < size_y; ++i) cells[i].fill(def_cell);
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
for (int i = PRIVATE->cur_y + 1; i < size_y; ++i)
|
||||
cells[i].fill(def_cell);
|
||||
break;
|
||||
case 1:
|
||||
for (int i = 0; i <= PRIVATE->cur_x; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
for (int i = 0; i < PRIVATE->cur_y; ++i) cells[i].fill(def_cell);
|
||||
for (int i = 0; i <= PRIVATE->cur_x; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
for (int i = 0; i < PRIVATE->cur_y; ++i)
|
||||
cells[i].fill(def_cell);
|
||||
break;
|
||||
case 2:
|
||||
for (int i = 0; i < size_y; ++i) cells[i].fill(def_cell);
|
||||
//PRIVATE->cur_x = PRIVATE->cur_y = 0;
|
||||
for (int i = 0; i < size_y; ++i)
|
||||
cells[i].fill(def_cell);
|
||||
// PRIVATE->cur_x = PRIVATE->cur_y = 0;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -684,14 +724,14 @@ void PITerminal::applyEscSeq(PIString es) {
|
||||
int v = es.toInt();
|
||||
switch (v) {
|
||||
case 0:
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
for (int i = PRIVATE->cur_x; i < size_x; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
break;
|
||||
case 1:
|
||||
for (int i = 0; i <= PRIVATE->cur_x; ++i) cells[PRIVATE->cur_y][i] = def_cell;
|
||||
break;
|
||||
case 2:
|
||||
cells[PRIVATE->cur_y].fill(def_cell);
|
||||
for (int i = 0; i <= PRIVATE->cur_x; ++i)
|
||||
cells[PRIVATE->cur_y][i] = def_cell;
|
||||
break;
|
||||
case 2: cells[PRIVATE->cur_y].fill(def_cell); break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -710,7 +750,7 @@ void PITerminal::moveCursor(int dx, int dy) {
|
||||
}
|
||||
if (PRIVATE->cur_y >= size_y) {
|
||||
int scroll = piMini(PRIVATE->cur_y - size_y + 1, size_y - 1);
|
||||
//piCout << "scroll" << size_x << size_y << size_y - scroll - 1;
|
||||
// piCout << "scroll" << size_x << size_y << size_y - scroll - 1;
|
||||
PRIVATE->cur_y = size_y - 1;
|
||||
for (int y = 0; y < size_y - scroll; ++y)
|
||||
cells[y] = cells[y + scroll];
|
||||
@@ -721,16 +761,18 @@ void PITerminal::moveCursor(int dx, int dy) {
|
||||
|
||||
|
||||
int PITerminal::termType(const PIString & t) {
|
||||
if (t == "xterm") return PIKbdListener::vt_xterm;
|
||||
else if (t == "linux") return PIKbdListener::vt_linux;
|
||||
if (t == "xterm")
|
||||
return PIKbdListener::vt_xterm;
|
||||
else if (t == "linux")
|
||||
return PIKbdListener::vt_linux;
|
||||
return PIKbdListener::vt_none;
|
||||
}
|
||||
#endif
|
||||
# endif
|
||||
|
||||
|
||||
bool PITerminal::initialize() {
|
||||
destroy();
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
/*SECURITY_ATTRIBUTES sa;
|
||||
sa.nLength = sizeof(SECURITY_ATTRIBUTES);
|
||||
sa.bInheritHandle = true;
|
||||
@@ -746,18 +788,18 @@ bool PITerminal::initialize() {
|
||||
destroy();
|
||||
return false;
|
||||
}*/
|
||||
//CreatePipe(&(PRIVATE->pipe_out[0]), &(PRIVATE->pipe_out[1]), &sa, 0);
|
||||
//SetHandleInformation(PRIVATE->pipe_in[1], HANDLE_FLAG_INHERIT, 0);
|
||||
//SetHandleInformation(PRIVATE->hConBuf, HANDLE_FLAG_INHERIT, 0);
|
||||
//GetStartupInfoA(&PRIVATE->si);
|
||||
// CreatePipe(&(PRIVATE->pipe_out[0]), &(PRIVATE->pipe_out[1]), &sa, 0);
|
||||
// SetHandleInformation(PRIVATE->pipe_in[1], HANDLE_FLAG_INHERIT, 0);
|
||||
// SetHandleInformation(PRIVATE->hConBuf, HANDLE_FLAG_INHERIT, 0);
|
||||
// GetStartupInfoA(&PRIVATE->si);
|
||||
memset(&PRIVATE->si, 0, sizeof(PRIVATE->si));
|
||||
PRIVATE->si.cb = sizeof(STARTUPINFO);
|
||||
//PRIVATE->si.dwFlags |= STARTF_USESTDHANDLES;
|
||||
// PRIVATE->si.dwFlags |= STARTF_USESTDHANDLES;
|
||||
PRIVATE->si.dwFlags |= STARTF_USESHOWWINDOW;
|
||||
PRIVATE->si.dwFlags |= STARTF_USECOUNTCHARS;
|
||||
//PRIVATE->si.hStdInput = PRIVATE->pipe;
|
||||
//PRIVATE->si.hStdOutput = PRIVATE->hConBuf;
|
||||
//PRIVATE->si.hStdError = PRIVATE->hConBuf;
|
||||
// PRIVATE->si.hStdInput = PRIVATE->pipe;
|
||||
// PRIVATE->si.hStdOutput = PRIVATE->hConBuf;
|
||||
// PRIVATE->si.hStdError = PRIVATE->hConBuf;
|
||||
PRIVATE->si.wShowWindow = SW_HIDE;
|
||||
PRIVATE->si.dwXCountChars = 80;
|
||||
PRIVATE->si.dwYCountChars = 24;
|
||||
@@ -767,12 +809,28 @@ bool PITerminal::initialize() {
|
||||
PIString shmh = PIString::fromNumber(randomi() % 10000);
|
||||
PIString pname = "\\\\.\\pipe\\piterm" + shmh;
|
||||
PIString cmd = "piterminal \"" + shmh + "\" \"" + pname + "\"";
|
||||
if(!CreateProcessA(0, (LPSTR)cmd.dataAscii(), 0, 0, false, CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP, 0, 0, &PRIVATE->si, &PRIVATE->pi)) {
|
||||
if (!CreateProcessA(0,
|
||||
(LPSTR)cmd.dataAscii(),
|
||||
0,
|
||||
0,
|
||||
false,
|
||||
CREATE_NEW_CONSOLE | CREATE_NEW_PROCESS_GROUP,
|
||||
0,
|
||||
0,
|
||||
&PRIVATE->si,
|
||||
&PRIVATE->pi)) {
|
||||
piCoutObj << "CreateProcess error," << errorString();
|
||||
destroy();
|
||||
return false;
|
||||
}
|
||||
PRIVATE->pipe = CreateNamedPipeA((LPSTR)pname.dataAscii(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT, 2, PIPE_BUFFER_SIZE, PIPE_BUFFER_SIZE, 1000, NULL);
|
||||
PRIVATE->pipe = CreateNamedPipeA((LPSTR)pname.dataAscii(),
|
||||
PIPE_ACCESS_DUPLEX,
|
||||
PIPE_TYPE_BYTE | PIPE_READMODE_BYTE | PIPE_WAIT,
|
||||
2,
|
||||
PIPE_BUFFER_SIZE,
|
||||
PIPE_BUFFER_SIZE,
|
||||
1000,
|
||||
NULL);
|
||||
if (PRIVATE->pipe == INVALID_HANDLE_VALUE) {
|
||||
piCoutObj << "CreateNamedPipe error," << errorString();
|
||||
destroy();
|
||||
@@ -792,26 +850,27 @@ bool PITerminal::initialize() {
|
||||
return false;
|
||||
}
|
||||
if (PRIVATE->shm) delete PRIVATE->shm;
|
||||
PRIVATE->shm = new PISharedMemory("piterm_aux" + shmh, 1024*1024);
|
||||
PRIVATE->shm = new PISharedMemory("piterm_aux" + shmh, 1024 * 1024);
|
||||
CloseHandle(PRIVATE->pi.hThread);
|
||||
resize(dsize_x, dsize_y);
|
||||
#else
|
||||
# else
|
||||
# ifdef HAS_FORKPTY
|
||||
char pty[256]; memset(pty, 0, 256);
|
||||
char pty[256];
|
||||
memset(pty, 0, 256);
|
||||
winsize ws;
|
||||
ws.ws_col = dsize_x;
|
||||
ws.ws_row = dsize_y;
|
||||
PIStringList env = PIProcess::currentEnvironment();
|
||||
piForeachC (PIString & e, env)
|
||||
piForeachC(PIString & e, env)
|
||||
if (e.startsWith("TERM=")) {
|
||||
PRIVATE->term_type = termType(e.mid(5).trim().toLowerCase());
|
||||
//piCout << PRIVATE->term_type;
|
||||
// piCout << PRIVATE->term_type;
|
||||
break;
|
||||
}
|
||||
pid_t fr = forkpty(&(PRIVATE->fd), pty, 0, &ws);
|
||||
//piCoutObj << fr << PRIVATE->fd << pty;
|
||||
// piCoutObj << fr << PRIVATE->fd << pty;
|
||||
if (fr == 0) {
|
||||
char ** argv = new char*[2];
|
||||
char ** argv = new char *[2];
|
||||
PIByteArray shell = PRIVATE->shell.toByteArray();
|
||||
argv[0] = new char[shell.size() + 1];
|
||||
memcpy(argv[0], shell.data(), shell.size());
|
||||
@@ -853,7 +912,7 @@ bool PITerminal::initialize() {
|
||||
resize(size_x, size_y);
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
# endif
|
||||
cursor_blink = false;
|
||||
cursor_tm.reset();
|
||||
start(40);
|
||||
@@ -862,27 +921,25 @@ bool PITerminal::initialize() {
|
||||
|
||||
|
||||
void PITerminal::destroy() {
|
||||
//piCout << "destroy ...";
|
||||
// piCout << "destroy ...";
|
||||
stop();
|
||||
waitForFinish(1000);
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
if (PRIVATE->pi.hProcess) {
|
||||
//piCout << "term";
|
||||
//TerminateProcess(PRIVATE->pi.hProcess, 0);
|
||||
// piCout << "term";
|
||||
// TerminateProcess(PRIVATE->pi.hProcess, 0);
|
||||
GenerateConsoleCtrlEvent(CTRL_C_EVENT, PRIVATE->pi.dwProcessId);
|
||||
CloseHandle(PRIVATE->pi.hProcess);
|
||||
}
|
||||
if (PRIVATE->pipe != INVALID_HANDLE_VALUE) CloseHandle(PRIVATE->pipe);
|
||||
if (PRIVATE->hConBuf != INVALID_HANDLE_VALUE) CloseHandle(PRIVATE->hConBuf);
|
||||
//piCout << "destroy" << size_y;
|
||||
#else
|
||||
// piCout << "destroy" << size_y;
|
||||
# else
|
||||
# ifdef HAS_FORKPTY
|
||||
if (PRIVATE->pid != 0)
|
||||
kill(PRIVATE->pid, SIGKILL);
|
||||
if (PRIVATE->fd != 0)
|
||||
::close(PRIVATE->fd);
|
||||
if (PRIVATE->pid != 0) kill(PRIVATE->pid, SIGKILL);
|
||||
if (PRIVATE->fd != 0) ::close(PRIVATE->fd);
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
initPrivate();
|
||||
}
|
||||
|
||||
@@ -891,17 +948,17 @@ bool PITerminal::resize(int cols, int rows) {
|
||||
bool ret = true;
|
||||
dsize_x = cols;
|
||||
dsize_y = rows;
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
if (PRIVATE->pipe == INVALID_HANDLE_VALUE) return false;
|
||||
PIByteArray msg;
|
||||
msg << int(mtResize) << dsize_x << dsize_y;
|
||||
writePipe(PRIVATE->pipe, msg);
|
||||
#else
|
||||
# else
|
||||
# ifdef HAS_FORKPTY
|
||||
if (PRIVATE->fd == 0) return false;
|
||||
size_x = dsize_x;
|
||||
size_y = dsize_y;
|
||||
//piCout << "resize" << PRIVATE->fd << size_x << size_y;
|
||||
// piCout << "resize" << PRIVATE->fd << size_x << size_y;
|
||||
winsize ws;
|
||||
ws.ws_col = cols;
|
||||
ws.ws_row = rows;
|
||||
@@ -912,7 +969,7 @@ bool PITerminal::resize(int cols, int rows) {
|
||||
for (int i = 0; i < size_y; ++i)
|
||||
PRIVATE->cells_save[i].resize(size_x);
|
||||
# endif
|
||||
#endif
|
||||
# endif
|
||||
cells.resize(size_y);
|
||||
for (int i = 0; i < size_y; ++i)
|
||||
cells[i].resize(size_x);
|
||||
|
||||
@@ -20,7 +20,7 @@
|
||||
#include "piauth.h"
|
||||
#define PIAUTH_NOISE_MAX_SIZE 256
|
||||
|
||||
PIAuth::PIAuth(const PIByteArray & sign) : PIObject() {
|
||||
PIAuth::PIAuth(const PIByteArray & sign): PIObject() {
|
||||
setName("Client");
|
||||
role = Client;
|
||||
state = NotConnected;
|
||||
@@ -56,7 +56,7 @@ PIByteArray PIAuth::startServer() {
|
||||
state = AuthProbe;
|
||||
PIByteArray ba;
|
||||
crypt.generateKeypair(my_pk, box_sk);
|
||||
PIByteArray noise = crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE+128);
|
||||
PIByteArray noise = crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE + 128);
|
||||
ba << (int)state << custom_info << sign_pk << my_pk << noise;
|
||||
PIByteArray sign = crypt.signMessage(ba, sign_sk);
|
||||
ba << sign;
|
||||
@@ -70,12 +70,12 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
int s;
|
||||
ba >> s;
|
||||
rstate = (State)s;
|
||||
// if (state != rstate) return disconect(ba);
|
||||
// if (state != rstate) return disconect(ba);
|
||||
|
||||
//client side
|
||||
// client side
|
||||
if (role == Client) {
|
||||
if (state == AuthProbe && rstate == AuthProbe) {
|
||||
if (ba.size() < sizeof(int)*5) return disconnect(ba, "invalid data size");
|
||||
if (ba.size() < sizeof(int) * 5) return disconnect(ba, "invalid data size");
|
||||
PIByteArray rinfo;
|
||||
PIByteArray rsign;
|
||||
PIByteArray rsign_pk;
|
||||
@@ -103,7 +103,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
tba << sign;
|
||||
tba = crypt.crypt(tba, box_pk, box_sk);
|
||||
state = AuthReply;
|
||||
noise = crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
noise = crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
ba << (int)state << tba << my_pk << noise;
|
||||
sign = crypt.signMessage(ba, sign_sk);
|
||||
ba << sign;
|
||||
@@ -154,14 +154,14 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
ba.clear();
|
||||
state = Connected;
|
||||
connected(PIString());
|
||||
ba << (int)state << crypt.crypt(custom_info, secret_key) << crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
ba << (int)state << crypt.crypt(custom_info, secret_key) << crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
return state;
|
||||
}
|
||||
if (state == Connected && rstate == Connected) {
|
||||
ba.clear();
|
||||
state = Connected;
|
||||
connected(PIString());
|
||||
ba << (int)state << crypt.crypt(custom_info, secret_key) << crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
ba << (int)state << crypt.crypt(custom_info, secret_key) << crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -169,7 +169,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
// server side
|
||||
if (role == Server) {
|
||||
if (state == AuthProbe && rstate == AuthReply) {
|
||||
if (ba.size() < sizeof(int)*4) return disconnect(ba, "invalid data size");
|
||||
if (ba.size() < sizeof(int) * 4) return disconnect(ba, "invalid data size");
|
||||
PIByteArray ctba, tba;
|
||||
PIByteArray noise;
|
||||
PIByteArray rsign1, rsign2;
|
||||
@@ -179,7 +179,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
bool ok = false;
|
||||
tba = crypt.decrypt(ctba, pk, box_sk, &ok);
|
||||
if (tba.isEmpty() || !ok) return disconnect(ba, "Message corrupted");
|
||||
if (tba.size() < sizeof(int)*3) return disconnect(tba, "invalid data size");
|
||||
if (tba.size() < sizeof(int) * 3) return disconnect(tba, "invalid data size");
|
||||
tba >> rsign_pk >> box_pk >> mpk >> rsign2;
|
||||
if (pk != box_pk || mpk != my_pk) return disconnect(ba, "Invalid public key");
|
||||
ba.clear();
|
||||
@@ -197,7 +197,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
ba.clear();
|
||||
tba.clear();
|
||||
state = PassRequest;
|
||||
noise = crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
noise = crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
tba << sign_pk << noise << box_pk;
|
||||
tba = crypt.crypt(tba, box_pk, box_sk);
|
||||
ba << (int)state << tba;
|
||||
@@ -223,7 +223,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
if (ctba.isEmpty() || pass_hash.isEmpty()) auth = false;
|
||||
passwordCheck(auth);
|
||||
if (!auth) {
|
||||
// piSleep(1);
|
||||
// piSleep(1);
|
||||
return disconnect(ba, "Invalid password");
|
||||
}
|
||||
state = KeyExchange;
|
||||
@@ -239,7 +239,7 @@ PIAuth::State PIAuth::receive(PIByteArray & ba) {
|
||||
if (!ok) return disconnect(ba, "Error while exchange keys");
|
||||
state = Connected;
|
||||
connected(rinfo);
|
||||
ba << (int)state << crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
ba << (int)state << crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
return state;
|
||||
}
|
||||
}
|
||||
@@ -276,7 +276,7 @@ PIAuth::State PIAuth::disconnect(PIByteArray & ba, const PIString & error) {
|
||||
|
||||
|
||||
bool PIAuth::isAuthorizedKey(const PIByteArray & pkey) {
|
||||
for (int i=0; i<auth_pkeys.size_s(); ++i) {
|
||||
for (int i = 0; i < auth_pkeys.size_s(); ++i) {
|
||||
if (pkey == auth_pkeys[i]) return true;
|
||||
}
|
||||
return false;
|
||||
@@ -286,7 +286,7 @@ bool PIAuth::isAuthorizedKey(const PIByteArray & pkey) {
|
||||
PIByteArray PIAuth::createSKMessage() {
|
||||
secret_key = crypt.generateKey();
|
||||
PIByteArray tba;
|
||||
PIByteArray noise = crypt.generateRandomBuff(randomi()%PIAUTH_NOISE_MAX_SIZE);
|
||||
PIByteArray noise = crypt.generateRandomBuff(randomi() % PIAUTH_NOISE_MAX_SIZE);
|
||||
tba << secret_key << noise;
|
||||
tba = crypt.crypt(tba, box_pk, box_sk);
|
||||
PIByteArray ret;
|
||||
|
||||
@@ -22,7 +22,9 @@
|
||||
# include <sodium.h>
|
||||
#endif
|
||||
|
||||
#define PICRYPT_DISABLED_WARNING piCout << "[PICrypt]" << "Warning: PICrypt is disabled, to enable install sodium library and rebuild pip";
|
||||
#define PICRYPT_DISABLED_WARNING \
|
||||
piCout << "[PICrypt]" \
|
||||
<< "Warning: PICrypt is disabled, to enable install sodium library and rebuild pip";
|
||||
|
||||
const char hash_def_key[] = "_picrypt_\0\0\0\0\0\0\0";
|
||||
const int hash_def_key_size = 9;
|
||||
@@ -30,7 +32,9 @@ const int hash_def_key_size = 9;
|
||||
|
||||
PICrypt::PICrypt() {
|
||||
#ifdef PIP_CRYPT
|
||||
if (!init()) piCout << "[PICrypt]" << "Error while initialize sodium!";
|
||||
if (!init())
|
||||
piCout << "[PICrypt]"
|
||||
<< "Error while initialize sodium!";
|
||||
nonce_.resize(crypto_secretbox_NONCEBYTES);
|
||||
key_.resize(crypto_secretbox_KEYBYTES);
|
||||
randombytes_buf(key_.data(), key_.size());
|
||||
@@ -53,7 +57,7 @@ PIByteArray PICrypt::setKey(const PIString & secret) {
|
||||
#ifdef PIP_CRYPT
|
||||
hash.resize(crypto_generichash_BYTES);
|
||||
PIByteArray s(secret.data(), secret.size());
|
||||
crypto_generichash(hash.data(), hash.size(), s.data(), s.size(), (const uchar*)hash_def_key, hash_def_key_size);
|
||||
crypto_generichash(hash.data(), hash.size(), s.data(), s.size(), (const uchar *)hash_def_key, hash_def_key_size);
|
||||
hash.resize(key_.size());
|
||||
setKey(hash);
|
||||
#endif
|
||||
@@ -76,9 +80,8 @@ PIByteArray PICrypt::crypt(const PIByteArray & data) {
|
||||
PIByteArray PICrypt::crypt(const PIByteArray & data, PIByteArray key) {
|
||||
PIByteArray ret;
|
||||
#ifdef PIP_CRYPT
|
||||
if (key.size() != crypto_secretbox_KEYBYTES)
|
||||
key.resize(crypto_secretbox_KEYBYTES, ' ');
|
||||
//return PIByteArray();
|
||||
if (key.size() != crypto_secretbox_KEYBYTES) key.resize(crypto_secretbox_KEYBYTES, ' ');
|
||||
// return PIByteArray();
|
||||
if (!init()) return ret;
|
||||
PIByteArray n;
|
||||
ret.resize(data.size() + crypto_secretbox_MACBYTES);
|
||||
@@ -93,7 +96,7 @@ PIByteArray PICrypt::crypt(const PIByteArray & data, PIByteArray key) {
|
||||
}
|
||||
|
||||
|
||||
PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, bool *ok) {
|
||||
PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, bool * ok) {
|
||||
PIByteArray ret;
|
||||
#ifdef PIP_CRYPT
|
||||
if (crypt_data.size() < nonce_.size() + crypto_secretbox_MACBYTES) {
|
||||
@@ -113,14 +116,13 @@ PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, bool *ok) {
|
||||
}
|
||||
|
||||
|
||||
PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, PIByteArray key, bool *ok) {
|
||||
PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, PIByteArray key, bool * ok) {
|
||||
PIByteArray ret;
|
||||
#ifdef PIP_CRYPT
|
||||
if (key.size() != crypto_secretbox_KEYBYTES)
|
||||
key.resize(crypto_secretbox_KEYBYTES, ' ');
|
||||
if (key.size() != crypto_secretbox_KEYBYTES) key.resize(crypto_secretbox_KEYBYTES, ' ');
|
||||
/*if (ok) *ok = false;
|
||||
return PIByteArray();
|
||||
}*/
|
||||
}*/
|
||||
if (crypt_data.size() < crypto_secretbox_NONCEBYTES + crypto_secretbox_MACBYTES) {
|
||||
if (ok) *ok = false;
|
||||
return PIByteArray();
|
||||
@@ -134,7 +136,8 @@ PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, PIByteArray key, bo
|
||||
if (ok) *ok = false;
|
||||
// piCout << "[PICrypt]" << "bad key_";
|
||||
return PIByteArray();
|
||||
} else if (ok) *ok = true;
|
||||
} else if (ok)
|
||||
*ok = true;
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
#endif
|
||||
@@ -148,7 +151,7 @@ PIByteArray PICrypt::hash(const PIString & secret) {
|
||||
if (!init()) return hash;
|
||||
hash.resize(crypto_generichash_BYTES);
|
||||
PIByteArray s(secret.data(), secret.size());
|
||||
crypto_generichash(hash.data(), hash.size(), s.data(), s.size(),(const uchar*)hash_def_key, hash_def_key_size);
|
||||
crypto_generichash(hash.data(), hash.size(), s.data(), s.size(), (const uchar *)hash_def_key, hash_def_key_size);
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
#endif
|
||||
@@ -161,7 +164,7 @@ PIByteArray PICrypt::hash(const PIByteArray & data) {
|
||||
#ifdef PIP_CRYPT
|
||||
if (!init()) return hash;
|
||||
hash.resize(crypto_generichash_BYTES);
|
||||
crypto_generichash(hash.data(), hash.size(), data.data(), data.size(), (const uchar*)hash_def_key, hash_def_key_size);
|
||||
crypto_generichash(hash.data(), hash.size(), data.data(), data.size(), (const uchar *)hash_def_key, hash_def_key_size);
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
#endif
|
||||
@@ -169,7 +172,7 @@ PIByteArray PICrypt::hash(const PIByteArray & data) {
|
||||
}
|
||||
|
||||
|
||||
PIByteArray PICrypt::hash(const PIByteArray & data, const unsigned char *key, size_t keylen) {
|
||||
PIByteArray PICrypt::hash(const PIByteArray & data, const unsigned char * key, size_t keylen) {
|
||||
PIByteArray hash;
|
||||
#ifdef PIP_CRYPT
|
||||
if (!init()) return hash;
|
||||
@@ -192,13 +195,16 @@ size_t PICrypt::sizeHash() {
|
||||
}
|
||||
|
||||
|
||||
ullong PICrypt::shorthash(const PIString& s, PIByteArray key) {
|
||||
ullong PICrypt::shorthash(const PIString & s, PIByteArray key) {
|
||||
ullong hash = 0;
|
||||
#ifdef PIP_CRYPT
|
||||
if (crypto_shorthash_BYTES != sizeof(hash)) piCout << "[PICrypt]" << "internal error: bad hash size";
|
||||
if (crypto_shorthash_BYTES != sizeof(hash))
|
||||
piCout << "[PICrypt]"
|
||||
<< "internal error: bad hash size";
|
||||
if (!init()) return hash;
|
||||
if (key.size() != crypto_shorthash_KEYBYTES) {
|
||||
piCout << "[PICrypt]" << "invalid key size" << key.size() << ", shoud be" << crypto_shorthash_KEYBYTES << ", filled zeros";
|
||||
piCout << "[PICrypt]"
|
||||
<< "invalid key size" << key.size() << ", shoud be" << crypto_shorthash_KEYBYTES << ", filled zeros";
|
||||
key.resize(crypto_shorthash_KEYBYTES, 0);
|
||||
}
|
||||
PIByteArray in(s.data(), s.size());
|
||||
@@ -345,16 +351,13 @@ PIByteArray PICrypt::crypt(const PIByteArray & data, const PIByteArray & public_
|
||||
PIByteArray ret;
|
||||
#ifdef PIP_CRYPT
|
||||
if (!init()) return ret;
|
||||
if (public_key.size() != crypto_box_PUBLICKEYBYTES)
|
||||
return ret;
|
||||
if (secret_key.size() != crypto_box_SECRETKEYBYTES)
|
||||
return ret;
|
||||
if (public_key.size() != crypto_box_PUBLICKEYBYTES) return ret;
|
||||
if (secret_key.size() != crypto_box_SECRETKEYBYTES) return ret;
|
||||
PIByteArray n;
|
||||
ret.resize(data.size() + crypto_box_MACBYTES);
|
||||
n.resize(crypto_box_NONCEBYTES);
|
||||
randombytes_buf(n.data(), n.size());
|
||||
if (crypto_box_easy(ret.data(), data.data(), data.size(), n.data(), public_key.data(), secret_key.data()) != 0)
|
||||
return PIByteArray();
|
||||
if (crypto_box_easy(ret.data(), data.data(), data.size(), n.data(), public_key.data(), secret_key.data()) != 0) return PIByteArray();
|
||||
ret.append(n);
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
@@ -383,11 +386,13 @@ PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, const PIByteArray &
|
||||
n.resize(crypto_secretbox_NONCEBYTES);
|
||||
ret.resize(crypt_data.size() - n.size() - crypto_secretbox_MACBYTES);
|
||||
memcpy(n.data(), crypt_data.data(crypt_data.size() - n.size()), n.size());
|
||||
if (crypto_box_open_easy(ret.data(), crypt_data.data(), crypt_data.size() - n.size(), n.data(), public_key.data(), secret_key.data()) != 0) {
|
||||
if (crypto_box_open_easy(ret.data(), crypt_data.data(), crypt_data.size() - n.size(), n.data(), public_key.data(), secret_key.data()) !=
|
||||
0) {
|
||||
if (ok) *ok = false;
|
||||
// piCout << "[PICrypt]" << "bad key_";
|
||||
return PIByteArray();
|
||||
} else if (ok) *ok = true;
|
||||
} else if (ok)
|
||||
*ok = true;
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
#endif
|
||||
@@ -397,16 +402,24 @@ PIByteArray PICrypt::decrypt(const PIByteArray & crypt_data, const PIByteArray &
|
||||
|
||||
PIByteArray PICrypt::passwordHash(const PIString & password, const PIByteArray & seed) {
|
||||
#ifdef crypto_pwhash_ALG_ARGON2I13
|
||||
// char out[crypto_pwhash_STRBYTES];
|
||||
// char out[crypto_pwhash_STRBYTES];
|
||||
PIByteArray pass = password.toUTF8();
|
||||
PIByteArray n = hash(seed);
|
||||
PIByteArray ph;
|
||||
ph.resize(crypto_box_SEEDBYTES);
|
||||
n.resize(crypto_pwhash_SALTBYTES);
|
||||
// randombytes_buf(n.data(), n.size());
|
||||
// crypto_shorthash(n.data(), seed.data(), seed.size(), PIByteArray(crypto_shorthash_KEYBYTES).data());
|
||||
int r = crypto_pwhash(ph.data(), ph.size(), (const char*)pass.data(), pass.size(), n.data(), crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate(), crypto_pwhash_ALG_ARGON2I13);
|
||||
//crypto_pwhash_str(out, (const char*)pass.data(), pass.size(), crypto_pwhash_argon2i_opslimit_moderate(), crypto_pwhash_argon2i_memlimit_moderate());
|
||||
// randombytes_buf(n.data(), n.size());
|
||||
// crypto_shorthash(n.data(), seed.data(), seed.size(), PIByteArray(crypto_shorthash_KEYBYTES).data());
|
||||
int r = crypto_pwhash(ph.data(),
|
||||
ph.size(),
|
||||
(const char *)pass.data(),
|
||||
pass.size(),
|
||||
n.data(),
|
||||
crypto_pwhash_argon2i_opslimit_moderate(),
|
||||
crypto_pwhash_argon2i_memlimit_moderate(),
|
||||
crypto_pwhash_ALG_ARGON2I13);
|
||||
// crypto_pwhash_str(out, (const char*)pass.data(), pass.size(), crypto_pwhash_argon2i_opslimit_moderate(),
|
||||
// crypto_pwhash_argon2i_memlimit_moderate());
|
||||
pass.fill(0);
|
||||
if (r != 0) return PIByteArray();
|
||||
return ph;
|
||||
@@ -432,17 +445,13 @@ bool PICrypt::init() {
|
||||
#ifdef PIP_CRYPT
|
||||
static bool inited = false;
|
||||
if (inited) return true;
|
||||
//piCout << "[PICrypt]" << "init ...";
|
||||
// piCout << "[PICrypt]" << "init ...";
|
||||
inited = sodium_init();
|
||||
if (!inited)
|
||||
inited = sodium_init();
|
||||
//piCout << "[PICrypt]" << "init" << inited;
|
||||
if (!inited) inited = sodium_init();
|
||||
// piCout << "[PICrypt]" << "init" << inited;
|
||||
return inited;
|
||||
#else
|
||||
PICRYPT_DISABLED_WARNING
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -18,16 +18,30 @@
|
||||
*/
|
||||
|
||||
#include "pifft.h"
|
||||
|
||||
#include "pifft_p.h"
|
||||
|
||||
|
||||
#define _PIFFTW_CPP(type) \
|
||||
_PIFFTW_P_##type##_::_PIFFTW_P_##type##_() {impl = new PIFFTW_Private<type>();;} \
|
||||
_PIFFTW_P_##type##_::~_PIFFTW_P_##type##_() {delete (PIFFTW_Private<type>*)impl;} \
|
||||
const PIVector<complex<type> > & _PIFFTW_P_##type##_::calcFFT(const PIVector<complex<type> > & in) {return ((PIFFTW_Private<type>*)impl)->calcFFT(in);} \
|
||||
const PIVector<complex<type> > & _PIFFTW_P_##type##_::calcFFTR(const PIVector<type> & in) {return ((PIFFTW_Private<type>*)impl)->calcFFT(in);} \
|
||||
const PIVector<complex<type> > & _PIFFTW_P_##type##_::calcFFTI(const PIVector<complex<type> > & in) {return ((PIFFTW_Private<type>*)impl)->calcFFTinverse(in);} \
|
||||
void _PIFFTW_P_##type##_::preparePlan(int size, int op) {return ((PIFFTW_Private<type>*)impl)->preparePlan(size, op);}
|
||||
_PIFFTW_P_##type##_::_PIFFTW_P_##type##_() { \
|
||||
impl = new PIFFTW_Private<type>(); \
|
||||
; \
|
||||
} \
|
||||
_PIFFTW_P_##type##_::~_PIFFTW_P_##type##_() { \
|
||||
delete (PIFFTW_Private<type> *)impl; \
|
||||
} \
|
||||
const PIVector<complex<type>> & _PIFFTW_P_##type##_::calcFFT(const PIVector<complex<type>> & in) { \
|
||||
return ((PIFFTW_Private<type> *)impl)->calcFFT(in); \
|
||||
} \
|
||||
const PIVector<complex<type>> & _PIFFTW_P_##type##_::calcFFTR(const PIVector<type> & in) { \
|
||||
return ((PIFFTW_Private<type> *)impl)->calcFFT(in); \
|
||||
} \
|
||||
const PIVector<complex<type>> & _PIFFTW_P_##type##_::calcFFTI(const PIVector<complex<type>> & in) { \
|
||||
return ((PIFFTW_Private<type> *)impl)->calcFFTinverse(in); \
|
||||
} \
|
||||
void _PIFFTW_P_##type##_::preparePlan(int size, int op) { \
|
||||
return ((PIFFTW_Private<type> *)impl)->preparePlan(size, op); \
|
||||
}
|
||||
|
||||
_PIFFTW_CPP(float)
|
||||
_PIFFTW_CPP(double)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
/*! \file pifft_p.h
|
||||
* \brief Class for FFT, IFFT and Hilbert transformations
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Private header for fftw3
|
||||
@@ -23,8 +23,8 @@
|
||||
#ifndef PIFFT_P_H
|
||||
#define PIFFT_P_H
|
||||
|
||||
#include "pivector.h"
|
||||
#include "picout.h"
|
||||
#include "pivector.h"
|
||||
#if defined(PIP_FFTW) || defined(PIP_FFTWf) || defined(PIP_FFTWl) || defined(PIP_FFTWq)
|
||||
# include "fftw3.h"
|
||||
#else
|
||||
@@ -35,43 +35,42 @@
|
||||
#endif
|
||||
|
||||
|
||||
template <typename T>
|
||||
class PIFFTW_Private
|
||||
{
|
||||
template<typename T>
|
||||
class PIFFTW_Private {
|
||||
public:
|
||||
explicit PIFFTW_Private() {
|
||||
plan = 0;
|
||||
//#ifndef PIP_FFTW
|
||||
// piCout << "[PIFFTW]" << "Warning: PIFFTW is disabled, to enable install libfftw3-dev library and build pip with -DFFTW=1";
|
||||
//#endif
|
||||
// #ifndef PIP_FFTW
|
||||
// piCout << "[PIFFTW]" << "Warning: PIFFTW is disabled, to enable install libfftw3-dev library and build pip with -DFFTW=1";
|
||||
// #endif
|
||||
p_makeThreadSafe();
|
||||
}
|
||||
~PIFFTW_Private() {p_destroyPlan(plan);}
|
||||
~PIFFTW_Private() { p_destroyPlan(plan); }
|
||||
|
||||
const PIVector<complex<T> > & calcFFT(const PIVector<complex<T> > & in) {
|
||||
const PIVector<complex<T>> & calcFFT(const PIVector<complex<T>> & in) {
|
||||
if (prepare != PlanParams(in.size(), fo_complex)) {
|
||||
p_out.resize(in.size());
|
||||
//piCout << "[PIFFTW]" << "creating plan";
|
||||
// piCout << "[PIFFTW]" << "creating plan";
|
||||
p_createPlan_c2c_1d(plan, in.size(), in.data(), p_out.data(), FFTW_FORWARD, FFTW_ESTIMATE | FFTW_UNALIGNED);
|
||||
prepare = PlanParams(in.size(), fo_complex);
|
||||
}
|
||||
p_executePlan_c2c(plan, in.data(), p_out.data());
|
||||
return p_out;
|
||||
}
|
||||
const PIVector<complex<T> > & calcFFT(const PIVector<T> & in) {
|
||||
const PIVector<complex<T>> & calcFFT(const PIVector<T> & in) {
|
||||
if (prepare != PlanParams(in.size(), fo_real)) {
|
||||
p_out.resize(in.size());
|
||||
//piCout << "[PIFFTW]" << "creating plan";
|
||||
// piCout << "[PIFFTW]" << "creating plan";
|
||||
p_createPlan_r2c_1d(plan, in.size(), in.data(), p_out.data(), FFTW_ESTIMATE | FFTW_UNALIGNED);
|
||||
prepare = PlanParams(in.size(), fo_real);
|
||||
}
|
||||
p_executePlan_r2c(plan, in.data(), p_out.data());
|
||||
return p_out;
|
||||
}
|
||||
const PIVector<complex<T> > & calcFFTinverse(const PIVector<complex<T> > & in) {
|
||||
const PIVector<complex<T>> & calcFFTinverse(const PIVector<complex<T>> & in) {
|
||||
if (prepare != PlanParams(in.size(), fo_inverse)) {
|
||||
p_out.resize(in.size());
|
||||
//piCout << "[PIFFTW]" << "creating plan";
|
||||
// piCout << "[PIFFTW]" << "creating plan";
|
||||
p_createPlan_c2c_1d(plan, in.size(), in.data(), p_out.data(), FFTW_BACKWARD, FFTW_ESTIMATE | FFTW_UNALIGNED);
|
||||
prepare = PlanParams(in.size(), fo_inverse);
|
||||
}
|
||||
@@ -79,7 +78,11 @@ public:
|
||||
return p_out;
|
||||
}
|
||||
|
||||
enum FFT_Operation {fo_real, fo_complex, fo_inverse};
|
||||
enum FFT_Operation {
|
||||
fo_real,
|
||||
fo_complex,
|
||||
fo_inverse
|
||||
};
|
||||
|
||||
void preparePlan(int size, int op) {
|
||||
p_inr.clear();
|
||||
@@ -101,9 +104,7 @@ public:
|
||||
p_out.resize(size);
|
||||
p_createPlan_c2c_1d(plan, size, p_in.data(), p_out.data(), FFTW_BACKWARD, FFTW_MEASURE | FFTW_UNALIGNED);
|
||||
break;
|
||||
default:
|
||||
size = 0;
|
||||
break;
|
||||
default: size = 0; break;
|
||||
}
|
||||
prepare = PlanParams(size, (FFT_Operation)op);
|
||||
}
|
||||
@@ -117,62 +118,128 @@ public:
|
||||
inline void p_makeThreadSafe() {}
|
||||
|
||||
struct PlanParams {
|
||||
PlanParams() {size = 0; op = fo_complex;}
|
||||
PlanParams(int size_, FFT_Operation op_) {size = size_; op = op_;}
|
||||
bool isValid() {return size > 0;}
|
||||
bool operator ==(const PlanParams & v) const {return (v.size == size) && (v.op == op);}
|
||||
bool operator !=(const PlanParams & v) const {return !(*this == v);}
|
||||
PlanParams() {
|
||||
size = 0;
|
||||
op = fo_complex;
|
||||
}
|
||||
PlanParams(int size_, FFT_Operation op_) {
|
||||
size = size_;
|
||||
op = op_;
|
||||
}
|
||||
bool isValid() { return size > 0; }
|
||||
bool operator==(const PlanParams & v) const { return (v.size == size) && (v.op == op); }
|
||||
bool operator!=(const PlanParams & v) const { return !(*this == v); }
|
||||
int size;
|
||||
FFT_Operation op;
|
||||
};
|
||||
|
||||
PIVector<complex<T> > p_in;
|
||||
PIVector<complex<T>> p_in;
|
||||
PIVector<T> p_inr;
|
||||
PIVector<complex<T> > p_out;
|
||||
PIVector<complex<T>> p_out;
|
||||
void * plan;
|
||||
PlanParams prepare;
|
||||
};
|
||||
|
||||
|
||||
#ifdef PIP_FFTWf
|
||||
template<> inline void PIFFTW_Private<float>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftwf_plan_dft_1d(size, (fftwf_complex *)in, (fftwf_complex *)out, dir, flags);}
|
||||
template<> inline void PIFFTW_Private<float>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftwf_plan_dft_r2c_1d(size, (float *)in, (fftwf_complex *)out, flags);}
|
||||
template<> inline void PIFFTW_Private<float>::p_executePlan(void * plan) {fftwf_execute((fftwf_plan)plan);}
|
||||
template<> inline void PIFFTW_Private<float>::p_executePlan_c2c(void * plan, const void * in, void * out) {fftwf_execute_dft((fftwf_plan)plan, (fftwf_complex *)in, (fftwf_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<float>::p_executePlan_r2c(void * plan, const void * in, void * out) {fftwf_execute_dft_r2c((fftwf_plan)plan, (float *)in, (fftwf_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<float>::p_destroyPlan(void *& plan) {if (plan) fftwf_destroy_plan((fftwf_plan)plan); plan = 0;}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftwf_plan_dft_1d(size, (fftwf_complex *)in, (fftwf_complex *)out, dir, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftwf_plan_dft_r2c_1d(size, (float *)in, (fftwf_complex *)out, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_executePlan(void * plan) {
|
||||
fftwf_execute((fftwf_plan)plan);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_executePlan_c2c(void * plan, const void * in, void * out) {
|
||||
fftwf_execute_dft((fftwf_plan)plan, (fftwf_complex *)in, (fftwf_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_executePlan_r2c(void * plan, const void * in, void * out) {
|
||||
fftwf_execute_dft_r2c((fftwf_plan)plan, (float *)in, (fftwf_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_destroyPlan(void *& plan) {
|
||||
if (plan) fftwf_destroy_plan((fftwf_plan)plan);
|
||||
plan = 0;
|
||||
}
|
||||
# ifdef PIP_FFTWf_THREADSAFE
|
||||
template<> inline void PIFFTW_Private<float>::p_makeThreadSafe() {fftwf_make_planner_thread_safe();}
|
||||
template<>
|
||||
inline void PIFFTW_Private<float>::p_makeThreadSafe() {
|
||||
fftwf_make_planner_thread_safe();
|
||||
}
|
||||
# endif
|
||||
#endif // PIP_FFTWf
|
||||
|
||||
#ifdef PIP_FFTW
|
||||
template<> inline void PIFFTW_Private<double>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftw_plan_dft_1d(size, (fftw_complex *)in, (fftw_complex *)out, dir, flags);}
|
||||
template<> inline void PIFFTW_Private<double>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftw_plan_dft_r2c_1d(size, (double *)in, (fftw_complex *)out, flags);}
|
||||
template<> inline void PIFFTW_Private<double>::p_executePlan(void * plan) {fftw_execute((fftw_plan)plan);}
|
||||
template<> inline void PIFFTW_Private<double>::p_executePlan_c2c(void * plan, const void * in, void * out) {fftw_execute_dft((fftw_plan)plan, (fftw_complex *)in, (fftw_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<double>::p_executePlan_r2c(void * plan, const void * in, void * out) {fftw_execute_dft_r2c((fftw_plan)plan, (double *)in, (fftw_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<double>::p_destroyPlan(void *& plan) {if (plan) fftw_destroy_plan((fftw_plan)plan); plan = 0;}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftw_plan_dft_1d(size, (fftw_complex *)in, (fftw_complex *)out, dir, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftw_plan_dft_r2c_1d(size, (double *)in, (fftw_complex *)out, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_executePlan(void * plan) {
|
||||
fftw_execute((fftw_plan)plan);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_executePlan_c2c(void * plan, const void * in, void * out) {
|
||||
fftw_execute_dft((fftw_plan)plan, (fftw_complex *)in, (fftw_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_executePlan_r2c(void * plan, const void * in, void * out) {
|
||||
fftw_execute_dft_r2c((fftw_plan)plan, (double *)in, (fftw_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_destroyPlan(void *& plan) {
|
||||
if (plan) fftw_destroy_plan((fftw_plan)plan);
|
||||
plan = 0;
|
||||
}
|
||||
# ifdef PIP_FFTW_THREADSAFE
|
||||
template<> inline void PIFFTW_Private<double>::p_makeThreadSafe() {fftw_make_planner_thread_safe();}
|
||||
template<>
|
||||
inline void PIFFTW_Private<double>::p_makeThreadSafe() {
|
||||
fftw_make_planner_thread_safe();
|
||||
}
|
||||
# endif
|
||||
#endif // PIP_FFTW
|
||||
|
||||
#ifdef PIP_FFTWl
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftwl_plan_dft_1d(size, (fftwl_complex *)in, (fftwl_complex *)out, dir, flags);}
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftwl_plan_dft_r2c_1d(size, (ldouble *)in, (fftwl_complex *)out, flags);}
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_executePlan(void * plan) {fftwl_execute((fftwl_plan)plan);}
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_executePlan_c2c(void * plan, const void * in, void * out) {fftwl_execute_dft((fftwl_plan)plan, (fftwl_complex *)in, (fftwl_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_executePlan_r2c(void * plan, const void * in, void * out) {fftwl_execute_dft_r2c((fftwl_plan)plan, (ldouble *)in, (fftwl_complex *)out);}
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_destroyPlan(void *& plan) {if (plan) fftwl_destroy_plan((fftwl_plan)plan); plan = 0;}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_createPlan_c2c_1d(void *& plan, int size, const void * in, void * out, int dir, int flags) {
|
||||
plan = fftwl_plan_dft_1d(size, (fftwl_complex *)in, (fftwl_complex *)out, dir, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_createPlan_r2c_1d(void *& plan, int size, const void * in, void * out, int flags) {
|
||||
plan = fftwl_plan_dft_r2c_1d(size, (ldouble *)in, (fftwl_complex *)out, flags);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_executePlan(void * plan) {
|
||||
fftwl_execute((fftwl_plan)plan);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_executePlan_c2c(void * plan, const void * in, void * out) {
|
||||
fftwl_execute_dft((fftwl_plan)plan, (fftwl_complex *)in, (fftwl_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_executePlan_r2c(void * plan, const void * in, void * out) {
|
||||
fftwl_execute_dft_r2c((fftwl_plan)plan, (ldouble *)in, (fftwl_complex *)out);
|
||||
}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_destroyPlan(void *& plan) {
|
||||
if (plan) fftwl_destroy_plan((fftwl_plan)plan);
|
||||
plan = 0;
|
||||
}
|
||||
# ifdef PIP_FFTWl_THREADSAFE
|
||||
template<> inline void PIFFTW_Private<ldouble>::p_makeThreadSafe() {fftwl_make_planner_thread_safe();}
|
||||
template<>
|
||||
inline void PIFFTW_Private<ldouble>::p_makeThreadSafe() {
|
||||
fftwl_make_planner_thread_safe();
|
||||
}
|
||||
# endif
|
||||
#endif // PIP_FFTWl
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@
|
||||
* current \a PIEthernet::allAddresses() was changed and call
|
||||
* \a reinit() if it necessary.
|
||||
*
|
||||
*/
|
||||
*/
|
||||
|
||||
#define MULTICAST_TTL 4
|
||||
|
||||
@@ -113,7 +113,7 @@ void PIBroadcast::setLoopbackPortsCount(int count) {
|
||||
|
||||
|
||||
void PIBroadcast::destroyAll() {
|
||||
piForeach (PIEthernet * e, eth_mcast) {
|
||||
piForeach(PIEthernet * e, eth_mcast) {
|
||||
e->stopThreadedRead();
|
||||
delete e;
|
||||
}
|
||||
@@ -135,9 +135,9 @@ void PIBroadcast::initAll(PIVector<PIEthernet::Address> al) {
|
||||
al << mcast_address;
|
||||
eth_mcast.clear();
|
||||
PIEthernet::InterfaceList ifaces = PIEthernet::interfaces();
|
||||
piForeachC (PIEthernet::Address & a, al) {
|
||||
piForeachC(PIEthernet::Address & a, al) {
|
||||
PIEthernet * ce = 0;
|
||||
//piCout << "mcast try" << a;
|
||||
// piCout << "mcast try" << a;
|
||||
if (_channels[Multicast]) {
|
||||
ce = new PIEthernet();
|
||||
ce->setDebug(false);
|
||||
@@ -148,7 +148,7 @@ void PIBroadcast::initAll(PIVector<PIEthernet::Address> al) {
|
||||
if (!_send_only) {
|
||||
ce->setReadAddress(a.ipString(), mcast_address.port());
|
||||
ce->joinMulticastGroup(mcast_address.ipString());
|
||||
//piCout << "mcast " << ce->readAddress() << ce->sendAddress();
|
||||
// piCout << "mcast " << ce->readAddress() << ce->sendAddress();
|
||||
if (ce->open()) {
|
||||
eth_mcast << ce;
|
||||
CONNECT2(void, const uchar *, ssize_t, ce, threadedReadEvent, this, mcastRead);
|
||||
@@ -170,7 +170,7 @@ void PIBroadcast::initAll(PIVector<PIEthernet::Address> al) {
|
||||
ce->setSendAddress(PIEthernet::getBroadcast(a, nm).ipString(), bcast_port);
|
||||
if (!_send_only) {
|
||||
ce->setReadAddress(PIEthernet::Address(a.ip(), bcast_port));
|
||||
//piCout << "bcast " << ce->readAddress() << ce->sendAddress();
|
||||
// piCout << "bcast " << ce->readAddress() << ce->sendAddress();
|
||||
if (ce->open()) {
|
||||
eth_mcast << ce;
|
||||
CONNECT2(void, const uchar *, ssize_t, ce, threadedReadEvent, this, mcastRead);
|
||||
@@ -193,7 +193,7 @@ void PIBroadcast::initAll(PIVector<PIEthernet::Address> al) {
|
||||
for (int i = 0; i < lo_pcnt; ++i) {
|
||||
eth_lo->setReadAddress("127.0.0.1", lo_port + i);
|
||||
if (eth_lo->open()) {
|
||||
//piCout << "bind local to" << (lo_port + i);
|
||||
// piCout << "bind local to" << (lo_port + i);
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -210,7 +210,8 @@ void PIBroadcast::send(const PIByteArray & data) {
|
||||
PIByteArray cd = cryptData(data);
|
||||
if (cd.isEmpty()) return;
|
||||
PIMutexLocker ml(mcast_mutex);
|
||||
piForeach (PIEthernet * e, eth_mcast) e->send(cd);
|
||||
piForeach(PIEthernet * e, eth_mcast)
|
||||
e->send(cd);
|
||||
if (eth_lo) {
|
||||
for (int i = 0; i < lo_pcnt; ++i) {
|
||||
eth_lo->send("127.0.0.1", lo_port + i, cd);
|
||||
@@ -227,7 +228,8 @@ void PIBroadcast::startRead() {
|
||||
}
|
||||
if (_send_only) return;
|
||||
PIMutexLocker ml(mcast_mutex);
|
||||
piForeach (PIEthernet * e, eth_mcast) e->startThreadedRead();
|
||||
piForeach(PIEthernet * e, eth_mcast)
|
||||
e->startThreadedRead();
|
||||
if (eth_lo) eth_lo->startThreadedRead();
|
||||
_started = true;
|
||||
}
|
||||
@@ -236,7 +238,8 @@ void PIBroadcast::startRead() {
|
||||
void PIBroadcast::stopRead() {
|
||||
if (isRunning()) stop();
|
||||
PIMutexLocker ml(mcast_mutex);
|
||||
piForeach (PIEthernet * e, eth_mcast) e->stopThreadedRead();
|
||||
piForeach(PIEthernet * e, eth_mcast)
|
||||
e->stopThreadedRead();
|
||||
if (eth_lo) eth_lo->stopThreadedRead();
|
||||
_started = false;
|
||||
}
|
||||
|
||||
@@ -43,7 +43,7 @@
|
||||
* You can use this class as base for your own classes. Use \a cryptData()
|
||||
* and \a decryptData() when send and receive your data.
|
||||
*
|
||||
*/
|
||||
*/
|
||||
|
||||
|
||||
PIEthUtilBase::PIEthUtilBase() {
|
||||
@@ -51,8 +51,7 @@ PIEthUtilBase::PIEthUtilBase() {
|
||||
}
|
||||
|
||||
|
||||
PIEthUtilBase::~PIEthUtilBase() {
|
||||
}
|
||||
PIEthUtilBase::~PIEthUtilBase() {}
|
||||
|
||||
|
||||
void PIEthUtilBase::setCryptEnabled(bool on) {
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
# pragma GCC diagnostic ignored "-Wnonnull"
|
||||
#endif
|
||||
#include "pistreampacker.h"
|
||||
|
||||
#include "piiodevice.h"
|
||||
#ifdef __GNUC__
|
||||
# pragma GCC diagnostic pop
|
||||
@@ -43,7 +44,7 @@
|
||||
*
|
||||
* Use \a assignDevice() to connect device to this %PIStreamPacker.
|
||||
*
|
||||
*/
|
||||
*/
|
||||
|
||||
|
||||
PIStreamPacker::PIStreamPacker(PIIODevice * dev): PIObject() {
|
||||
@@ -51,7 +52,7 @@ PIStreamPacker::PIStreamPacker(PIIODevice * dev): PIObject() {
|
||||
aggressive_optimization = true;
|
||||
packet_size = -1;
|
||||
size_crypted_size = sizeof(int);
|
||||
crypt_frag_size = 1024*1024;
|
||||
crypt_frag_size = 1024 * 1024;
|
||||
max_packet_size = 1400;
|
||||
packet_sign = 0xAFBE;
|
||||
assignDevice(dev);
|
||||
@@ -61,7 +62,8 @@ PIStreamPacker::PIStreamPacker(PIIODevice * dev): PIObject() {
|
||||
void PIStreamPacker::setCryptSizeEnabled(bool on) {
|
||||
crypt_size = on;
|
||||
if (crypt_size) {
|
||||
PIByteArray ba; ba << int(0);
|
||||
PIByteArray ba;
|
||||
ba << int(0);
|
||||
size_crypted_size = cryptData(ba).size_s();
|
||||
} else
|
||||
size_crypted_size = sizeof(int);
|
||||
@@ -80,31 +82,36 @@ void PIStreamPacker::send(const PIByteArray & data) {
|
||||
PIByteArray cd;
|
||||
if (crypt_frag) {
|
||||
int fcnt = (data.size_s() - 1) / crypt_frag_size + 1, fst = 0;
|
||||
//piCout << "crypt_frag send" << fcnt << "frags";
|
||||
// piCout << "crypt_frag send" << fcnt << "frags";
|
||||
PIByteArray frag;
|
||||
for (int i = 0; i < fcnt; ++i) {
|
||||
if (i == fcnt - 1) frag = PIByteArray(data.data(fst), data.size_s() - fst);
|
||||
else frag = PIByteArray(data.data(fst), crypt_frag_size);
|
||||
if (i == fcnt - 1)
|
||||
frag = PIByteArray(data.data(fst), data.size_s() - fst);
|
||||
else
|
||||
frag = PIByteArray(data.data(fst), crypt_frag_size);
|
||||
fst += crypt_frag_size;
|
||||
cd << cryptData(frag);
|
||||
}
|
||||
} else {
|
||||
cd = cryptData(data);
|
||||
}
|
||||
//piCout << "crypt" << data.size() << "->" << cd.size() << key().size();
|
||||
// piCout << "crypt" << data.size() << "->" << cd.size() << key().size();
|
||||
PIByteArray hdr, part;
|
||||
hdr << packet_sign;
|
||||
if (crypt_size) {
|
||||
PIByteArray crsz; crsz << int(cd.size_s());
|
||||
PIByteArray crsz;
|
||||
crsz << int(cd.size_s());
|
||||
hdr.append(cryptData(crsz));
|
||||
} else
|
||||
hdr << int(cd.size_s());
|
||||
cd.insert(0, hdr);
|
||||
int pcnt = (cd.size_s() - 1) / max_packet_size + 1, pst = 0;
|
||||
for (int i = 0; i < pcnt; ++i) {
|
||||
if (i == pcnt - 1) part = PIByteArray(cd.data(pst), cd.size_s() - pst);
|
||||
else part = PIByteArray(cd.data(pst), max_packet_size);
|
||||
//piCout << "send" << part.size();
|
||||
if (i == pcnt - 1)
|
||||
part = PIByteArray(cd.data(pst), cd.size_s() - pst);
|
||||
else
|
||||
part = PIByteArray(cd.data(pst), max_packet_size);
|
||||
// piCout << "send" << part.size();
|
||||
sendRequest(part);
|
||||
pst += max_packet_size;
|
||||
}
|
||||
@@ -118,7 +125,7 @@ void PIStreamPacker::received(const uchar * readed, ssize_t size) {
|
||||
|
||||
void PIStreamPacker::received(const PIByteArray & data) {
|
||||
stream.append(data);
|
||||
//piCout << "rec" << data.size();
|
||||
// piCout << "rec" << data.size();
|
||||
while (!stream.isEmpty()) {
|
||||
int hdr_size = sizeof(packet_sign) + size_crypted_size;
|
||||
if (packet_size < 0) {
|
||||
@@ -126,8 +133,10 @@ void PIStreamPacker::received(const PIByteArray & data) {
|
||||
ushort sign(0);
|
||||
memcpy(&sign, stream.data(), 2);
|
||||
if (sign != packet_sign) {
|
||||
if (aggressive_optimization) stream.clear();
|
||||
else stream.pop_front();
|
||||
if (aggressive_optimization)
|
||||
stream.clear();
|
||||
else
|
||||
stream.pop_front();
|
||||
continue;
|
||||
}
|
||||
int sz = -1;
|
||||
@@ -136,8 +145,10 @@ void PIStreamPacker::received(const PIByteArray & data) {
|
||||
memcpy(crsz.data(), stream.data(2), size_crypted_size);
|
||||
crsz = decryptData(crsz);
|
||||
if (crsz.size() < sizeof(sz)) {
|
||||
if (aggressive_optimization) stream.clear();
|
||||
else stream.pop_front();
|
||||
if (aggressive_optimization)
|
||||
stream.clear();
|
||||
else
|
||||
stream.pop_front();
|
||||
continue;
|
||||
}
|
||||
crsz >> sz;
|
||||
@@ -145,15 +156,16 @@ void PIStreamPacker::received(const PIByteArray & data) {
|
||||
memcpy(&sz, stream.data(2), size_crypted_size);
|
||||
}
|
||||
if (sz < 0) {
|
||||
if (aggressive_optimization) stream.clear();
|
||||
else stream.pop_front();
|
||||
if (aggressive_optimization)
|
||||
stream.clear();
|
||||
else
|
||||
stream.pop_front();
|
||||
continue;
|
||||
}
|
||||
stream.remove(0, hdr_size);
|
||||
packet.clear();
|
||||
packet_size = sz;
|
||||
if (packet_size == 0)
|
||||
packet_size = -1;
|
||||
if (packet_size == 0) packet_size = -1;
|
||||
continue;
|
||||
} else {
|
||||
int ps = piMini(stream.size_s(), packet_size - packet.size_s());
|
||||
@@ -162,25 +174,25 @@ void PIStreamPacker::received(const PIByteArray & data) {
|
||||
if (packet.size_s() == packet_size) {
|
||||
PIByteArray cd;
|
||||
if (crypt_frag) {
|
||||
//piCout << "decrypt frags ..." << packet_size;
|
||||
// piCout << "decrypt frags ..." << packet_size;
|
||||
while (packet.size_s() >= 4) {
|
||||
//piCout << "decrypt frags take data ...";
|
||||
// piCout << "decrypt frags take data ...";
|
||||
PIByteArray frag;
|
||||
//piCout << "decrypt frags take data done" << frag.size_s();
|
||||
// piCout << "decrypt frags take data done" << frag.size_s();
|
||||
packet >> frag;
|
||||
if (frag.isEmpty()) {
|
||||
//piCout << "decrypt frags corrupt, break";
|
||||
// piCout << "decrypt frags corrupt, break";
|
||||
cd.clear();
|
||||
break;
|
||||
}
|
||||
cd.append(decryptData(frag));
|
||||
//piCout << "decrypt frags add" << frag.size_s();
|
||||
// piCout << "decrypt frags add" << frag.size_s();
|
||||
}
|
||||
//piCout << "decrypt frags done" << cd.size();
|
||||
// piCout << "decrypt frags done" << cd.size();
|
||||
} else {
|
||||
cd = decryptData(packet);
|
||||
}
|
||||
//piCout << "decrypt" << packet.size() << "->" << cd.size() << key().size();
|
||||
// piCout << "decrypt" << packet.size() << "->" << cd.size() << key().size();
|
||||
if (!cd.isEmpty()) {
|
||||
packetReceived(cd);
|
||||
packetReceiveEvent(cd);
|
||||
|
||||
@@ -50,4 +50,3 @@ luabridge::LuaRef PILuaProgram::getGlobal(const PIString & name) {
|
||||
luabridge::Namespace PILuaProgram::getGlobalNamespace() {
|
||||
return luabridge::getGlobalNamespace(PRIVATE->lua_state);
|
||||
}
|
||||
|
||||
|
||||
@@ -31,8 +31,7 @@
|
||||
#include "pistreampacker.h"
|
||||
|
||||
|
||||
class PIP_CLOUD_EXPORT PICloudBase
|
||||
{
|
||||
class PIP_CLOUD_EXPORT PICloudBase {
|
||||
public:
|
||||
PICloudBase();
|
||||
|
||||
|
||||
@@ -32,17 +32,19 @@
|
||||
|
||||
//! \brief PICloudClient
|
||||
|
||||
class PIP_CLOUD_EXPORT PICloudClient: public PIIODevice, public PICloudBase
|
||||
{
|
||||
class PIP_CLOUD_EXPORT PICloudClient
|
||||
: public PIIODevice
|
||||
, public PICloudBase {
|
||||
PIIODEVICE(PICloudClient, "");
|
||||
|
||||
public:
|
||||
explicit PICloudClient(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
virtual ~PICloudClient();
|
||||
|
||||
void setServerName(const PIString & server_name);
|
||||
void setKeepConnection(bool on);
|
||||
bool isConnected() const {return is_connected;}
|
||||
ssize_t bytesAvailable() const override {return buff.size();}
|
||||
bool isConnected() const { return is_connected; }
|
||||
ssize_t bytesAvailable() const override { return buff.size(); }
|
||||
void interrupt() override;
|
||||
|
||||
EVENT(connected);
|
||||
@@ -53,7 +55,7 @@ protected:
|
||||
bool closeDevice() override;
|
||||
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
||||
ssize_t writeDevice(const void * data, ssize_t size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Reliable;}
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
EVENT_HANDLER1(void, _readed, PIByteArray &, data);
|
||||
@@ -66,7 +68,6 @@ private:
|
||||
PIConditionVariable cond_connect;
|
||||
std::atomic_bool is_connected;
|
||||
std::atomic_bool is_deleted;
|
||||
|
||||
};
|
||||
|
||||
#endif // PICLOUDCLIENT_H
|
||||
|
||||
@@ -51,8 +51,8 @@
|
||||
#ifndef PICLOUDMODULE_H
|
||||
#define PICLOUDMODULE_H
|
||||
|
||||
#include "picloudtcp.h"
|
||||
#include "picloudclient.h"
|
||||
#include "picloudserver.h"
|
||||
#include "picloudtcp.h"
|
||||
|
||||
#endif // PICLOUDMODULE_H
|
||||
|
||||
@@ -30,27 +30,31 @@
|
||||
#include "piconditionvar.h"
|
||||
|
||||
|
||||
class PIP_CLOUD_EXPORT PICloudServer: public PIIODevice, public PICloudBase
|
||||
{
|
||||
class PIP_CLOUD_EXPORT PICloudServer
|
||||
: public PIIODevice
|
||||
, public PICloudBase {
|
||||
PIIODEVICE(PICloudServer, "");
|
||||
|
||||
public:
|
||||
//! PICloudServer
|
||||
explicit PICloudServer(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
virtual ~PICloudServer();
|
||||
|
||||
class Client : public PIIODevice {
|
||||
class Client: public PIIODevice {
|
||||
PIIODEVICE(PICloudServer::Client, "");
|
||||
friend class PICloudServer;
|
||||
|
||||
public:
|
||||
Client(PICloudServer * srv = nullptr, uint id = 0);
|
||||
virtual ~Client();
|
||||
|
||||
protected:
|
||||
bool openDevice() override;
|
||||
bool closeDevice() override;
|
||||
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
||||
ssize_t writeDevice(const void * data, ssize_t size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Reliable;}
|
||||
ssize_t bytesAvailable() const override {return buff.size();}
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
ssize_t bytesAvailable() const override { return buff.size(); }
|
||||
void interrupt() override;
|
||||
|
||||
private:
|
||||
@@ -67,7 +71,7 @@ public:
|
||||
|
||||
PIVector<PICloudServer::Client *> clients() const;
|
||||
|
||||
EVENT1(newConnection, PICloudServer::Client * , client);
|
||||
EVENT1(newConnection, PICloudServer::Client *, client);
|
||||
|
||||
protected:
|
||||
bool openDevice() override;
|
||||
|
||||
@@ -26,9 +26,9 @@
|
||||
#ifndef PICLOUDTCP_H
|
||||
#define PICLOUDTCP_H
|
||||
|
||||
#include "pimutex.h"
|
||||
#include "pip_cloud_export.h"
|
||||
#include "pistring.h"
|
||||
#include "pimutex.h"
|
||||
|
||||
|
||||
class PIEthernet;
|
||||
@@ -37,7 +37,6 @@ class PIStreamPacker;
|
||||
namespace PICloud {
|
||||
|
||||
|
||||
|
||||
class PIP_CLOUD_EXPORT TCP {
|
||||
public:
|
||||
enum Version {
|
||||
@@ -61,7 +60,7 @@ public:
|
||||
|
||||
TCP(PIStreamPacker * s);
|
||||
void setRole(Role r);
|
||||
Role role() const {return (Role)header.role;}
|
||||
Role role() const { return (Role)header.role; }
|
||||
void setServerName(const PIString & server_name_);
|
||||
PIString serverName() const;
|
||||
|
||||
@@ -91,9 +90,8 @@ private:
|
||||
PIString server_name;
|
||||
PIStreamPacker * streampacker;
|
||||
PIMutex mutex_send;
|
||||
|
||||
};
|
||||
|
||||
}
|
||||
} // namespace PICloud
|
||||
|
||||
#endif // PICLOUDTCP_H
|
||||
|
||||
@@ -18,35 +18,35 @@
|
||||
*/
|
||||
|
||||
#include "picodeinfo.h"
|
||||
|
||||
#include "pivariant.h"
|
||||
|
||||
|
||||
PIString PICodeInfo::EnumInfo::memberName(int value_) const {
|
||||
piForeachC (PICodeInfo::EnumeratorInfo & e, members)
|
||||
if (e.value == value_)
|
||||
return e.name.toString();
|
||||
piForeachC(PICodeInfo::EnumeratorInfo & e, members)
|
||||
if (e.value == value_) return e.name.toString();
|
||||
return PIString();
|
||||
}
|
||||
|
||||
|
||||
int PICodeInfo::EnumInfo::memberValue(const PIString & name_) const {
|
||||
piForeachC (PICodeInfo::EnumeratorInfo & e, members)
|
||||
if (e.name.toString() == name_)
|
||||
return e.value;
|
||||
piForeachC(PICodeInfo::EnumeratorInfo & e, members)
|
||||
if (e.name.toString() == name_) return e.value;
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
PIVariantTypes::Enum PICodeInfo::EnumInfo::toPIVariantEnum() {
|
||||
PIVariantTypes::Enum en(name.toString());
|
||||
for (auto m: members) en << m.toPIVariantEnumerator();
|
||||
for (auto m: members)
|
||||
en << m.toPIVariantEnumerator();
|
||||
if (!en.isEmpty()) en.selectValue(members.front().value);
|
||||
return en;
|
||||
}
|
||||
|
||||
|
||||
PIMap<PIConstChars, PICodeInfo::ClassInfo * > * PICodeInfo::classesInfo;
|
||||
PIMap<PIConstChars, PICodeInfo::EnumInfo * > * PICodeInfo::enumsInfo;
|
||||
PIMap<PIConstChars, PICodeInfo::ClassInfo *> * PICodeInfo::classesInfo;
|
||||
PIMap<PIConstChars, PICodeInfo::EnumInfo *> * PICodeInfo::enumsInfo;
|
||||
PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * PICodeInfo::accessValueFunctions;
|
||||
PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * PICodeInfo::accessTypeFunctions;
|
||||
|
||||
|
||||
@@ -56,18 +56,23 @@ enum TypeFlag {
|
||||
|
||||
typedef PIFlags<PICodeInfo::TypeFlag> TypeFlags;
|
||||
typedef PIMap<PIString, PIString> MetaMap;
|
||||
typedef PIByteArray(*AccessValueFunction)(const void *, const char *);
|
||||
typedef const char*(*AccessTypeFunction)(const char *);
|
||||
typedef PIByteArray (*AccessValueFunction)(const void *, const char *);
|
||||
typedef const char * (*AccessTypeFunction)(const char *);
|
||||
|
||||
|
||||
//! \~english Type information
|
||||
//! \~russian Информация о типе
|
||||
struct PIP_EXPORT TypeInfo {
|
||||
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {name = n; type = t; flags = f; bits = b;}
|
||||
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {
|
||||
name = n;
|
||||
type = t;
|
||||
flags = f;
|
||||
bits = b;
|
||||
}
|
||||
|
||||
//! \~english Returns if variable if bitfield
|
||||
//! \~russian Возвращает битовым ли полем является переменная
|
||||
bool isBitfield() const {return bits > 0;}
|
||||
bool isBitfield() const { return bits > 0; }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
//! \~russian Произвольное содержимое PIMETA
|
||||
@@ -94,7 +99,6 @@ struct PIP_EXPORT TypeInfo {
|
||||
//! \~english Method information
|
||||
//! \~russian Информация о методе
|
||||
struct PIP_EXPORT FunctionInfo {
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
//! \~russian Произвольное содержимое PIMETA
|
||||
MetaMap meta;
|
||||
@@ -116,7 +120,7 @@ struct PIP_EXPORT FunctionInfo {
|
||||
//! \~english Class or struct information
|
||||
//! \~russian Информация о классе или структуре
|
||||
struct PIP_EXPORT ClassInfo {
|
||||
ClassInfo() {has_name = true;}
|
||||
ClassInfo() { has_name = true; }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
//! \~russian Произвольное содержимое PIMETA
|
||||
@@ -148,15 +152,18 @@ struct PIP_EXPORT ClassInfo {
|
||||
|
||||
//! \~english Subclass list
|
||||
//! \~russian Список наследников
|
||||
PIVector<PICodeInfo::ClassInfo * > children_info;
|
||||
PIVector<PICodeInfo::ClassInfo *> children_info;
|
||||
};
|
||||
|
||||
|
||||
//! \~english Enumerator information
|
||||
//! \~russian Информация об элементе перечисления
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {name = n; value = v;}
|
||||
PIVariantTypes::Enumerator toPIVariantEnumerator() {return PIVariantTypes::Enumerator(value, name.toString());}
|
||||
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {
|
||||
name = n;
|
||||
value = v;
|
||||
}
|
||||
PIVariantTypes::Enumerator toPIVariantEnumerator() { return PIVariantTypes::Enumerator(value, name.toString()); }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
//! \~russian Произвольное содержимое PIMETA
|
||||
@@ -175,7 +182,6 @@ struct PIP_EXPORT EnumeratorInfo {
|
||||
//! \~english Enum information
|
||||
//! \~russian Информация о перечислении
|
||||
struct PIP_EXPORT EnumInfo {
|
||||
|
||||
//! \~english Returns member name with value "value"
|
||||
//! \~russian Возвращает имя элемента со значением "value"
|
||||
PIString memberName(int value) const;
|
||||
@@ -202,7 +208,7 @@ struct PIP_EXPORT EnumInfo {
|
||||
};
|
||||
|
||||
|
||||
inline PICout operator <<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
if (v.flags[Inline]) s << "inline ";
|
||||
if (v.flags[Virtual]) s << "virtual ";
|
||||
if (v.flags[Mutable]) s << "mutable ";
|
||||
@@ -210,22 +216,26 @@ inline PICout operator <<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
if (v.flags[Static]) s << "static ";
|
||||
if (v.flags[Const]) s << "const ";
|
||||
s << v.type;
|
||||
if (!v.name.isEmpty())
|
||||
s << " " << v.name;
|
||||
if (!v.name.isEmpty()) s << " " << v.name;
|
||||
return s;
|
||||
}
|
||||
|
||||
inline PICout operator <<(PICout s, const PICodeInfo::EnumeratorInfo & v) {s << v.name << " = " << v.value << " Meta" << v.meta; return s;}
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumeratorInfo & v) {
|
||||
s << v.name << " = " << v.value << " Meta" << v.meta;
|
||||
return s;
|
||||
}
|
||||
|
||||
inline PICout operator <<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "class " << v.name;
|
||||
if (!v.parents.isEmpty()) {
|
||||
s << ": ";
|
||||
bool first = true;
|
||||
for (const auto & i: v.parents) {
|
||||
if (first) first = false;
|
||||
else s << ", ";
|
||||
if (first)
|
||||
first = false;
|
||||
else
|
||||
s << ", ";
|
||||
s << i;
|
||||
}
|
||||
}
|
||||
@@ -234,14 +244,15 @@ inline PICout operator <<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
s << PICoutManipulators::Tab << i.return_type << " " << i.name << "(";
|
||||
bool fa = true;
|
||||
for (const auto & a: i.arguments) {
|
||||
if (fa) fa = false;
|
||||
else s << ", ";
|
||||
if (fa)
|
||||
fa = false;
|
||||
else
|
||||
s << ", ";
|
||||
s << a;
|
||||
}
|
||||
s << ") Meta" << i.meta << ";\n";
|
||||
}
|
||||
if (!v.functions.isEmpty() && !v.variables.isEmpty())
|
||||
s << "\n";
|
||||
if (!v.functions.isEmpty() && !v.variables.isEmpty()) s << "\n";
|
||||
for (const auto & i: v.variables) {
|
||||
s << PICoutManipulators::Tab << i << " Meta" << i.meta << ";\n";
|
||||
}
|
||||
@@ -250,13 +261,15 @@ inline PICout operator <<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
inline PICout operator <<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "enum " << v.name << " Meta" << v.meta << " {\n";
|
||||
for (const auto & i: v.members) {
|
||||
bool f = true;
|
||||
if (f) f = false;
|
||||
else s << ", ";
|
||||
if (f)
|
||||
f = false;
|
||||
else
|
||||
s << ", ";
|
||||
s << PICoutManipulators::Tab << i << "\n";
|
||||
}
|
||||
s << "}\n";
|
||||
@@ -267,11 +280,11 @@ inline PICout operator <<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
|
||||
//! \~english Pointer to single storage of PICodeInfo::ClassInfo, access by name
|
||||
//! \~russian Указатель на единое хренилище PICodeInfo::ClassInfo, доступ по имени
|
||||
extern PIP_EXPORT PIMap<PIConstChars, PICodeInfo::ClassInfo * > * classesInfo;
|
||||
extern PIP_EXPORT PIMap<PIConstChars, PICodeInfo::ClassInfo *> * classesInfo;
|
||||
|
||||
//! \~english Pointer to single storage of PICodeInfo::EnumInfo, access by name
|
||||
//! \~russian Указатель на единое хренилище PICodeInfo::EnumInfo, доступ по имени
|
||||
extern PIP_EXPORT PIMap<PIConstChars, PICodeInfo::EnumInfo * > * enumsInfo;
|
||||
extern PIP_EXPORT PIMap<PIConstChars, PICodeInfo::EnumInfo *> * enumsInfo;
|
||||
|
||||
extern PIP_EXPORT PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * accessValueFunctions;
|
||||
|
||||
@@ -294,21 +307,23 @@ inline const char * getMemberType(const char * class_name, const char * member_n
|
||||
PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
|
||||
|
||||
|
||||
template<typename T, typename std::enable_if< std::is_assignable<T&, const T&>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {ret << v;}
|
||||
template<typename T, typename std::enable_if<std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {
|
||||
ret << v;
|
||||
}
|
||||
|
||||
template<typename T, typename std::enable_if<!std::is_assignable<T&, const T&>::value, int>::type = 0>
|
||||
template<typename T, typename std::enable_if<!std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {}
|
||||
|
||||
}
|
||||
} // namespace PICodeInfo
|
||||
|
||||
class PIP_EXPORT __PICodeInfoInitializer__ {
|
||||
public:
|
||||
__PICodeInfoInitializer__() {
|
||||
if (_inited_) return;
|
||||
_inited_ = true;
|
||||
PICodeInfo::classesInfo = new PIMap<PIConstChars, PICodeInfo::ClassInfo * >;
|
||||
PICodeInfo::enumsInfo = new PIMap<PIConstChars, PICodeInfo::EnumInfo * >;
|
||||
PICodeInfo::classesInfo = new PIMap<PIConstChars, PICodeInfo::ClassInfo *>;
|
||||
PICodeInfo::enumsInfo = new PIMap<PIConstChars, PICodeInfo::EnumInfo *>;
|
||||
PICodeInfo::accessValueFunctions = new PIMap<PIConstChars, PICodeInfo::AccessValueFunction>;
|
||||
PICodeInfo::accessTypeFunctions = new PIMap<PIConstChars, PICodeInfo::AccessTypeFunction>;
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@
|
||||
#include "picodeparser.h"
|
||||
|
||||
|
||||
|
||||
PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
|
||||
PIStringList arg_vals;
|
||||
while (!args_.isEmpty()) {
|
||||
@@ -32,29 +31,32 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
|
||||
PIString ca;
|
||||
if (bi >= 0 && bi < ci) {
|
||||
ca = args_.left(args_.takeLeft(bi).toInt());
|
||||
ci -= ca.size_s(); bi -= ca.size_s();
|
||||
ci -= ca.size_s();
|
||||
bi -= ca.size_s();
|
||||
ca += '(' + args_.takeRange('(', ')') + ')';
|
||||
} else {
|
||||
ca = args_.takeLeft(ci);
|
||||
}
|
||||
arg_vals << ca;
|
||||
args_.trim(); args_.takeLeft(1); args_.trim();
|
||||
args_.trim();
|
||||
args_.takeLeft(1);
|
||||
args_.trim();
|
||||
}
|
||||
if (args.size() != arg_vals.size()) {
|
||||
piCout << ("Error: in expansion of macro \"" + name + '(' + args.join(", ") + ")\": expect")
|
||||
<< args.size() << "arguments but takes" << arg_vals.size() << "!";
|
||||
piCout << ("Error: in expansion of macro \"" + name + '(' + args.join(", ") + ")\": expect") << args.size() << "arguments but takes"
|
||||
<< arg_vals.size() << "!";
|
||||
if (ok != 0) *ok = false;
|
||||
return PIString();
|
||||
}
|
||||
PIString ret = value;
|
||||
for (int i = 0; i < args.size_s(); ++i) {
|
||||
const PIString & an(args[i]), av(arg_vals[i]);
|
||||
const PIString &an(args[i]), av(arg_vals[i]);
|
||||
int ind(-1);
|
||||
while ((ind = ret.find(an, ind + 1)) >= 0) {
|
||||
PIChar ppc, pc, nc;
|
||||
if (ind > 1) ppc = ret[ind - 2];
|
||||
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
|
||||
ind--;
|
||||
ret.replace(ind, an.size_s() + 1, '\"' + av + '\"');
|
||||
@@ -72,7 +74,6 @@ PIString PICodeParser::Macro::expand(PIString args_, bool * ok) const {
|
||||
}
|
||||
|
||||
|
||||
|
||||
PICodeParser::PICodeParser() {
|
||||
macros_iter = 32;
|
||||
with_includes = true;
|
||||
@@ -118,7 +119,7 @@ void PICodeParser::parseFile(const PIString & file, bool follow_includes) {
|
||||
|
||||
void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes) {
|
||||
clear();
|
||||
piForeachC (PIString & f, files)
|
||||
piForeachC(PIString & f, files)
|
||||
parseFileInternal(f, follow_includes);
|
||||
/*piCout << "\n\nDefines:";
|
||||
piForeachC (Define & m, defines)
|
||||
@@ -139,9 +140,8 @@ void PICodeParser::parseFiles(const PIStringList & files, bool follow_includes)
|
||||
|
||||
|
||||
bool PICodeParser::isEnum(const PIString & name) {
|
||||
piForeachC (Enum & e, enums)
|
||||
if (e.name == name)
|
||||
return true;
|
||||
piForeachC(Enum & e, enums)
|
||||
if (e.name == name) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -154,14 +154,14 @@ bool PICodeParser::parseFileInternal(const PIString & file, bool follow_includes
|
||||
int ii = 0;
|
||||
while (!f.isOpened() && ii < (includes.size_s() - 1)) {
|
||||
f.setPath(includes[++ii] + '/' + file);
|
||||
//piCout << "try" << f.path();
|
||||
// piCout << "try" << f.path();
|
||||
f.open(PIIODevice::ReadOnly);
|
||||
}
|
||||
if (!f.isOpened()) {
|
||||
piCout << ("Error: can`t open file \"" + file + "\"!");
|
||||
return false;
|
||||
}
|
||||
//piCout << "add" << file;
|
||||
// piCout << "add" << file;
|
||||
proc_files << f.path();
|
||||
PIString fc = PIString::fromUTF8(f.readAll());
|
||||
piCout << "parsing" << f.path() << "...";
|
||||
@@ -174,7 +174,8 @@ bool PICodeParser::parseFileInternal(const PIString & file, bool follow_includes
|
||||
|
||||
|
||||
void PICodeParser::clear() {
|
||||
piForeach (Entity * i, entities) delete i;
|
||||
piForeach(Entity * i, entities)
|
||||
delete i;
|
||||
defines.clear();
|
||||
macros.clear();
|
||||
enums.clear();
|
||||
@@ -187,37 +188,142 @@ void PICodeParser::clear() {
|
||||
cur_def_vis = Global;
|
||||
anon_num = 0;
|
||||
PIStringList defs = PIStringAscii(PICODE_DEFINES).split(",");
|
||||
piForeachC (PIString & d, defs)
|
||||
piForeachC(PIString & d, defs)
|
||||
defines << Define(d, "");
|
||||
defines << Define(PIStringAscii("PICODE"), "") << custom_defines;
|
||||
macros << Macro(PIStringAscii("PIOBJECT"), "", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("PIOBJECT_PARENT"), "", PIStringList() << "parent")
|
||||
<< Macro(PIStringAscii("PIOBJECT_SUBCLASS"), "", PIStringList() << "name" << "parent")
|
||||
<< Macro(PIStringAscii("PIOBJECT_SUBCLASS"),
|
||||
"",
|
||||
PIStringList() << "name"
|
||||
<< "parent")
|
||||
<< Macro(PIStringAscii("PIIODEVICE"), "", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("NO_COPY_CLASS"), "", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("PRIVATE_DECLARATION"))
|
||||
<< Macro(PIStringAscii("NO_COPY_CLASS"), "", PIStringList() << "name") << Macro(PIStringAscii("PRIVATE_DECLARATION"))
|
||||
|
||||
<< Macro(PIStringAscii("EVENT" ), "void name();", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("EVENT"), "void name();", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("EVENT0"), "void name();", PIStringList() << "name")
|
||||
<< Macro(PIStringAscii("EVENT1"), "void name(a0 n0);", PIStringList() << "name" << "a0" << "n0")
|
||||
<< Macro(PIStringAscii("EVENT2"), "void name(a0 n0, a1 n1);", PIStringList() << "name" << "a0" << "n0" << "a1" << "n1")
|
||||
<< Macro(PIStringAscii("EVENT3"), "void name(a0 n0, a1 n1, a2 n2);", PIStringList() << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2")
|
||||
<< Macro(PIStringAscii("EVENT4"), "void name(a0 n0, a1 n1, a2 n2, a3 n3);", PIStringList() << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2" << "a3" << "n3")
|
||||
<< Macro(PIStringAscii("EVENT1"),
|
||||
"void name(a0 n0);",
|
||||
PIStringList() << "name"
|
||||
<< "a0"
|
||||
<< "n0")
|
||||
<< Macro(PIStringAscii("EVENT2"),
|
||||
"void name(a0 n0, a1 n1);",
|
||||
PIStringList() << "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1")
|
||||
<< Macro(PIStringAscii("EVENT3"),
|
||||
"void name(a0 n0, a1 n1, a2 n2);",
|
||||
PIStringList() << "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2")
|
||||
<< Macro(PIStringAscii("EVENT4"),
|
||||
"void name(a0 n0, a1 n1, a2 n2, a3 n3);",
|
||||
PIStringList() << "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2"
|
||||
<< "a3"
|
||||
<< "n3")
|
||||
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER" ), "ret name()", PIStringList() << "ret" << "name")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER0"), "ret name()", PIStringList() << "ret" << "name")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER1"), "ret name(a0 n0)", PIStringList() << "ret" << "name" << "a0" << "n0")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER2"), "ret name(a0 n0, a1 n1)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER3"), "ret name(a0 n0, a1 n1, a2 n2)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER4"), "ret name(a0 n0, a1 n1, a2 n2, a3 n3)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2" << "a3" << "n3")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER"),
|
||||
"ret name()",
|
||||
PIStringList() << "ret"
|
||||
<< "name")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER0"),
|
||||
"ret name()",
|
||||
PIStringList() << "ret"
|
||||
<< "name")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER1"),
|
||||
"ret name(a0 n0)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER2"),
|
||||
"ret name(a0 n0, a1 n1)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER3"),
|
||||
"ret name(a0 n0, a1 n1, a2 n2)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2")
|
||||
<< Macro(PIStringAscii("EVENT_HANDLER4"),
|
||||
"ret name(a0 n0, a1 n1, a2 n2, a3 n3)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2"
|
||||
<< "a3"
|
||||
<< "n3")
|
||||
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER" ), "virtual ret name()", PIStringList() << "ret" << "name")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER0"), "virtual ret name()", PIStringList() << "ret" << "name")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER1"), "virtual ret name(a0 n0)", PIStringList() << "ret" << "name" << "a0" << "n0")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER2"), "virtual ret name(a0 n0, a1 n1)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER3"), "virtual ret name(a0 n0, a1 n1, a2 n2)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER4"), "virtual ret name(a0 n0, a1 n1, a2 n2, a3 n3)", PIStringList() << "ret" << "name" << "a0" << "n0" << "a1" << "n1" << "a2" << "n2" << "a3" << "n3")
|
||||
;
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER"),
|
||||
"virtual ret name()",
|
||||
PIStringList() << "ret"
|
||||
<< "name")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER0"),
|
||||
"virtual ret name()",
|
||||
PIStringList() << "ret"
|
||||
<< "name")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER1"),
|
||||
"virtual ret name(a0 n0)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER2"),
|
||||
"virtual ret name(a0 n0, a1 n1)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER3"),
|
||||
"virtual ret name(a0 n0, a1 n1, a2 n2)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2")
|
||||
<< Macro(PIStringAscii("EVENT_VHANDLER4"),
|
||||
"virtual ret name(a0 n0, a1 n1, a2 n2, a3 n3)",
|
||||
PIStringList() << "ret"
|
||||
<< "name"
|
||||
<< "a0"
|
||||
<< "n0"
|
||||
<< "a1"
|
||||
<< "n1"
|
||||
<< "a2"
|
||||
<< "n2"
|
||||
<< "a3"
|
||||
<< "n3");
|
||||
}
|
||||
|
||||
|
||||
@@ -247,7 +353,8 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
if (i > 0) pc = c;
|
||||
c = fc[i].toAscii();
|
||||
if (c == '"' && !mlc && pc != '\'') {
|
||||
if (i > 0) if (fc[i - 1] == '\\') continue;
|
||||
if (i > 0)
|
||||
if (fc[i - 1] == '\\') continue;
|
||||
cc = !cc;
|
||||
continue;
|
||||
}
|
||||
@@ -258,9 +365,24 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
continue;
|
||||
}
|
||||
if (cc) continue;
|
||||
if (fc.mid(i, 2) == "/*") {mlc = true; mls = i; ++i; continue;}
|
||||
if (fc.mid(i, 2) == "*/" && mlc) {mlc = false; fc.cutMid(mls, i - mls + 2); i = mls - 1; continue;}
|
||||
if (fc.mid(i, 2) == "//" && !mlc) {ole = fc.find('\n', i); fc.cutMid(i, ole < 0 ? -1 : ole - i); --i; continue;}
|
||||
if (fc.mid(i, 2) == "/*") {
|
||||
mlc = true;
|
||||
mls = i;
|
||||
++i;
|
||||
continue;
|
||||
}
|
||||
if (fc.mid(i, 2) == "*/" && mlc) {
|
||||
mlc = false;
|
||||
fc.cutMid(mls, i - mls + 2);
|
||||
i = mls - 1;
|
||||
continue;
|
||||
}
|
||||
if (fc.mid(i, 2) == "//" && !mlc) {
|
||||
ole = fc.find('\n', i);
|
||||
fc.cutMid(i, ole < 0 ? -1 : ole - i);
|
||||
--i;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
pfc = procMacros(fc);
|
||||
|
||||
@@ -269,33 +391,34 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
bool replaced = true;
|
||||
int replaced_cnt = 0;
|
||||
while (replaced) {
|
||||
//piCout << "MACRO iter" << replaced_cnt;
|
||||
// piCout << "MACRO iter" << replaced_cnt;
|
||||
if (replaced_cnt >= macros_iter) {
|
||||
piCout << "Error: recursive macros detected!";
|
||||
break;//return false;
|
||||
break; // return false;
|
||||
}
|
||||
replaced_cnt++;
|
||||
replaced = false;
|
||||
piForeachC (Define & d, defines) {
|
||||
piForeachC(Define & d, defines) {
|
||||
int ind(-1);
|
||||
while ((ind = pfc.find(d.first, ind + 1)) >= 0) {
|
||||
PIChar pc, nc;
|
||||
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;
|
||||
pfc.replace(ind, d.first.size_s(), d.second);
|
||||
ind -= d.first.size_s() - d.second.size_s();
|
||||
replaced = true;
|
||||
}
|
||||
}
|
||||
piForeachC (Macro & m, macros) {
|
||||
piForeachC(Macro & m, macros) {
|
||||
int ind(-1);
|
||||
while ((ind = pfc.find(m.name, ind + 1)) >= 0) {
|
||||
PIChar pc, nc;
|
||||
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;
|
||||
PIString ret, range; bool ok(false);
|
||||
PIString ret, range;
|
||||
bool ok(false);
|
||||
range = pfc.mid(ind + m.name.size_s()).takeRange('(', ')');
|
||||
ret = m.expand(range, &ok);
|
||||
if (!ok) return false;
|
||||
@@ -309,7 +432,7 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
|
||||
replaceMeta(pfc);
|
||||
|
||||
//piCout << PICoutManipulators::NewLine << "file" << cur_file << pfc;
|
||||
// piCout << PICoutManipulators::NewLine << "file" << cur_file << pfc;
|
||||
int pl = -1;
|
||||
cur_def_vis = Global;
|
||||
while (!pfc.isEmpty()) {
|
||||
@@ -331,14 +454,22 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
pfc.takeRange('<', '>');
|
||||
bool def = !isDeclaration(pfc, 0, &end);
|
||||
pfc.cutLeft(end);
|
||||
if (def) pfc.takeRange('{', '}');
|
||||
else pfc.takeSymbol();
|
||||
if (def)
|
||||
pfc.takeRange('{', '}');
|
||||
else
|
||||
pfc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
if (pfc.left(5) == s_class || pfc.left(6) == s_struct || pfc.left(5) == s_union) {
|
||||
int dind = pfc.find('{', 0), find = pfc.find(';', 0);
|
||||
if (dind < 0 && find < 0) {pfc.cutLeft(6); continue;}
|
||||
if (dind < 0 || find < dind) {pfc.cutLeft(6); continue;}
|
||||
if (dind < 0 && find < 0) {
|
||||
pfc.cutLeft(6);
|
||||
continue;
|
||||
}
|
||||
if (dind < 0 || find < dind) {
|
||||
pfc.cutLeft(6);
|
||||
continue;
|
||||
}
|
||||
ccmn = pfc.left(dind) + s_bo + pfc.mid(dind).takeRange('{', '}') + s_bc;
|
||||
pfc.remove(0, ccmn.size());
|
||||
parseClass(0, ccmn, false);
|
||||
@@ -356,8 +487,10 @@ bool PICodeParser::parseFileContent(PIString & fc, bool main) {
|
||||
if (pfc.left(7) == s_typedef) {
|
||||
pfc.cutLeft(7);
|
||||
typedefs << parseTypedef(pfc.takeLeft(pfc.find(';')));
|
||||
if (typedefs.back().first.isEmpty()) typedefs.pop_back();
|
||||
else root_.typedefs << typedefs.back();
|
||||
if (typedefs.back().first.isEmpty())
|
||||
typedefs.pop_back();
|
||||
else
|
||||
root_.typedefs << typedefs.back();
|
||||
pfc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
@@ -391,19 +524,23 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
|
||||
meta = tmp_meta.value(cd.takeMid(ind, 5));
|
||||
cd.replaceAll(s_ss, ' ');
|
||||
}
|
||||
//piCout << "found class <****\n" << cd << "\n****>";
|
||||
// piCout << "found class <****\n" << cd << "\n****>";
|
||||
ind = cd.find(':');
|
||||
PIVector<Entity * > parents;
|
||||
PIVector<Entity *> parents;
|
||||
if (ind > 0) {
|
||||
PIStringList pl = cd.takeMid(ind + 1).trim().split(',');
|
||||
cd.cutRight(1);
|
||||
Entity * pe = 0;
|
||||
piForeachC (PIString & p, pl) {
|
||||
if (p.contains(' ')) pn = p.mid(p.find(' ') + 1);
|
||||
else pn = p;
|
||||
piForeachC(PIString & p, pl) {
|
||||
if (p.contains(' '))
|
||||
pn = p.mid(p.find(' ') + 1);
|
||||
else
|
||||
pn = p;
|
||||
pe = findEntityByName(pn);
|
||||
if (pe == 0) ;//{piCout << "Error: can`t find" << pn;}
|
||||
else parents << pe;
|
||||
if (pe == 0)
|
||||
; //{piCout << "Error: can`t find" << pn;}
|
||||
else
|
||||
parents << pe;
|
||||
}
|
||||
}
|
||||
PIString typename_ = cd.left(6).trim();
|
||||
@@ -413,7 +550,7 @@ PICodeParser::Entity * PICodeParser::parseClassDeclaration(const PIString & fc)
|
||||
PIString cn = cd.mid(6).trim();
|
||||
bool has_name = !cn.isEmpty();
|
||||
if (cn.isEmpty()) cn = PIStringAscii("<unnamed_") + PIString::fromNumber(anon_num++) + '>';
|
||||
//piCout << "found " << typename_ << cn;
|
||||
// piCout << "found " << typename_ << cn;
|
||||
if (cn.isEmpty()) return 0;
|
||||
Entity * e = new Entity();
|
||||
e->meta = meta;
|
||||
@@ -448,14 +585,14 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
fc.left(find);
|
||||
return;
|
||||
}
|
||||
//piCout << "parse class <****\n" << fc << "\n****>";
|
||||
// piCout << "parse class <****\n" << fc << "\n****>";
|
||||
Entity * ce = parent;
|
||||
if (!is_namespace) {
|
||||
ce = parseClassDeclaration(fc.takeLeft(dind));
|
||||
fc.trim().cutLeft(1).cutRight(1).trim();
|
||||
}
|
||||
//piCout << "found class <****\n" << fc << "\n****>";
|
||||
///if (!ce) return PIString();
|
||||
// piCout << "found class <****\n" << fc << "\n****>";
|
||||
/// if (!ce) return PIString();
|
||||
if (ce) {
|
||||
if (parent) parent->children << ce;
|
||||
ce->parent_scope = parent;
|
||||
@@ -464,14 +601,26 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
bool def = false;
|
||||
PIString prev_namespace = cur_namespace, stmp;
|
||||
if (ce) cur_namespace += ce->name + s_ns;
|
||||
//piCout << "parse class" << ce->name << "namespace" << cur_namespace;
|
||||
//piCout << "\nparse class" << ce->name << "namespace" << cur_namespace;
|
||||
// piCout << "parse class" << ce->name << "namespace" << cur_namespace;
|
||||
// piCout << "\nparse class" << ce->name << "namespace" << cur_namespace;
|
||||
while (!fc.isEmpty()) {
|
||||
PIString cw = fc.takeCWord(), tmp;
|
||||
//piCout << "\ntaked word" << cw;
|
||||
if (cw == s_public ) {cur_def_vis = Public; fc.cutLeft(1); continue;}
|
||||
if (cw == s_protected) {cur_def_vis = Protected; fc.cutLeft(1); continue;}
|
||||
if (cw == s_private ) {cur_def_vis = Private; fc.cutLeft(1); continue;}
|
||||
// piCout << "\ntaked word" << cw;
|
||||
if (cw == s_public) {
|
||||
cur_def_vis = Public;
|
||||
fc.cutLeft(1);
|
||||
continue;
|
||||
}
|
||||
if (cw == s_protected) {
|
||||
cur_def_vis = Protected;
|
||||
fc.cutLeft(1);
|
||||
continue;
|
||||
}
|
||||
if (cw == s_private) {
|
||||
cur_def_vis = Private;
|
||||
fc.cutLeft(1);
|
||||
continue;
|
||||
}
|
||||
if (cw == s_namespace) {
|
||||
PIString prev_namespace = cur_namespace, ccmn;
|
||||
cur_namespace += fc.takeCWord() + s_ns;
|
||||
@@ -501,14 +650,16 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
fc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
if (cw == s_friend) {fc.cutLeft(fc.find(';') + 1); continue;}
|
||||
if (cw == s_friend) {
|
||||
fc.cutLeft(fc.find(';') + 1);
|
||||
continue;
|
||||
}
|
||||
if (cw == s_typedef) {
|
||||
if (ce) {
|
||||
ce->typedefs << parseTypedef(fc.takeLeft(fc.find(';')));
|
||||
typedefs << ce->typedefs.back();
|
||||
typedefs.back().first.insert(0, cur_namespace);
|
||||
if (ce->typedefs.back().first.isEmpty())
|
||||
ce->typedefs.pop_back();
|
||||
if (ce->typedefs.back().first.isEmpty()) ce->typedefs.pop_back();
|
||||
}
|
||||
fc.takeSymbol();
|
||||
continue;
|
||||
@@ -517,17 +668,22 @@ void PICodeParser::parseClass(Entity * parent, PIString & fc, bool is_namespace)
|
||||
fc.takeRange('<', '>');
|
||||
def = !isDeclaration(fc, 0, &end);
|
||||
fc.cutLeft(end);
|
||||
if (def) fc.takeRange('{', '}');
|
||||
else fc.takeSymbol();
|
||||
if (def)
|
||||
fc.takeRange('{', '}');
|
||||
else
|
||||
fc.takeSymbol();
|
||||
continue;
|
||||
}
|
||||
def = !isDeclaration(fc, 0, &end);
|
||||
tmp = (cw + fc.takeLeft(end)).trim();
|
||||
if (!tmp.isEmpty() && ce)
|
||||
parseMember(ce, tmp);
|
||||
if (def) fc.takeRange('{', '}');
|
||||
else fc.takeSymbol();
|
||||
if (ps == fc.size_s()) {fc.cutLeft(1);}
|
||||
if (!tmp.isEmpty() && ce) parseMember(ce, tmp);
|
||||
if (def)
|
||||
fc.takeRange('{', '}');
|
||||
else
|
||||
fc.takeSymbol();
|
||||
if (ps == fc.size_s()) {
|
||||
fc.cutLeft(1);
|
||||
}
|
||||
ps = fc.size_s();
|
||||
}
|
||||
cur_def_vis = prev_vis;
|
||||
@@ -539,7 +695,7 @@ PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) {
|
||||
PICodeParser::MetaMap ret;
|
||||
if (fc.isEmpty()) return ret;
|
||||
PIStringList ml = fc.split(',');
|
||||
piForeachC (PIString & m, ml) {
|
||||
piForeachC(PIString & m, ml) {
|
||||
int i = m.find('=');
|
||||
if (i < 0) {
|
||||
ret[m.trimmed()] = PIString();
|
||||
@@ -550,7 +706,7 @@ PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) {
|
||||
ret[m.left(i).trim()] = mv;
|
||||
}
|
||||
}
|
||||
//piCout << ms << ret;
|
||||
// piCout << ms << ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -558,47 +714,53 @@ PICodeParser::MetaMap PICodeParser::parseMeta(PIString & fc) {
|
||||
bool PICodeParser::parseEnum(Entity * parent, const PIString & name, PIString fc, const MetaMap & meta) {
|
||||
static const PIString s_ss = PIStringAscii(" ");
|
||||
static const PIString s_M = PIStringAscii("$M");
|
||||
//piCout << PIStringAscii("enum") << name << fc;
|
||||
// piCout << PIStringAscii("enum") << name << fc;
|
||||
Enum e(name);
|
||||
e.meta = meta;
|
||||
PIStringList vl(fc.split(','));
|
||||
PIString vn;
|
||||
int cv = -1, ind = 0;
|
||||
piForeach (PIString & v, vl) {
|
||||
piForeach(PIString & v, vl) {
|
||||
MetaMap meta;
|
||||
int mi = v.find(s_M);
|
||||
if (mi >= 0) {
|
||||
meta = tmp_meta.value(v.takeMid(mi, 5));
|
||||
v.replaceAll(s_ss, ' ');
|
||||
}
|
||||
vn = v; ind = v.find('=');
|
||||
if (ind > 0) {cv = v.right(v.size_s() - ind - 1).toInt(); vn = v.left(ind);}
|
||||
vn = v;
|
||||
ind = v.find('=');
|
||||
if (ind > 0) {
|
||||
cv = v.right(v.size_s() - ind - 1).toInt();
|
||||
vn = v.left(ind);
|
||||
}
|
||||
if (ind < 0) ++cv;
|
||||
e.members << EnumeratorInfo(vn.trim(), cv, meta);
|
||||
}
|
||||
if (!e.members.isEmpty())
|
||||
if (e.members.back().name.isEmpty())
|
||||
e.members.pop_back();
|
||||
if (e.members.back().name.isEmpty()) e.members.pop_back();
|
||||
enums << e;
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
PICodeParser::Typedef PICodeParser::parseTypedef(PIString fc) {
|
||||
//piCout << "parse typedef" << fc;
|
||||
// piCout << "parse typedef" << fc;
|
||||
Typedef td;
|
||||
fc.replaceAll('\t', ' ');
|
||||
|
||||
if (fc.contains('(')) {
|
||||
int start = fc.find('('), end = fc.find(')');
|
||||
td.first = fc.takeMid(start + 1, end - start - 1).trim();
|
||||
if (td.first.left(1) == PIChar('*')) {td.first.cutLeft(1).trim(); fc.insert(start + 1, '*');}
|
||||
if (td.first.left(1) == PIChar('*')) {
|
||||
td.first.cutLeft(1).trim();
|
||||
fc.insert(start + 1, '*');
|
||||
}
|
||||
td.second = fc.trim();
|
||||
} else {
|
||||
td.first = fc.takeMid(fc.findLast(' ')).trim();
|
||||
td.second = fc.trim();
|
||||
}
|
||||
//piCout << "found typedef" << td;
|
||||
// piCout << "found typedef" << td;
|
||||
return td;
|
||||
}
|
||||
|
||||
@@ -634,22 +796,26 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
if (fc.trim().isEmpty()) return true;
|
||||
if (fc.find(s_operator) >= 0) return true;
|
||||
tmp_temp.clear();
|
||||
//piCout << "parse member" << fc;
|
||||
// piCout << "parse member" << fc;
|
||||
int ts = fc.find('<'), te = 0;
|
||||
PIString ctemp, crepl;
|
||||
while (ts >= 0) {
|
||||
ctemp = fc.mid(ts).takeRange('<', '>');
|
||||
if (ctemp.isEmpty()) {te = ts + 1; ts = fc.find('<', te); continue;}
|
||||
if (ctemp.isEmpty()) {
|
||||
te = ts + 1;
|
||||
ts = fc.find('<', te);
|
||||
continue;
|
||||
}
|
||||
crepl = s_T + PIString::fromNumber(tmp_temp.size_s()).expandLeftTo(3, '0');
|
||||
fc.replace(ts, ctemp.size_s() + 2, crepl);
|
||||
tmp_temp[crepl] = '<' + ctemp + '>';
|
||||
ts = fc.find('<', te);
|
||||
}
|
||||
fc.replaceAll('\n', ' ').replaceAll('\t', ' ').replaceAll(s_ss, ' ').replaceAll(s_cs, ',').replaceAll(s_sb, '(').replaceAll(s_sM, s_M);
|
||||
//piCout << "parse member" << fc;
|
||||
// piCout << "parse member" << fc;
|
||||
PIStringList tl, al;
|
||||
Member me;
|
||||
//piCout << fc;
|
||||
// piCout << fc;
|
||||
if (fc.contains('(')) {
|
||||
MetaMap meta;
|
||||
int ind = fc.find(s_M);
|
||||
@@ -659,10 +825,10 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
}
|
||||
fc.cutRight(fc.size_s() - fc.findLast(')') - 1);
|
||||
te = fc.find('(');
|
||||
//piCout << fc;
|
||||
// piCout << fc;
|
||||
for (ts = te - 1; ts >= 0; --ts)
|
||||
if (!_isCChar(fc[ts]) && !(fc[ts].isDigit())) break;
|
||||
//piCout << "takeMid" << ts + 1 << te - ts - 1;
|
||||
// piCout << "takeMid" << ts + 1 << te - ts - 1;
|
||||
me.meta = meta;
|
||||
me.name = fc.takeMid(ts + 1, te - ts - 1);
|
||||
if (me.name == parent->name) return true;
|
||||
@@ -683,20 +849,18 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
}
|
||||
normalizeEntityNamespace(me.type);
|
||||
int i = 0;
|
||||
//piCout << me.arguments_full;
|
||||
piForeach (PIString & a, me.arguments_full)
|
||||
if ((i = a.find('=')) > 0)
|
||||
a.cutRight(a.size_s() - i).trim();
|
||||
// piCout << me.arguments_full;
|
||||
piForeach(PIString & a, me.arguments_full)
|
||||
if ((i = a.find('=')) > 0) a.cutRight(a.size_s() - i).trim();
|
||||
for (int j = 0; j < me.arguments_full.size_s(); ++j)
|
||||
if (me.arguments_full[j] == s_void) {
|
||||
me.arguments_full.remove(j);
|
||||
--j;
|
||||
}
|
||||
me.arguments_type = me.arguments_full;
|
||||
piForeach (PIString & a, me.arguments_type) {
|
||||
piForeach(PIString & a, me.arguments_type) {
|
||||
crepl.clear();
|
||||
if (a.contains('['))
|
||||
crepl = a.takeMid(a.find('['), a.findLast(']') - a.find('[') + 1);
|
||||
if (a.contains('[')) crepl = a.takeMid(a.find('['), a.findLast(']') - a.find('[') + 1);
|
||||
for (ts = a.size_s() - 1; ts >= 0; --ts)
|
||||
if (!_isCChar(a[ts]) && !(a[ts].isDigit())) break;
|
||||
a.cutRight(a.size_s() - ts - 1);
|
||||
@@ -705,18 +869,18 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
a.trim();
|
||||
}
|
||||
restoreTmpTemp(&me);
|
||||
//piCout << "func" << me.type << me.name << me.arguments_full << me.arguments_type;
|
||||
// piCout << "func" << me.type << me.name << me.arguments_full << me.arguments_type;
|
||||
parent->functions << me;
|
||||
} else {
|
||||
if (fc.endsWith(';')) fc.cutRight(1);
|
||||
//piCout << "member" << fc;
|
||||
// piCout << "member" << fc;
|
||||
if (fc.startsWith(s_using) || !(fc.contains(' ') || fc.contains('\t') || fc.contains('\n'))) return true;
|
||||
int bits = extractMemberBits(fc);
|
||||
tl = fc.split(',');
|
||||
//piCout << "member" << fc << tl;
|
||||
//piCout << "member after eb" << fc << ", bits =" << bits;
|
||||
// piCout << "member" << fc << tl;
|
||||
// piCout << "member after eb" << fc << ", bits =" << bits;
|
||||
if (tl.isEmpty()) return true;
|
||||
piForeach (PIString & v, tl)
|
||||
piForeach(PIString & v, tl)
|
||||
removeAssignment(v);
|
||||
bool vn = true;
|
||||
ctemp = tl.front().trim();
|
||||
@@ -726,8 +890,11 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
ctemp.trim();
|
||||
}
|
||||
for (ts = ctemp.size_s() - 1; ts > 0; --ts) {
|
||||
if (vn) {if (!_isCChar(ctemp[ts]) && !ctemp[ts].isDigit() && ctemp[ts] != '[' && ctemp[ts] != ']') vn = false;}
|
||||
else {if (_isCChar(ctemp[ts]) || ctemp[ts].isDigit()) break;}
|
||||
if (vn) {
|
||||
if (!_isCChar(ctemp[ts]) && !ctemp[ts].isDigit() && ctemp[ts] != '[' && ctemp[ts] != ']') vn = false;
|
||||
} else {
|
||||
if (_isCChar(ctemp[ts]) || ctemp[ts].isDigit()) break;
|
||||
}
|
||||
}
|
||||
me.type = ctemp.takeLeft(ts + 1);
|
||||
me.visibility = cur_def_vis;
|
||||
@@ -757,21 +924,21 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
type.trim();
|
||||
normalizeEntityNamespace(type);
|
||||
tl[0] = ctemp.trim();
|
||||
//piCout << "vars" << tl;
|
||||
piForeachC (PIString & v, tl) {
|
||||
// piCout << "vars" << tl;
|
||||
piForeachC(PIString & v, tl) {
|
||||
crepl.clear();
|
||||
|
||||
me.name = v.trimmed();
|
||||
me.type = type;
|
||||
restoreTmpMeta(&me);
|
||||
if (me.name.isEmpty()) continue;
|
||||
if (me.name.contains('['))
|
||||
crepl = me.name.takeMid(me.name.find('['), me.name.findLast(']') - me.name.find('[') + 1);
|
||||
if (me.name.contains('[')) crepl = me.name.takeMid(me.name.find('['), me.name.findLast(']') - me.name.find('[') + 1);
|
||||
while (!me.name.isEmpty()) {
|
||||
if (me.name.front() == PIChar('*') || me.name.front() == PIChar('&')) {
|
||||
me.type += me.name.takeLeft(1);
|
||||
me.name.trim();
|
||||
} else break;
|
||||
} else
|
||||
break;
|
||||
}
|
||||
me.is_type_ptr = (me.type.right(1) == PIChar(']') || me.type.right(1) == PIChar('*'));
|
||||
me.type += crepl;
|
||||
@@ -781,12 +948,12 @@ bool PICodeParser::parseMember(Entity * parent, PIString & fc) {
|
||||
if (cdim.isEmpty()) break;
|
||||
me.dims << cdim;
|
||||
}
|
||||
//PICout(PICoutManipulators::AddAll) << "var" << me.type << me.name << me.bits;
|
||||
//piCout << "var" << v << me.type << me.name << me.bits;
|
||||
// PICout(PICoutManipulators::AddAll) << "var" << me.type << me.name << me.bits;
|
||||
// piCout << "var" << v << me.type << me.name << me.bits;
|
||||
parent->members << me;
|
||||
}
|
||||
}
|
||||
//piCout << "parse member" << fc;
|
||||
// piCout << "parse member" << fc;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -818,13 +985,25 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
|
||||
break;
|
||||
}
|
||||
n.push_front(' ');
|
||||
if (n.find(s_s_const_s) >= 0) {n.replaceAll(s_s_const_s, ""); pref += s_const_s;}
|
||||
if (n.find(s_s_static_s) >= 0) {n.replaceAll(s_s_static_s, ""); pref += s_static_s;}
|
||||
if (n.find(s_s_mutable_s) >= 0) {n.replaceAll(s_s_mutable_s, ""); pref += s_mutable_s;}
|
||||
if (n.find(s_s_volatile_s) >= 0) {n.replaceAll(s_s_volatile_s, ""); pref += s_volatile_s;}
|
||||
if (n.find(s_s_const_s) >= 0) {
|
||||
n.replaceAll(s_s_const_s, "");
|
||||
pref += s_const_s;
|
||||
}
|
||||
if (n.find(s_s_static_s) >= 0) {
|
||||
n.replaceAll(s_s_static_s, "");
|
||||
pref += s_static_s;
|
||||
}
|
||||
if (n.find(s_s_mutable_s) >= 0) {
|
||||
n.replaceAll(s_s_mutable_s, "");
|
||||
pref += s_mutable_s;
|
||||
}
|
||||
if (n.find(s_s_volatile_s) >= 0) {
|
||||
n.replaceAll(s_s_volatile_s, "");
|
||||
pref += s_volatile_s;
|
||||
}
|
||||
n.trim();
|
||||
int f = 0;
|
||||
piForeachC (Entity * e, entities) {
|
||||
piForeachC(Entity * e, entities) {
|
||||
if (e->name == n) {
|
||||
n = (pref + n + suff).trim();
|
||||
return;
|
||||
@@ -836,20 +1015,20 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
piForeachC (Enum & e, enums) {
|
||||
piForeachC(Enum & e, enums) {
|
||||
if ((f = e.name.find(n)) >= 0)
|
||||
if (e.name.at(f - 1) == PIChar(':'))
|
||||
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;
|
||||
return;
|
||||
}
|
||||
}
|
||||
piForeachC (Typedef & e, typedefs) {
|
||||
piForeachC(Typedef & e, typedefs) {
|
||||
if ((f = e.first.find(n)) >= 0)
|
||||
if (e.first.at(f - 1) == PIChar(':'))
|
||||
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;
|
||||
return;
|
||||
}
|
||||
@@ -861,11 +1040,11 @@ void PICodeParser::normalizeEntityNamespace(PIString & n) {
|
||||
void PICodeParser::restoreTmpTemp(Member * e) {
|
||||
static const PIString s_T = PIStringAscii("$T");
|
||||
int i = 0;
|
||||
piForeach (PIString & a, e->arguments_full) {
|
||||
piForeach(PIString & a, e->arguments_full) {
|
||||
while ((i = a.find(s_T)) >= 0)
|
||||
a.replace(i, 5, tmp_temp[a.mid(i, 5)]);
|
||||
}
|
||||
piForeach (PIString & a, e->arguments_type) {
|
||||
piForeach(PIString & a, e->arguments_type) {
|
||||
while ((i = a.find(s_T)) >= 0)
|
||||
a.replace(i, 5, tmp_temp[a.mid(i, 5)]);
|
||||
}
|
||||
@@ -898,7 +1077,7 @@ bool PICodeParser::macroCondition(const PIString & mif, PIString mifcond) {
|
||||
static const PIString s_ifndef = PIStringAscii("ifndef");
|
||||
static const PIString s_if = PIStringAscii("if");
|
||||
static const PIString s_elif = PIStringAscii("elif");
|
||||
//piCout << "macroCondition" << mif << mifcond;
|
||||
// piCout << "macroCondition" << mif << mifcond;
|
||||
if (mif == s_ifdef) return isDefineExists(mifcond);
|
||||
if (mif == s_ifndef) return !isDefineExists(mifcond);
|
||||
if (mif == s_if || mif == s_elif) {
|
||||
@@ -917,14 +1096,29 @@ double PICodeParser::procMacrosCond(PIString fc) {
|
||||
char cc, nc;
|
||||
PIString ce;
|
||||
fc.removeAll(s_defined);
|
||||
//piCout << "procMacrosCond" << fc;
|
||||
// piCout << "procMacrosCond" << fc;
|
||||
while (!fc.isEmpty()) {
|
||||
cc = fc[0].toAscii();
|
||||
nc = (fc.size() > 1 ? fc[1].toAscii() : 0);
|
||||
if (cc == '!') {neg = true; fc.pop_front(); continue;}
|
||||
if (cc == '(') {br = true; brv = procMacrosCond(fc.takeRange('(', ')'));}
|
||||
if (cc == '&' && nc == '&') {fc.remove(0, 2); oper = 1; continue;}
|
||||
if (cc == '|' && nc == '|') {fc.remove(0, 2); oper = 2; continue;}
|
||||
if (cc == '!') {
|
||||
neg = true;
|
||||
fc.pop_front();
|
||||
continue;
|
||||
}
|
||||
if (cc == '(') {
|
||||
br = true;
|
||||
brv = procMacrosCond(fc.takeRange('(', ')'));
|
||||
}
|
||||
if (cc == '&' && nc == '&') {
|
||||
fc.remove(0, 2);
|
||||
oper = 1;
|
||||
continue;
|
||||
}
|
||||
if (cc == '|' && nc == '|') {
|
||||
fc.remove(0, 2);
|
||||
oper = 2;
|
||||
continue;
|
||||
}
|
||||
if (!br) {
|
||||
ce = fc.takeCWord();
|
||||
if (ce.isEmpty()) ce = fc.takeNumber();
|
||||
@@ -934,7 +1128,7 @@ double PICodeParser::procMacrosCond(PIString fc) {
|
||||
ret = br ? brv : defineValue(ce);
|
||||
if (neg) ret = -ret;
|
||||
} else {
|
||||
//piCout << "oper" << oper << "with" << ce;
|
||||
// piCout << "oper" << oper << "with" << ce;
|
||||
if (!br) brv = defineValue(ce);
|
||||
switch (oper) {
|
||||
case 1: ret = ret && (neg ? -brv : brv); break;
|
||||
@@ -945,24 +1139,22 @@ double PICodeParser::procMacrosCond(PIString fc) {
|
||||
ps = fc.size_s();
|
||||
br = neg = false;
|
||||
}
|
||||
//piCout << "return" << ret;
|
||||
// piCout << "return" << ret;
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
bool PICodeParser::isDefineExists(const PIString & dn) {
|
||||
piForeachC (Define & d, defines) {
|
||||
if (d.first == dn)
|
||||
return true;
|
||||
piForeachC(Define & d, defines) {
|
||||
if (d.first == dn) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
double PICodeParser::defineValue(const PIString & dn) {
|
||||
piForeachC (Define & d, defines) {
|
||||
if (d.first == dn)
|
||||
return d.second.isEmpty() ? 1. : d.second.toDouble();
|
||||
piForeachC(Define & d, defines) {
|
||||
if (d.first == dn) return d.second.isEmpty() ? 1. : d.second.toDouble();
|
||||
}
|
||||
return dn.toDouble();
|
||||
}
|
||||
@@ -981,7 +1173,7 @@ void PICodeParser::replaceMeta(PIString & dn) {
|
||||
PIString meta = dn.mid(ms, ml).trim();
|
||||
PIString rm = s_M + PIString::fromNumber(tmp_meta.size_s()).expandLeftTo(3, '0');
|
||||
dn.replace(s, ms + ml + 1 - s, rm);
|
||||
//piCout << "FOUND META \"" << meta << '\"';
|
||||
// piCout << "FOUND META \"" << meta << '\"';
|
||||
tmp_meta[rm] = parseMeta(meta);
|
||||
s = dn.find(s_PIMETA);
|
||||
}
|
||||
@@ -989,18 +1181,23 @@ void PICodeParser::replaceMeta(PIString & dn) {
|
||||
|
||||
|
||||
PICodeParser::Entity * PICodeParser::findEntityByName(const PIString & en) {
|
||||
piForeach (Entity * e, entities)
|
||||
if (e->name == en)
|
||||
return e;
|
||||
piForeach(Entity * e, entities)
|
||||
if (e->name == en) return e;
|
||||
return 0;
|
||||
}
|
||||
|
||||
|
||||
bool PICodeParser::isDeclaration(const PIString & fc, int start, int * end) {
|
||||
int dind = fc.find('{', start), find = fc.find(';', start);
|
||||
//piCout << "isDeclaration" << dind << find << fc.left(10);
|
||||
if (dind < 0 && find < 0) {if (end) *end = -1; return true;}
|
||||
if (dind < 0 || find < dind) {if (end) *end = find; return true;}
|
||||
// piCout << "isDeclaration" << dind << find << fc.left(10);
|
||||
if (dind < 0 && find < 0) {
|
||||
if (end) *end = -1;
|
||||
return true;
|
||||
}
|
||||
if (dind < 0 || find < dind) {
|
||||
if (end) *end = find;
|
||||
return true;
|
||||
}
|
||||
if (end) *end = dind;
|
||||
return false;
|
||||
}
|
||||
@@ -1038,68 +1235,80 @@ PIString PICodeParser::procMacros(PIString fc) {
|
||||
int ifcnt = 0;
|
||||
bool grab = false, skip = false, cond_ok = false;
|
||||
PIString pfc, nfc, line, mif, mifcond;
|
||||
//piCout << "procMacros\n<******" << fc << "\n******>";
|
||||
// piCout << "procMacros\n<******" << fc << "\n******>";
|
||||
fc += '\n';
|
||||
while (!fc.isEmpty()) {
|
||||
line = fc.takeLine().trimmed();
|
||||
if (line.left(1) == PIChar('#')) {
|
||||
mifcond = line.mid(1);
|
||||
mif = mifcond.takeCWord();
|
||||
//piCout << mif;
|
||||
//piCout << "mif mifcond" << mif << mifcond << ifcnt;
|
||||
// piCout << mif;
|
||||
// piCout << "mif mifcond" << mif << mifcond << ifcnt;
|
||||
if (skip || grab) {
|
||||
if (mif.left(2) == s_if) ifcnt++;
|
||||
if (mif.left(5) == s_endif) {
|
||||
if (ifcnt > 0) ifcnt--;
|
||||
if (ifcnt > 0)
|
||||
ifcnt--;
|
||||
else {
|
||||
//piCout << "main endif" << skip << grab;
|
||||
// piCout << "main endif" << skip << grab;
|
||||
if (grab) pfc += procMacros(nfc);
|
||||
skip = grab = false;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
if (mif.left(4) == s_elif && ifcnt == 0) {
|
||||
//piCout << "main elif" << skip << grab << cond_ok;
|
||||
// piCout << "main elif" << skip << grab << cond_ok;
|
||||
if (cond_ok) {
|
||||
if (grab) {
|
||||
pfc += procMacros(nfc);
|
||||
skip = true; grab = false;
|
||||
skip = true;
|
||||
grab = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (skip) {
|
||||
//piCout << "check elif" << skip << grab << cond_ok;
|
||||
// piCout << "check elif" << skip << grab << cond_ok;
|
||||
if (!macroCondition(mif, mifcond.trimmed())) continue;
|
||||
//piCout << "check elif ok";
|
||||
skip = false; grab = cond_ok = true;
|
||||
// piCout << "check elif ok";
|
||||
skip = false;
|
||||
grab = cond_ok = true;
|
||||
continue;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (mif.left(4) == s_else && ifcnt == 0) {
|
||||
//piCout << "main else" << skip << grab;
|
||||
// piCout << "main else" << skip << grab;
|
||||
if (grab) pfc += procMacros(nfc);
|
||||
if (skip && !cond_ok) {skip = false; grab = true;}
|
||||
else {skip = true; grab = false;}
|
||||
if (skip && !cond_ok) {
|
||||
skip = false;
|
||||
grab = true;
|
||||
} else {
|
||||
skip = true;
|
||||
grab = false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (grab) nfc += line + '\n';
|
||||
continue;
|
||||
}
|
||||
if (mif.left(2) == s_if) {
|
||||
//piCout << "main if";
|
||||
// piCout << "main if";
|
||||
skip = grab = cond_ok = false;
|
||||
if (macroCondition(mif, mifcond.trimmed())) grab = cond_ok = true;
|
||||
else skip = true;
|
||||
if (macroCondition(mif, mifcond.trimmed()))
|
||||
grab = cond_ok = true;
|
||||
else
|
||||
skip = true;
|
||||
ifcnt = 0;
|
||||
nfc.clear();
|
||||
} else {
|
||||
parseDirective(line.cutLeft(1).trim());
|
||||
//return false; /// WARNING: now skip errors
|
||||
// return false; /// WARNING: now skip errors
|
||||
}
|
||||
} else {
|
||||
if (grab) nfc += line + '\n';
|
||||
else if (!skip) pfc += line + '\n';
|
||||
if (grab)
|
||||
nfc += line + '\n';
|
||||
else if (!skip)
|
||||
pfc += line + '\n';
|
||||
}
|
||||
}
|
||||
return pfc;
|
||||
@@ -1113,7 +1322,7 @@ bool PICodeParser::parseDirective(PIString d) {
|
||||
static const PIString s_PIMETA = PIStringAscii("PIMETA");
|
||||
if (d.isEmpty()) return true;
|
||||
PIString dname = d.takeCWord();
|
||||
//piCout << "parseDirective" << d;
|
||||
// piCout << "parseDirective" << d;
|
||||
if (dname == s_include) {
|
||||
d.replaceAll('<', '\"').replaceAll('>', '\"');
|
||||
PIString cf = cur_file, ifc = d.takeRange('\"', '\"');
|
||||
@@ -1125,7 +1334,7 @@ bool PICodeParser::parseDirective(PIString d) {
|
||||
}
|
||||
if (dname == s_define) {
|
||||
PIString mname = d.takeCWord();
|
||||
//piCout << mname;
|
||||
// piCout << mname;
|
||||
if (mname == s_PIMETA) return true;
|
||||
if (d.left(1) == PIChar('(')) { // macro
|
||||
PIStringList args = d.takeRange('(', ')').split(',').trim();
|
||||
@@ -1150,7 +1359,10 @@ bool PICodeParser::parseDirective(PIString d) {
|
||||
if (dname == s_undef) {
|
||||
PIString mname = d.takeCWord();
|
||||
for (int i = 0; i < defines.size_s(); ++i)
|
||||
if (defines[i].first == mname) {defines.remove(i); --i;}
|
||||
if (defines[i].first == mname) {
|
||||
defines.remove(i);
|
||||
--i;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
|
||||
@@ -26,17 +26,27 @@
|
||||
#ifndef PICODEPARSER_H
|
||||
#define PICODEPARSER_H
|
||||
|
||||
#include "pifile.h"
|
||||
#include "pievaluator.h"
|
||||
#include "pifile.h"
|
||||
|
||||
inline bool _isCChar(const PIChar & c) {return (c.isAlpha() || (c.toAscii() == '_'));}
|
||||
inline bool _isCChar(const PIString & c) {if (c.isEmpty()) return false; return _isCChar(c[0]);}
|
||||
inline bool _isCChar(const PIChar & c) {
|
||||
return (c.isAlpha() || (c.toAscii() == '_'));
|
||||
}
|
||||
inline bool _isCChar(const PIString & c) {
|
||||
if (c.isEmpty()) return false;
|
||||
return _isCChar(c[0]);
|
||||
}
|
||||
|
||||
class PIP_EXPORT PICodeParser {
|
||||
public:
|
||||
PICodeParser();
|
||||
|
||||
enum Visibility {Global, Public, Protected, Private};
|
||||
enum Visibility {
|
||||
Global,
|
||||
Public,
|
||||
Protected,
|
||||
Private
|
||||
};
|
||||
enum Attribute {
|
||||
NoAttributes = 0x0,
|
||||
Const = 0x01,
|
||||
@@ -73,7 +83,7 @@ public:
|
||||
is_type_ptr = false;
|
||||
attributes = NoAttributes;
|
||||
}
|
||||
bool isBitfield() const {return bits > 0;}
|
||||
bool isBitfield() const { return bits > 0; }
|
||||
MetaMap meta;
|
||||
PIString type;
|
||||
PIString name;
|
||||
@@ -102,24 +112,26 @@ public:
|
||||
int size;
|
||||
bool has_name;
|
||||
Entity * parent_scope;
|
||||
PIVector<Entity * > parents;
|
||||
PIVector<Entity * > children;
|
||||
PIVector<Entity *> parents;
|
||||
PIVector<Entity *> children;
|
||||
PIVector<Member> functions;
|
||||
PIVector<Member> members;
|
||||
PIVector<Typedef> typedefs;
|
||||
};
|
||||
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {name = n; value = v; meta = m;}
|
||||
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {
|
||||
name = n;
|
||||
value = v;
|
||||
meta = m;
|
||||
}
|
||||
MetaMap meta;
|
||||
PIString name;
|
||||
int value;
|
||||
};
|
||||
|
||||
struct PIP_EXPORT Enum {
|
||||
Enum(const PIString & n = PIString()) {
|
||||
name = n;
|
||||
}
|
||||
Enum(const PIString & n = PIString()) { name = n; }
|
||||
MetaMap meta;
|
||||
PIString name;
|
||||
PIVector<EnumeratorInfo> members;
|
||||
@@ -128,22 +140,22 @@ public:
|
||||
void parseFile(const PIString & file, bool follow_includes = true);
|
||||
void parseFiles(const PIStringList & files, bool follow_includes = true);
|
||||
|
||||
void includeDirectory(const PIString & dir) {includes << dir;}
|
||||
void addDefine(const PIString & def_name, const PIString & def_value) {custom_defines << Define(def_name, def_value);}
|
||||
void includeDirectory(const PIString & dir) { includes << dir; }
|
||||
void addDefine(const PIString & def_name, const PIString & def_value) { custom_defines << Define(def_name, def_value); }
|
||||
bool isEnum(const PIString & name);
|
||||
Entity * findEntityByName(const PIString & en);
|
||||
PIStringList parsedFiles() const {return PIStringList(proc_files.toVector());}
|
||||
PIString mainFile() const {return main_file;}
|
||||
const PICodeParser::Entity * global() const {return &root_;}
|
||||
PIStringList parsedFiles() const { return PIStringList(proc_files.toVector()); }
|
||||
PIString mainFile() const { return main_file; }
|
||||
const PICodeParser::Entity * global() const { return &root_; }
|
||||
|
||||
int macrosSubstitutionMaxIterations() const {return macros_iter;}
|
||||
void setMacrosSubstitutionMaxIterations(int value) {macros_iter = value;}
|
||||
int macrosSubstitutionMaxIterations() const { return macros_iter; }
|
||||
void setMacrosSubstitutionMaxIterations(int value) { macros_iter = value; }
|
||||
|
||||
PIVector<Define> defines, custom_defines;
|
||||
PIVector<Macro> macros;
|
||||
PIVector<Enum> enums;
|
||||
PIVector<Typedef> typedefs;
|
||||
PIVector<Entity * > entities;
|
||||
PIVector<Entity *> entities;
|
||||
|
||||
private:
|
||||
void clear();
|
||||
@@ -181,7 +193,6 @@ private:
|
||||
PIString cur_namespace;
|
||||
PIMap<PIString, PIString> tmp_temp;
|
||||
PIMap<PIString, MetaMap> tmp_meta;
|
||||
|
||||
};
|
||||
|
||||
#endif // PICODEPARSER_H
|
||||
|
||||
@@ -58,8 +58,8 @@
|
||||
#ifndef PICOMPRESS_H
|
||||
#define PICOMPRESS_H
|
||||
|
||||
#include "pip_compress_export.h"
|
||||
#include "pibytearray.h"
|
||||
#include "pip_compress_export.h"
|
||||
|
||||
//! \~english Compress "ba" with compression level "level", return empty %PIByteArray if no compression supports
|
||||
//! \~russian Сжимает "ba" с уровнем сжатия "level", возвращает пустой %PIByteArray если нет поддержки
|
||||
|
||||
@@ -27,60 +27,64 @@
|
||||
#define PISCREEN_H
|
||||
|
||||
#include "pip_console_export.h"
|
||||
#include "piscreentile.h"
|
||||
#include "piscreendrawer.h"
|
||||
#include "piscreentile.h"
|
||||
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreen: public PIThread, public PIScreenTypes::PIScreenBase
|
||||
{
|
||||
class PIP_CONSOLE_EXPORT PIScreen
|
||||
: public PIThread
|
||||
, public PIScreenTypes::PIScreenBase {
|
||||
PIOBJECT_SUBCLASS(PIScreen, PIThread);
|
||||
class SystemConsole;
|
||||
public:
|
||||
|
||||
public:
|
||||
//! Constructs %PIScreen with key handler "slot" and if "startNow" start it
|
||||
PIScreen(bool startNow = true, PIKbdListener::KBFunc slot = 0);
|
||||
|
||||
~PIScreen();
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
void enableExitCapture(int key = 'Q') {listener->enableExitCapture(key);}
|
||||
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
void disableExitCapture() {listener->disableExitCapture();}
|
||||
void disableExitCapture() { listener->disableExitCapture(); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
bool exitCaptured() const {return listener->exitCaptured();}
|
||||
bool exitCaptured() const { return listener->exitCaptured(); }
|
||||
|
||||
//! Directly call function from \a PIKbdListener
|
||||
int exitKey() const {return listener->exitKey();}
|
||||
int exitKey() const { return listener->exitKey(); }
|
||||
|
||||
int windowWidth() const {return console.width;}
|
||||
int windowHeight() const {return console.height;}
|
||||
int windowWidth() const { return console.width; }
|
||||
int windowHeight() const { return console.height; }
|
||||
|
||||
bool isMouseEnabled() const {return mouse_;}
|
||||
bool isMouseEnabled() const { return mouse_; }
|
||||
void setMouseEnabled(bool on);
|
||||
|
||||
PIScreenTile * rootTile() {return &root;}
|
||||
PIScreenTile * rootTile() { return &root; }
|
||||
PIScreenTile * tileByName(const PIString & name);
|
||||
|
||||
void setDialogTile(PIScreenTile * t);
|
||||
PIScreenTile * dialogTile() const {return tile_dialog;}
|
||||
PIScreenTile * dialogTile() const { return tile_dialog; }
|
||||
|
||||
PIScreenDrawer * drawer() {return &drawer_;}
|
||||
void clear() {drawer_.clear();}
|
||||
void resize(int w, int h) {console.resize(w, h);}
|
||||
PIScreenDrawer * drawer() { return &drawer_; }
|
||||
void clear() { drawer_.clear(); }
|
||||
void resize(int w, int h) { console.resize(w, h); }
|
||||
|
||||
EVENT_HANDLER0(void, waitForFinish);
|
||||
EVENT_HANDLER0(void, start) {start(false);}
|
||||
EVENT_HANDLER1(void, start, bool, wait) {PIThread::start(40); if (wait) waitForFinish();}
|
||||
EVENT_HANDLER0(void, stop) {stop(false);}
|
||||
EVENT_HANDLER0(void, start) { start(false); }
|
||||
EVENT_HANDLER1(void, start, bool, wait) {
|
||||
PIThread::start(40);
|
||||
if (wait) waitForFinish();
|
||||
}
|
||||
EVENT_HANDLER0(void, stop) { stop(false); }
|
||||
EVENT_HANDLER1(void, stop, bool, clear);
|
||||
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void * , data);
|
||||
EVENT2(tileEvent, PIScreenTile * , tile, PIScreenTypes::TileEvent, e);
|
||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void waitForFinish()
|
||||
//! \brief block until finished (exit key will be pressed)
|
||||
@@ -91,9 +95,9 @@ public:
|
||||
//! \fn void stop(bool clear = false)
|
||||
//! \brief Stop console output and if "clear" clear the screen
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
||||
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
|
||||
@@ -101,7 +105,7 @@ public:
|
||||
//! \fn void tileEvent(PIScreenTile * tile, PIScreenTypes::TileEvent e)
|
||||
//! \brief Raise on some event "e" from tile "tile"
|
||||
|
||||
//! \}
|
||||
//! \}
|
||||
|
||||
private:
|
||||
class PIP_CONSOLE_EXPORT SystemConsole {
|
||||
@@ -131,7 +135,7 @@ private:
|
||||
PRIVATE_DECLARATION(PIP_CONSOLE_EXPORT)
|
||||
int width, height, pwidth, pheight;
|
||||
int mouse_x, mouse_y;
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > cells, pcells;
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> cells, pcells;
|
||||
};
|
||||
|
||||
void begin() override;
|
||||
@@ -140,10 +144,10 @@ private:
|
||||
void key_event(PIKbdListener::KeyEvent key);
|
||||
EVENT_HANDLER1(void, mouse_event, PIKbdListener::MouseEvent, me);
|
||||
EVENT_HANDLER1(void, wheel_event, PIKbdListener::WheelEvent, we);
|
||||
static void key_eventS(PIKbdListener::KeyEvent key, void * t) {((PIScreen*)t)->key_event(key);}
|
||||
PIVector<PIScreenTile*> tiles() {return root.children();}
|
||||
PIVector<PIScreenTile*> prepareMouse(PIKbdListener::MouseEvent * e);
|
||||
PIVector<PIScreenTile*> tilesUnderMouse(int x, int y);
|
||||
static void key_eventS(PIKbdListener::KeyEvent key, void * t) { ((PIScreen *)t)->key_event(key); }
|
||||
PIVector<PIScreenTile *> tiles() { return root.children(); }
|
||||
PIVector<PIScreenTile *> prepareMouse(PIKbdListener::MouseEvent * e);
|
||||
PIVector<PIScreenTile *> tilesUnderMouse(int x, int y);
|
||||
bool nextFocus(PIScreenTile * rt, PIKbdListener::KeyEvent key = PIKbdListener::KeyEvent());
|
||||
void tileEventInternal(PIScreenTile * t, PIScreenTypes::TileEvent e) override;
|
||||
void tileRemovedInternal(PIScreenTile * t) override;
|
||||
@@ -155,8 +159,7 @@ private:
|
||||
PIKbdListener * listener;
|
||||
PIKbdListener::KBFunc ret_func;
|
||||
PIScreenTile root;
|
||||
PIScreenTile * tile_focus, * tile_dialog;
|
||||
|
||||
PIScreenTile *tile_focus, *tile_dialog;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -35,10 +35,15 @@
|
||||
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
|
||||
public:
|
||||
TileVars(const PIString & n = PIString());
|
||||
|
||||
protected:
|
||||
struct PIP_CONSOLE_EXPORT Variable {
|
||||
Variable() {nx = ny = type = offset = bitFrom = bitCount = size = 0; format = PIScreenTypes::CellFormat(); ptr = 0;}
|
||||
bool isEmpty() const {return (ptr == 0);}
|
||||
Variable() {
|
||||
nx = ny = type = offset = bitFrom = bitCount = size = 0;
|
||||
format = PIScreenTypes::CellFormat();
|
||||
ptr = 0;
|
||||
}
|
||||
bool isEmpty() const { return (ptr == 0); }
|
||||
PIString name;
|
||||
PIScreenTypes::CellFormat format;
|
||||
int nx;
|
||||
@@ -69,9 +74,7 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreenConsoleTile : public PIScreenTile
|
||||
{
|
||||
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
|
||||
public:
|
||||
PIScreenConsoleTile();
|
||||
};
|
||||
|
||||
@@ -30,10 +30,10 @@
|
||||
#include "piscreentypes.h"
|
||||
#include "pistring.h"
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreenDrawer
|
||||
{
|
||||
class PIP_CONSOLE_EXPORT PIScreenDrawer {
|
||||
friend class PIScreen;
|
||||
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell> > & c);
|
||||
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
|
||||
|
||||
public:
|
||||
enum ArtChar {
|
||||
LineVertical = 1,
|
||||
@@ -48,24 +48,60 @@ public:
|
||||
};
|
||||
|
||||
void clear();
|
||||
void clearRect(int x0, int y0, int x1, int y1) {fillRect(x0, y0, x1, y1, ' ');}
|
||||
void drawPixel(int x, int y, const PIChar & c, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Default, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawLine(int x0, int y0, int x1, int y1, const PIChar & c, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Default, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawRect(int x0, int y0, int x1, int y1, const PIChar & c, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Default, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawFrame(int x0, int y0, int x1, int y1, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Default, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawText(int x, int y, const PIString & s, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Transparent, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void fillRect(int x0, int y0, int x1, int y1, const PIChar & c, PIScreenTypes::Color col_char = PIScreenTypes::Default, PIScreenTypes::Color col_back = PIScreenTypes::Default, PIScreenTypes::CharFlags flags_char = 0);
|
||||
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell> > & content);
|
||||
void clearRect(int x0, int y0, int x1, int y1) { fillRect(x0, y0, x1, y1, ' '); }
|
||||
void drawPixel(int x,
|
||||
int y,
|
||||
const PIChar & c,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawLine(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
int y1,
|
||||
const PIChar & c,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawRect(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
int y1,
|
||||
const PIChar & c,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawFrame(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
int y1,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void drawText(int x,
|
||||
int y,
|
||||
const PIString & s,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Transparent,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void fillRect(int x0,
|
||||
int y0,
|
||||
int x1,
|
||||
int y1,
|
||||
const PIChar & c,
|
||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||
PIScreenTypes::CharFlags flags_char = 0);
|
||||
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell>> & content);
|
||||
|
||||
PIChar artChar(const ArtChar type) const {return arts_.value(type, PIChar(' '));}
|
||||
PIChar artChar(const ArtChar type) const { return arts_.value(type, PIChar(' ')); }
|
||||
|
||||
static void clear(PIVector<PIVector<PIScreenTypes::Cell> > & cells);
|
||||
static void clear(PIVector<PIVector<PIScreenTypes::Cell>> & cells);
|
||||
|
||||
private:
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > & cells;
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> & cells;
|
||||
int width, height;
|
||||
PIMap<ArtChar, PIChar> arts_;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -26,36 +26,44 @@
|
||||
#ifndef PISCREENTILE_H
|
||||
#define PISCREENTILE_H
|
||||
|
||||
#include "pikbdlistener.h"
|
||||
#include "pip_console_export.h"
|
||||
#include "piscreentypes.h"
|
||||
#include "pikbdlistener.h"
|
||||
|
||||
class PIScreenDrawer;
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
|
||||
friend class PIScreen;
|
||||
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
|
||||
|
||||
public:
|
||||
PIScreenTile(const PIString & n = PIString(), PIScreenTypes::Direction d = PIScreenTypes::Vertical, PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
|
||||
PIScreenTile(const PIString & n = PIString(),
|
||||
PIScreenTypes::Direction d = PIScreenTypes::Vertical,
|
||||
PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
|
||||
virtual ~PIScreenTile();
|
||||
|
||||
void addTile(PIScreenTile * t);
|
||||
void takeTile(PIScreenTile * t);
|
||||
void removeTile(PIScreenTile * t);
|
||||
PIScreenTile * parentTile() const {return parent;}
|
||||
PIVector<PIScreenTile * > children(bool only_visible = false);
|
||||
PIScreenTile * parentTile() const { return parent; }
|
||||
PIVector<PIScreenTile *> children(bool only_visible = false);
|
||||
PIScreenTile * childUnderMouse(int x, int y);
|
||||
void show() {visible = true;}
|
||||
void hide() {visible = false;}
|
||||
void show() { visible = true; }
|
||||
void hide() { visible = false; }
|
||||
void setFocus();
|
||||
bool hasFocus() const {return has_focus;}
|
||||
void setMargins(int m) {marginLeft = marginRight = marginTop = marginBottom = m;}
|
||||
void setMargins(int l, int r, int t, int b) {marginLeft = l; marginRight = r; marginTop = t; marginBottom = b;}
|
||||
bool hasFocus() const { return has_focus; }
|
||||
void setMargins(int m) { marginLeft = marginRight = marginTop = marginBottom = m; }
|
||||
void setMargins(int l, int r, int t, int b) {
|
||||
marginLeft = l;
|
||||
marginRight = r;
|
||||
marginTop = t;
|
||||
marginBottom = b;
|
||||
}
|
||||
|
||||
int x() const {return x_;}
|
||||
int y() const {return y_;}
|
||||
int width() const {return width_;}
|
||||
int height() const {return height_;}
|
||||
int x() const { return x_; }
|
||||
int y() const { return y_; }
|
||||
int width() const { return width_; }
|
||||
int height() const { return height_; }
|
||||
|
||||
PIScreenTypes::Direction direction;
|
||||
PIScreenTypes::SizePolicy size_policy;
|
||||
@@ -69,7 +77,6 @@ public:
|
||||
bool visible;
|
||||
|
||||
protected:
|
||||
|
||||
//! Returns desired tile size in "w" and "h"
|
||||
virtual void sizeHint(int & w, int & h) const;
|
||||
|
||||
@@ -80,22 +87,22 @@ protected:
|
||||
virtual void drawEvent(PIScreenDrawer * d) {}
|
||||
|
||||
//! Return "true" if you process key
|
||||
virtual bool keyEvent(PIKbdListener::KeyEvent key) {return false;}
|
||||
virtual bool keyEvent(PIKbdListener::KeyEvent key) { return false; }
|
||||
|
||||
//! Return "true" if you process event
|
||||
virtual bool mouseEvent(PIKbdListener::MouseEvent me) {return false;}
|
||||
virtual bool mouseEvent(PIKbdListener::MouseEvent me) { return false; }
|
||||
|
||||
//! Return "true" if you process wheel
|
||||
virtual bool wheelEvent(PIKbdListener::WheelEvent we) {return false;}
|
||||
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
|
||||
|
||||
void raiseEvent(PIScreenTypes::TileEvent e);
|
||||
void setScreen(PIScreenTypes::PIScreenBase * s);
|
||||
void deleteChildren();
|
||||
void drawEventInternal(PIScreenDrawer * d);
|
||||
void layout();
|
||||
bool needLayout() {return size_policy != PIScreenTypes::Ignore;}
|
||||
bool needLayout() { return size_policy != PIScreenTypes::Ignore; }
|
||||
|
||||
PIVector<PIScreenTile * > tiles;
|
||||
PIVector<PIScreenTile *> tiles;
|
||||
PIScreenTile * parent;
|
||||
PIScreenTypes::PIScreenBase * screen;
|
||||
int x_, y_, width_, height_;
|
||||
@@ -103,7 +110,6 @@ protected:
|
||||
|
||||
private:
|
||||
int pw, ph;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile);
|
||||
|
||||
public:
|
||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
||||
TileSimple(const PIString & n = PIString());
|
||||
@@ -39,6 +40,7 @@ public:
|
||||
virtual ~TileSimple() {}
|
||||
PIVector<Row> content;
|
||||
PIScreenTypes::Alignment alignment;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
@@ -50,16 +52,18 @@ class TileList;
|
||||
class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile);
|
||||
friend class TileList;
|
||||
|
||||
public:
|
||||
TileScrollBar(const PIString & n = PIString());
|
||||
virtual ~TileScrollBar() {}
|
||||
void setMinimum(int v);
|
||||
void setMaximum(int v);
|
||||
void setValue(int v);
|
||||
int minimum() const {return minimum_;}
|
||||
int maximum() const {return maximum_;}
|
||||
int value() const {return value_;}
|
||||
int minimum() const { return minimum_; }
|
||||
int maximum() const { return maximum_; }
|
||||
int value() const { return value_; }
|
||||
int thickness;
|
||||
|
||||
protected:
|
||||
void _check();
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
@@ -72,6 +76,7 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileList, PIScreenTile);
|
||||
|
||||
public:
|
||||
enum SelectionMode {
|
||||
NoSelection,
|
||||
@@ -92,6 +97,7 @@ public:
|
||||
SelectionMode selection_mode;
|
||||
PISet<int> selected;
|
||||
int lhei, cur, offset;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void resizeEvent(int w, int h) override;
|
||||
@@ -106,6 +112,7 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileButton, PIScreenTile);
|
||||
|
||||
public:
|
||||
TileButton(const PIString & n = PIString());
|
||||
virtual ~TileButton() {}
|
||||
@@ -114,6 +121,7 @@ public:
|
||||
};
|
||||
PIScreenTypes::CellFormat format;
|
||||
PIString text;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
@@ -122,10 +130,9 @@ protected:
|
||||
};
|
||||
|
||||
|
||||
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile);
|
||||
|
||||
public:
|
||||
TileButtons(const PIString & n = PIString());
|
||||
virtual ~TileButtons() {}
|
||||
@@ -136,14 +143,15 @@ public:
|
||||
PIScreenTypes::Alignment alignment;
|
||||
PIVector<Button> content;
|
||||
int cur;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
bool keyEvent(PIKbdListener::KeyEvent key) override;
|
||||
bool mouseEvent(PIKbdListener::MouseEvent me) override;
|
||||
struct Rect {
|
||||
Rect(int _x0 = 0, int _y0 = 0, int _x1 = 0, int _y1 = 0): x0(_x0),y0(_y0),x1(_x1),y1(_y1) {}
|
||||
int x0,y0,x1,y1;
|
||||
Rect(int _x0 = 0, int _y0 = 0, int _x1 = 0, int _y1 = 0): x0(_x0), y0(_y0), x1(_x1), y1(_y1) {}
|
||||
int x0, y0, x1, y1;
|
||||
};
|
||||
PIVector<Rect> btn_rects;
|
||||
};
|
||||
@@ -151,6 +159,7 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile);
|
||||
|
||||
public:
|
||||
TileCheck(const PIString & n = PIString());
|
||||
virtual ~TileCheck() {}
|
||||
@@ -160,6 +169,7 @@ public:
|
||||
PIScreenTypes::CellFormat format;
|
||||
PIString text;
|
||||
bool toggled;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
@@ -170,6 +180,7 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile);
|
||||
|
||||
public:
|
||||
TileProgress(const PIString & n = PIString());
|
||||
virtual ~TileProgress() {}
|
||||
@@ -178,6 +189,7 @@ public:
|
||||
PIString suffix;
|
||||
double maximum;
|
||||
double value;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
@@ -186,11 +198,13 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
|
||||
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
|
||||
|
||||
public:
|
||||
TilePICout(const PIString & n = PIString());
|
||||
virtual ~TilePICout() {}
|
||||
PIScreenTypes::CellFormat format;
|
||||
int max_lines;
|
||||
|
||||
protected:
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
bool keyEvent(PIKbdListener::KeyEvent key) override;
|
||||
@@ -199,12 +213,14 @@ protected:
|
||||
|
||||
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
|
||||
|
||||
public:
|
||||
TileInput(const PIString & n = PIString());
|
||||
virtual ~TileInput() {}
|
||||
PIScreenTypes::CellFormat format;
|
||||
PIString text;
|
||||
int max_length;
|
||||
|
||||
protected:
|
||||
void sizeHint(int & w, int & h) const override;
|
||||
void drawEvent(PIScreenDrawer * d) override;
|
||||
|
||||
@@ -34,8 +34,8 @@ class PIScreenTile;
|
||||
|
||||
namespace PIScreenTypes {
|
||||
|
||||
//! Color for chars or background
|
||||
enum Color {
|
||||
//! Color for chars or background
|
||||
enum Color {
|
||||
Default /** Default */,
|
||||
Black /** Black */,
|
||||
Red /** Red */,
|
||||
@@ -46,39 +46,39 @@ namespace PIScreenTypes {
|
||||
Yellow /** Yellow */,
|
||||
White /** White */,
|
||||
Transparent /** Save previous color */
|
||||
};
|
||||
};
|
||||
|
||||
//! Flags for chars
|
||||
enum CharFlag {
|
||||
//! Flags for chars
|
||||
enum CharFlag {
|
||||
Bold /** Bold or bright */ = 0x1,
|
||||
Blink /** Blink text */ = 0x2,
|
||||
Underline /** Underline text */ = 0x4,
|
||||
Inverse = 0x08
|
||||
};
|
||||
};
|
||||
|
||||
//! Alignment
|
||||
enum Alignment {
|
||||
Left /** Left */ ,
|
||||
Center /** Center */ ,
|
||||
//! Alignment
|
||||
enum Alignment {
|
||||
Left /** Left */,
|
||||
Center /** Center */,
|
||||
Right /** Right */
|
||||
};
|
||||
};
|
||||
|
||||
//! Size policy
|
||||
enum SizePolicy {
|
||||
Fixed /** Fixed size */ ,
|
||||
Preferred /** Preferred size */ ,
|
||||
Expanding /** Maximum available size */ ,
|
||||
//! Size policy
|
||||
enum SizePolicy {
|
||||
Fixed /** Fixed size */,
|
||||
Preferred /** Preferred size */,
|
||||
Expanding /** Maximum available size */,
|
||||
Ignore /** Ignore layout logic */
|
||||
};
|
||||
};
|
||||
|
||||
//! Direction
|
||||
enum Direction {
|
||||
Horizontal /** Horizontal */ ,
|
||||
//! Direction
|
||||
enum Direction {
|
||||
Horizontal /** Horizontal */,
|
||||
Vertical /** Vertical */
|
||||
};
|
||||
};
|
||||
|
||||
//! Focus flags
|
||||
enum FocusFlag {
|
||||
//! Focus flags
|
||||
enum FocusFlag {
|
||||
CanHasFocus /** Tile can has focus */ = 0x1,
|
||||
NextByTab /** Focus passed to next tile by tab key */ = 0x2,
|
||||
NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4,
|
||||
@@ -87,13 +87,13 @@ namespace PIScreenTypes {
|
||||
FocusOnMouse /** Tile focused on mouse press */ = 0x10,
|
||||
FocusOnWheel /** Tile focused on wheel */ = 0x20,
|
||||
FocusOnMouseOrWheel /** Tile focused on mouse press or wheel */ = FocusOnMouse | FocusOnWheel
|
||||
};
|
||||
};
|
||||
|
||||
typedef PIFlags<CharFlag> CharFlags;
|
||||
typedef PIFlags<FocusFlag> FocusFlags;
|
||||
typedef PIFlags<CharFlag> CharFlags;
|
||||
typedef PIFlags<FocusFlag> FocusFlags;
|
||||
|
||||
union PIP_CONSOLE_EXPORT CellFormat {
|
||||
CellFormat(ushort f = 0) {raw_format = f;}
|
||||
union PIP_CONSOLE_EXPORT CellFormat {
|
||||
CellFormat(ushort f = 0) { raw_format = f; }
|
||||
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
|
||||
color_char = col_char;
|
||||
color_back = col_back;
|
||||
@@ -101,71 +101,87 @@ namespace PIScreenTypes {
|
||||
}
|
||||
ushort raw_format;
|
||||
struct {
|
||||
ushort color_char : 4;
|
||||
ushort color_back : 4;
|
||||
ushort color_char: 4;
|
||||
ushort color_back: 4;
|
||||
ushort flags : 8;
|
||||
};
|
||||
bool operator ==(const CellFormat & c) const {return raw_format == c.raw_format;}
|
||||
bool operator !=(const CellFormat & c) const {return raw_format != c.raw_format;}
|
||||
};
|
||||
bool operator==(const CellFormat & c) const { return raw_format == c.raw_format; }
|
||||
bool operator!=(const CellFormat & c) const { return raw_format != c.raw_format; }
|
||||
};
|
||||
|
||||
struct PIP_CONSOLE_EXPORT Cell {
|
||||
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {symbol = c; format = f;}
|
||||
struct PIP_CONSOLE_EXPORT Cell {
|
||||
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {
|
||||
symbol = c;
|
||||
format = f;
|
||||
}
|
||||
CellFormat format;
|
||||
PIChar symbol;
|
||||
bool operator ==(const Cell & c) const {return format == c.format && symbol == c.symbol;}
|
||||
bool operator !=(const Cell & c) const {return format != c.format || symbol != c.symbol;}
|
||||
Cell & operator =(const Cell & c) {
|
||||
bool operator==(const Cell & c) const { return format == c.format && symbol == c.symbol; }
|
||||
bool operator!=(const Cell & c) const { return format != c.format || symbol != c.symbol; }
|
||||
Cell & operator=(const Cell & c) {
|
||||
symbol = c.symbol;
|
||||
if (c.format.color_back == Transparent) {
|
||||
format.color_char = c.format.color_char;
|
||||
format.flags = c.format.flags;
|
||||
} else format = c.format;
|
||||
} else
|
||||
format = c.format;
|
||||
return *this;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
struct PIP_CONSOLE_EXPORT TileEvent {
|
||||
struct PIP_CONSOLE_EXPORT TileEvent {
|
||||
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
|
||||
int type;
|
||||
PIVariant data;
|
||||
};
|
||||
};
|
||||
|
||||
class PIP_CONSOLE_EXPORT PIScreenBase {
|
||||
public:
|
||||
class PIP_CONSOLE_EXPORT PIScreenBase {
|
||||
public:
|
||||
PIScreenBase() {}
|
||||
virtual ~PIScreenBase() {}
|
||||
virtual void tileEventInternal(PIScreenTile * , TileEvent) {}
|
||||
virtual void tileRemovedInternal(PIScreenTile * ) {}
|
||||
virtual void tileSetFocusInternal(PIScreenTile * ) {}
|
||||
};
|
||||
virtual void tileEventInternal(PIScreenTile *, TileEvent) {}
|
||||
virtual void tileRemovedInternal(PIScreenTile *) {}
|
||||
virtual void tileSetFocusInternal(PIScreenTile *) {}
|
||||
};
|
||||
|
||||
} // namespace PIScreenTypes
|
||||
|
||||
|
||||
// inline PIByteArray & operator <<(PIByteArray & s, const PIScreenTypes::Cell & v) {s << v.format.raw_format << v.symbol; return s;}
|
||||
// inline PIByteArray & operator >>(PIByteArray & s, PIScreenTypes::Cell & v) {s >> v.format.raw_format >> v.symbol; return s;}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
BINARY_STREAM_WRITE(PIScreenTypes::Cell) {
|
||||
s << v.format.raw_format << v.symbol;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
BINARY_STREAM_READ(PIScreenTypes::Cell) {
|
||||
s >> v.format.raw_format >> v.symbol;
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
//inline PIByteArray & operator <<(PIByteArray & s, const PIScreenTypes::Cell & v) {s << v.format.raw_format << v.symbol; return s;}
|
||||
//inline PIByteArray & operator >>(PIByteArray & s, PIScreenTypes::Cell & v) {s >> v.format.raw_format >> v.symbol; return s;}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
BINARY_STREAM_WRITE(PIScreenTypes::Cell) {s << v.format.raw_format << v.symbol; return s;}
|
||||
BINARY_STREAM_WRITE(PIScreenTypes::TileEvent) {
|
||||
s << v.type << v.data;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
BINARY_STREAM_READ (PIScreenTypes::Cell) {s >> v.format.raw_format >> v.symbol; return s;}
|
||||
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Store operator
|
||||
//! \~russian Оператор сохранения
|
||||
BINARY_STREAM_WRITE(PIScreenTypes::TileEvent) {s << v.type << v.data; return s;}
|
||||
|
||||
//! \relatesalso PIBinaryStream
|
||||
//! \~english Restore operator
|
||||
//! \~russian Оператор извлечения
|
||||
BINARY_STREAM_READ (PIScreenTypes::TileEvent) {s >> v.type >> v.data; return s;}
|
||||
BINARY_STREAM_READ(PIScreenTypes::TileEvent) {
|
||||
s >> v.type >> v.data;
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
REGISTER_PIVARIANTSIMPLE(PIScreenTypes::TileEvent)
|
||||
|
||||
@@ -26,33 +26,33 @@
|
||||
#ifndef PITERMINAL_H
|
||||
#define PITERMINAL_H
|
||||
|
||||
#include "pip_console_export.h"
|
||||
#include "pikbdlistener.h"
|
||||
#include "pip_console_export.h"
|
||||
#include "piscreentypes.h"
|
||||
|
||||
|
||||
class PIP_CONSOLE_EXPORT PITerminal: public PIThread
|
||||
{
|
||||
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PITerminal, PIThread);
|
||||
public:
|
||||
|
||||
public:
|
||||
//! Constructs %PITerminal
|
||||
PITerminal();
|
||||
|
||||
~PITerminal();
|
||||
|
||||
int columns() const {return size_x;}
|
||||
int rows() const {return size_y;}
|
||||
int columns() const { return size_x; }
|
||||
int rows() const { return size_y; }
|
||||
bool resize(int cols, int rows);
|
||||
|
||||
void write(const PIByteArray & d);
|
||||
void write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m);
|
||||
void write(PIKbdListener::KeyEvent ke);
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > content();
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> content();
|
||||
static bool isSpecialKey(int k);
|
||||
|
||||
bool initialize();
|
||||
void destroy();
|
||||
|
||||
private:
|
||||
void initPrivate();
|
||||
void readConsole();
|
||||
@@ -72,8 +72,7 @@ private:
|
||||
int size_x, size_y, cursor_x, cursor_y;
|
||||
bool cursor_blink, cursor_visible;
|
||||
PITimeMeasurer cursor_tm;
|
||||
PIVector<PIVector<PIScreenTypes::Cell> > cells;
|
||||
|
||||
PIVector<PIVector<PIScreenTypes::Cell>> cells;
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -29,6 +29,6 @@ size_t _PIContainerConstantsBase::calcMinCountPoT(size_t szof) {
|
||||
elc *= 2;
|
||||
++ret;
|
||||
}
|
||||
//printf("calcMinCount sizeof = %d, min_count = %d, pot = %d\n", szof, elc, ret);
|
||||
// printf("calcMinCount sizeof = %d, min_count = %d, pot = %d\n", szof, elc, ret);
|
||||
return ret;
|
||||
}
|
||||
|
||||
@@ -41,23 +41,24 @@
|
||||
#else
|
||||
# include <malloc.h>
|
||||
#endif
|
||||
#include <initializer_list>
|
||||
#include <type_traits>
|
||||
#include <string.h>
|
||||
#include <new>
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <initializer_list>
|
||||
#include <new>
|
||||
#include <string.h>
|
||||
#include <type_traits>
|
||||
|
||||
|
||||
template <typename C>
|
||||
template<typename C>
|
||||
class _PIReverseWrapper {
|
||||
public:
|
||||
_PIReverseWrapper(C & c): c_(c) {}
|
||||
_PIReverseWrapper(const C & c): c_(const_cast<C&>(c)) {}
|
||||
typename C::reverse_iterator begin() {return c_.rbegin();}
|
||||
typename C::reverse_iterator end() {return c_.rend(); }
|
||||
typename C::const_reverse_iterator begin() const {return c_.rbegin();}
|
||||
typename C::const_reverse_iterator end() const {return c_.rend(); }
|
||||
_PIReverseWrapper(const C & c): c_(const_cast<C &>(c)) {}
|
||||
typename C::reverse_iterator begin() { return c_.rbegin(); }
|
||||
typename C::reverse_iterator end() { return c_.rend(); }
|
||||
typename C::const_reverse_iterator begin() const { return c_.rbegin(); }
|
||||
typename C::const_reverse_iterator end() const { return c_.rend(); }
|
||||
|
||||
private:
|
||||
C & c_;
|
||||
};
|
||||
@@ -71,15 +72,24 @@ public:
|
||||
template<typename T>
|
||||
class _PIContainerConstants {
|
||||
public:
|
||||
static size_t minCountPoT() {static size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T)); return ret;}
|
||||
static size_t minCountPoT() {
|
||||
static size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Template reverse wrapper over any container
|
||||
//! \~russian Шаблонная функция обертки любого контейнера для обратного доступа через итераторы
|
||||
template <typename C> _PIReverseWrapper<C> PIReverseWrap(C & c) {return _PIReverseWrapper<C>(c);}
|
||||
template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _PIReverseWrapper<C>(c);}
|
||||
template<typename C>
|
||||
_PIReverseWrapper<C> PIReverseWrap(C & c) {
|
||||
return _PIReverseWrapper<C>(c);
|
||||
}
|
||||
template<typename C>
|
||||
_PIReverseWrapper<C> PIReverseWrap(const C & c) {
|
||||
return _PIReverseWrapper<C>(c);
|
||||
}
|
||||
|
||||
|
||||
//! \brief
|
||||
@@ -88,7 +98,7 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! \~\param c
|
||||
//! \~english Iteration times in loop
|
||||
//! \~russian Количество итераций цикла
|
||||
#define piForTimes(c) for(int _i##c = 0; _i##c < c; ++_i##c)
|
||||
#define piForTimes(c) for (int _i##c = 0; _i##c < c; ++_i##c)
|
||||
|
||||
|
||||
//! \brief
|
||||
@@ -120,7 +130,7 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! // 4
|
||||
//! \endcode
|
||||
//! \sa \a piForeachC, \a piForeachR, \a piForeachRC
|
||||
#define piForeach(i, c) for(i : c)
|
||||
#define piForeach(i, c) for (i: c)
|
||||
|
||||
//! \brief
|
||||
//! \~english Macro for iterate any container
|
||||
@@ -136,7 +146,7 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! \~russian Перебор всех элементов контейнера с доступом только на чтение.
|
||||
//! Перебор осуществляется в прямом порядке.
|
||||
//! \~ \sa \a piForeach, \a piForeachR, \a piForeachRC
|
||||
#define piForeachC(i, c) for(const i : c)
|
||||
#define piForeachC(i, c) for (const i: c)
|
||||
|
||||
//! \brief
|
||||
//! \~english Macro for iterate any container
|
||||
@@ -152,7 +162,7 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! \~russian Перебор всех элементов контейнера с доступом на чтение и запись.
|
||||
//! Перебор осуществляется в обратном порядке.
|
||||
//! \~ \sa \a piForeach, \a piForeachC, \a piForeachRC
|
||||
#define piForeachR(i, c) for(i : PIReverseWrap(c))
|
||||
#define piForeachR(i, c) for (i: PIReverseWrap(c))
|
||||
|
||||
//! \brief
|
||||
//! \~english Macro for iterate any container
|
||||
@@ -168,7 +178,7 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! \~russian Перебор всех элементов контейнера с доступом только на чтение.
|
||||
//! Перебор осуществляется в обратном порядке. Также можно писать **piForeachCR**
|
||||
//! \~ \sa \a piForeach, \a piForeachC, \a piForeachR
|
||||
#define piForeachRC(i, c) for(const i : PIReverseWrap(c))
|
||||
#define piForeachRC(i, c) for (const i: PIReverseWrap(c))
|
||||
#define piForeachCR piForeachRC
|
||||
|
||||
|
||||
@@ -177,7 +187,9 @@ template <typename C> _PIReverseWrapper<C> PIReverseWrap(const C & c) {return _P
|
||||
//! \~russian Порядок обхода для функции изменения размерности reshape().
|
||||
//! \~ \sa \a PIVector::reshape(), \a PIDeque::reshape()
|
||||
enum ReshapeOrder {
|
||||
ReshapeByRow /*! \~english Traversing elements by line, just as they stay in memory \~russian Обход элементов построчно, так же как они находятся в памяти */,
|
||||
ReshapeByRow /*! \~english Traversing elements by line, just as they stay in memory \~russian Обход элементов построчно, так же как они
|
||||
находятся в памяти */
|
||||
,
|
||||
ReshapeByColumn /*! \~english Traversing elements by column \~russian Обход элементов по столбцам */,
|
||||
};
|
||||
|
||||
|
||||
@@ -180,12 +180,12 @@
|
||||
#ifndef PICONTAINERSMODULE_H
|
||||
#define PICONTAINERSMODULE_H
|
||||
|
||||
#include "pivector.h"
|
||||
#include "pideque.h"
|
||||
#include "pimap.h"
|
||||
#include "piqueue.h"
|
||||
#include "piset.h"
|
||||
#include "pistack.h"
|
||||
#include "pivector.h"
|
||||
#include "pivector2d.h"
|
||||
|
||||
|
||||
|
||||
@@ -114,22 +114,20 @@
|
||||
//! - Вставка и удаление элементов — линейная по расстоянию до конца массива 𝓞(n)
|
||||
//!
|
||||
//! \~\sa \a PIVector, \a PIMap
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
class PIDeque {
|
||||
public:
|
||||
typedef bool (*CompareFunc)(const T & , const T & );
|
||||
typedef bool (*CompareFunc)(const T &, const T &);
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef const T* const_pointer;
|
||||
typedef T& reference;
|
||||
typedef const T& const_reference;
|
||||
typedef T * pointer;
|
||||
typedef const T * const_pointer;
|
||||
typedef T & reference;
|
||||
typedef const T & const_reference;
|
||||
typedef size_t size_type;
|
||||
|
||||
//! \~english Constructs an empty array.
|
||||
//! \~russian Создает пустой массив.
|
||||
inline PIDeque() {
|
||||
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
|
||||
}
|
||||
inline PIDeque() { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) }
|
||||
|
||||
//! \~english Copy constructor.
|
||||
//! \~russian Копирующий конструктор.
|
||||
@@ -209,7 +207,7 @@ public:
|
||||
|
||||
//! \~english Assign operator.
|
||||
//! \~russian Оператор присваивания.
|
||||
inline PIDeque<T> & operator =(const PIDeque<T> & other) {
|
||||
inline PIDeque<T> & operator=(const PIDeque<T> & other) {
|
||||
if (this == &other) return *this;
|
||||
clear();
|
||||
alloc_forward(other.pid_size);
|
||||
@@ -219,360 +217,330 @@ public:
|
||||
|
||||
//! \~english Assign move operator.
|
||||
//! \~russian Оператор перемещающего присваивания.
|
||||
inline PIDeque<T> & operator =(PIDeque<T> && other) {
|
||||
inline PIDeque<T> & operator=(PIDeque<T> && other) {
|
||||
swap(other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
class iterator {
|
||||
friend class PIDeque<T>;
|
||||
|
||||
private:
|
||||
inline iterator(PIDeque<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
PIDeque<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline T & operator *() {return (*parent)[pos];}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline T & operator ->() {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline T & operator*() { return (*parent)[pos]; }
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline T & operator->() { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline iterator & operator ++() {
|
||||
inline iterator & operator++() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator operator ++(int) {
|
||||
inline iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
inline iterator & operator --() {
|
||||
inline iterator & operator--() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator operator --(int) {
|
||||
inline iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline iterator & operator +=(const iterator & it) {
|
||||
inline iterator & operator+=(const iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator +=(size_t p) {
|
||||
inline iterator & operator+=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator -=(const iterator & it) {
|
||||
inline iterator & operator-=(const iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator -=(size_t p) {
|
||||
inline iterator & operator-=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline iterator operator -(size_t p, const iterator & it) {return it - p;}
|
||||
friend inline iterator operator -(const iterator & it, size_t p) {
|
||||
friend inline iterator operator-(size_t p, const iterator & it) { return it - p; }
|
||||
friend inline iterator operator-(const iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos - it2.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const iterator & it1, const iterator & it2) { return it1.pos - it2.pos; }
|
||||
|
||||
friend inline iterator operator +(size_t p, const iterator & it) {return it + p;}
|
||||
friend inline iterator operator +(const iterator & it, size_t p) {
|
||||
friend inline iterator operator+(size_t p, const iterator & it) { return it + p; }
|
||||
friend inline iterator operator+(const iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const iterator & it1, const iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const iterator & it1, const iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const iterator & it1, const iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const iterator & it1, const iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class const_iterator {
|
||||
friend class PIDeque<T>;
|
||||
|
||||
private:
|
||||
inline const_iterator(const PIDeque<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIDeque<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline const_iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline const_iterator & operator ++() {
|
||||
inline const_iterator & operator++() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator operator ++(int) {
|
||||
inline const_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
inline const_iterator & operator --() {
|
||||
inline const_iterator & operator--() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator operator --(int) {
|
||||
inline const_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline const_iterator & operator +=(const const_iterator & it) {
|
||||
inline const_iterator & operator+=(const const_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator +=(size_t p) {
|
||||
inline const_iterator & operator+=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator -=(const const_iterator & it) {
|
||||
inline const_iterator & operator-=(const const_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator -=(size_t p) {
|
||||
inline const_iterator & operator-=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline const_iterator operator -(size_t p, const const_iterator & it) {return it - p;}
|
||||
friend inline const_iterator operator -(const const_iterator & it, size_t p) {
|
||||
friend inline const_iterator operator-(size_t p, const const_iterator & it) { return it - p; }
|
||||
friend inline const_iterator operator-(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos - it2.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; }
|
||||
|
||||
friend inline const_iterator operator +(size_t p, const const_iterator & it) {return it + p;}
|
||||
friend inline const_iterator operator +(const const_iterator & it, size_t p) {
|
||||
friend inline const_iterator operator+(size_t p, const const_iterator & it) { return it + p; }
|
||||
friend inline const_iterator operator+(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const const_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const const_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class reverse_iterator {
|
||||
friend class PIDeque<T>;
|
||||
|
||||
private:
|
||||
inline reverse_iterator(PIDeque<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
PIDeque<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline reverse_iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline T & operator *() {return (*parent)[pos];}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline T & operator ->() {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline T & operator*() { return (*parent)[pos]; }
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline T & operator->() { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline reverse_iterator & operator ++() {
|
||||
inline reverse_iterator & operator++() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator operator ++(int) {
|
||||
inline reverse_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
inline reverse_iterator & operator --() {
|
||||
inline reverse_iterator & operator--() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator operator --(int) {
|
||||
inline reverse_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline reverse_iterator & operator +=(const reverse_iterator & it) {
|
||||
inline reverse_iterator & operator+=(const reverse_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator +=(size_t p) {
|
||||
inline reverse_iterator & operator+=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator -=(const reverse_iterator & it) {
|
||||
inline reverse_iterator & operator-=(const reverse_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator -=(size_t p) {
|
||||
inline reverse_iterator & operator-=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline reverse_iterator operator -(size_t p, const reverse_iterator & it) {return it - p;}
|
||||
friend inline reverse_iterator operator -(const reverse_iterator & it, size_t p) {
|
||||
friend inline reverse_iterator operator-(size_t p, const reverse_iterator & it) { return it - p; }
|
||||
friend inline reverse_iterator operator-(const reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it2.pos - it1.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const reverse_iterator & it1, const reverse_iterator & it2) { return it2.pos - it1.pos; }
|
||||
|
||||
friend inline reverse_iterator operator +(size_t p, const reverse_iterator & it) {return it + p;}
|
||||
friend inline reverse_iterator operator +(const reverse_iterator & it, size_t p) {
|
||||
friend inline reverse_iterator operator+(size_t p, const reverse_iterator & it) { return it + p; }
|
||||
friend inline reverse_iterator operator+(const reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const reverse_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const reverse_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const reverse_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const reverse_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class const_reverse_iterator {
|
||||
friend class PIDeque<T>;
|
||||
|
||||
private:
|
||||
inline const_reverse_iterator(const PIDeque<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIDeque<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline const_reverse_iterator(): parent(0), pos(0) {}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline const_reverse_iterator & operator ++() {
|
||||
inline const_reverse_iterator & operator++() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator operator ++(int) {
|
||||
inline const_reverse_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
inline const_reverse_iterator & operator --() {
|
||||
inline const_reverse_iterator & operator--() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator operator --(int) {
|
||||
inline const_reverse_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline const_reverse_iterator & operator +=(const const_reverse_iterator & it) {
|
||||
inline const_reverse_iterator & operator+=(const const_reverse_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator +=(size_t p) {
|
||||
inline const_reverse_iterator & operator+=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator -=(const const_reverse_iterator & it) {
|
||||
inline const_reverse_iterator & operator-=(const const_reverse_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator -=(size_t p) {
|
||||
inline const_reverse_iterator & operator-=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline const_reverse_iterator operator -(size_t p, const const_reverse_iterator & it) {return it - p;}
|
||||
friend inline const_reverse_iterator operator -(const const_reverse_iterator & it, size_t p) {
|
||||
friend inline const_reverse_iterator operator-(size_t p, const const_reverse_iterator & it) { return it - p; }
|
||||
friend inline const_reverse_iterator operator-(const const_reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
friend inline std::ptrdiff_t operator-(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it2.pos - it1.pos;
|
||||
}
|
||||
|
||||
friend inline const_reverse_iterator operator +(size_t p, const const_reverse_iterator & it) {return it + p;}
|
||||
friend inline const_reverse_iterator operator +(const const_reverse_iterator & it, size_t p) {
|
||||
friend inline const_reverse_iterator operator+(size_t p, const const_reverse_iterator & it) { return it + p; }
|
||||
friend inline const_reverse_iterator operator+(const const_reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const const_reverse_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const const_reverse_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const const_reverse_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const const_reverse_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
|
||||
@@ -584,7 +552,7 @@ public:
|
||||
//! \~russian Если массив - пуст, возвращаемый итератор будет равен \a end().
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a end(), \a rbegin(), \a rend()
|
||||
inline iterator begin() {return iterator(this, 0);}
|
||||
inline iterator begin() { return iterator(this, 0); }
|
||||
|
||||
//! \~english Iterator to the element following the last element.
|
||||
//! \~russian Итератор на элемент, следующий за последним элементом.
|
||||
@@ -596,10 +564,10 @@ public:
|
||||
//! попытка доступа к нему приведёт к выходу за разрешенную память.
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a begin(), \a rbegin(), \a rend()
|
||||
inline iterator end() {return iterator(this, pid_size);}
|
||||
inline iterator end() { return iterator(this, pid_size); }
|
||||
|
||||
inline const_iterator begin() const {return const_iterator(this, 0); }
|
||||
inline const_iterator end() const {return const_iterator(this, pid_size);}
|
||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||
inline const_iterator end() const { return const_iterator(this, pid_size); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the first element of the reversed array.
|
||||
//! \~russian Обратный итератор на первый элемент.
|
||||
@@ -612,7 +580,7 @@ public:
|
||||
//! Если массив пустой, то совпадает с итератором \a rend().
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a rend(), \a begin(), \a end()
|
||||
inline reverse_iterator rbegin() {return reverse_iterator(this, pid_size - 1);}
|
||||
inline reverse_iterator rbegin() { return reverse_iterator(this, pid_size - 1); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the element.
|
||||
//! following the last element of the reversed array.
|
||||
@@ -628,25 +596,25 @@ public:
|
||||
//! попытка доступа к нему приведёт к выходу за разрешенную память.
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a rbegin(), \a begin(), \a end()
|
||||
inline reverse_iterator rend() {return reverse_iterator(this, -1);}
|
||||
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
||||
|
||||
inline const_reverse_iterator rbegin() const {return const_reverse_iterator(this, pid_size - 1);}
|
||||
inline const_reverse_iterator rend() const {return const_reverse_iterator(this, -1);}
|
||||
inline const_reverse_iterator rbegin() const { return const_reverse_iterator(this, pid_size - 1); }
|
||||
inline const_reverse_iterator rend() const { return const_reverse_iterator(this, -1); }
|
||||
|
||||
//! \~english Number of elements in the container.
|
||||
//! \~russian Количество элементов массива.
|
||||
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t size() const {return pid_size;}
|
||||
inline size_t size() const { return pid_size; }
|
||||
|
||||
//! \~english Number of elements in the container as signed value.
|
||||
//! \~russian Количество элементов массива в виде знакового числа.
|
||||
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline ssize_t size_s() const {return pid_size;}
|
||||
inline ssize_t size_s() const { return pid_size; }
|
||||
|
||||
//! \~english Same as \a size().
|
||||
//! \~russian Синоним \a size().
|
||||
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t length() const {return pid_size;}
|
||||
inline size_t length() const { return pid_size; }
|
||||
|
||||
//! \~english Number of elements that the container has currently allocated space for.
|
||||
//! \~russian Количество элементов, для которого сейчас выделена память массивом.
|
||||
@@ -654,9 +622,9 @@ public:
|
||||
//! \~english To find out the actual number of items, use the function \a size().
|
||||
//! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size().
|
||||
//! \~\sa \a reserve(), \a size(), \a size_s()
|
||||
inline size_t capacity() const {return pid_rsize;}
|
||||
inline size_t capacity() const { return pid_rsize; }
|
||||
|
||||
inline size_t _start() const {return pid_start;}
|
||||
inline size_t _start() const { return pid_start; }
|
||||
|
||||
//! \~english Checks if the container has no elements.
|
||||
//! \~russian Проверяет пуст ли массив.
|
||||
@@ -664,7 +632,7 @@ public:
|
||||
//! \~english **true** if the container is empty, **false** otherwise
|
||||
//! \~russian **true** если массив пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isEmpty() const {return (pid_size == 0);}
|
||||
inline bool isEmpty() const { return (pid_size == 0); }
|
||||
|
||||
//! \~english Checks if the container has elements.
|
||||
//! \~russian Проверяет не пуст ли массив.
|
||||
@@ -672,7 +640,7 @@ public:
|
||||
//! \~english **true** if the container is not empty, **false** otherwise
|
||||
//! \~russian **true** если массив не пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isNotEmpty() const {return (pid_size > 0);}
|
||||
inline bool isNotEmpty() const { return (pid_size > 0); }
|
||||
|
||||
//! \~english Tests whether at least one element in the array
|
||||
//! passes the test implemented by the provided function `test`.
|
||||
@@ -740,8 +708,8 @@ public:
|
||||
//! piCout << v; // {1, 2, 5, 9}
|
||||
//! \endcode
|
||||
//! \~\sa \a at()
|
||||
inline T & operator [](size_t index) {return pid_data[pid_start + index];}
|
||||
inline const T & operator [](size_t index) const {return pid_data[pid_start + index];}
|
||||
inline T & operator[](size_t index) { return pid_data[pid_start + index]; }
|
||||
inline const T & operator[](size_t index) const { return pid_data[pid_start + index]; }
|
||||
|
||||
//! \~english Read only access to element by `index`.
|
||||
//! \~russian Доступ исключительно на чтение к элементу по индексу `index`.
|
||||
@@ -752,7 +720,7 @@ public:
|
||||
//! \~russian Индекс элемента считается от `0`.
|
||||
//! Индекс элемента должен лежать в пределах от `0` до `size()-1`.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline const T & at(size_t index) const {return pid_data[pid_start + index];}
|
||||
inline const T & at(size_t index) const { return pid_data[pid_start + index]; }
|
||||
|
||||
//! \~english Returns the first element of the array that
|
||||
//! passes the test implemented by the provided function `test`
|
||||
@@ -762,8 +730,10 @@ public:
|
||||
//! \~\sa \a indexWhere()
|
||||
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
|
||||
ssize_t i = indexWhere(test, start);
|
||||
if (i < 0) return def;
|
||||
else return at(i);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
return at(i);
|
||||
}
|
||||
|
||||
//! \~english Returns the last element of the array that
|
||||
@@ -774,8 +744,10 @@ public:
|
||||
//! \~\sa \a lastIndexWhere()
|
||||
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
|
||||
ssize_t i = lastIndexWhere(test, start);
|
||||
if (i < 0) return def;
|
||||
else return at(i);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
return at(i);
|
||||
}
|
||||
|
||||
//! \~english Last element.
|
||||
@@ -787,8 +759,8 @@ public:
|
||||
//! \~russian Возвращает ссылку на последний элемент в массиве.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline T & back() {return pid_data[pid_start + pid_size - 1];}
|
||||
inline const T & back() const {return pid_data[pid_start + pid_size - 1];}
|
||||
inline T & back() { return pid_data[pid_start + pid_size - 1]; }
|
||||
inline const T & back() const { return pid_data[pid_start + pid_size - 1]; }
|
||||
|
||||
//! \~english Last element.
|
||||
//! \~russian Первый элемент массива.
|
||||
@@ -799,12 +771,12 @@ public:
|
||||
//! \~russian Возвращает ссылку на пенрвый элемент в массиве.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline T & front() {return pid_data[pid_start];}
|
||||
inline const T & front() const {return pid_data[pid_start];}
|
||||
inline T & front() { return pid_data[pid_start]; }
|
||||
inline const T & front() const { return pid_data[pid_start]; }
|
||||
|
||||
//! \~english Compare operator with array `v`.
|
||||
//! \~russian Оператор сравнения с массивом `v`.
|
||||
inline bool operator ==(const PIDeque<T> & v) const {
|
||||
inline bool operator==(const PIDeque<T> & v) const {
|
||||
if (pid_size != v.pid_size) return false;
|
||||
for (size_t i = 0; i < pid_size; ++i) {
|
||||
if (v[i] != (*this)[i]) return false;
|
||||
@@ -814,7 +786,7 @@ public:
|
||||
|
||||
//! \~english Compare operator with array `v`.
|
||||
//! \~russian Оператор сравнения с массивом `v`.
|
||||
inline bool operator !=(const PIDeque<T> & v) const {return !(*this == v);}
|
||||
inline bool operator!=(const PIDeque<T> & v) const { return !(*this == v); }
|
||||
|
||||
//! \~english Tests if element `e` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента `e` в массиве.
|
||||
@@ -873,7 +845,7 @@ public:
|
||||
start = pid_size + start;
|
||||
if (start < 0) start = 0;
|
||||
}
|
||||
for (const T & e : v) {
|
||||
for (const T & e: v) {
|
||||
bool c = false;
|
||||
for (size_t i = pid_start + size_t(start); i < pid_start + pid_size; ++i) {
|
||||
if (e == pid_data[i]) {
|
||||
@@ -1134,7 +1106,7 @@ public:
|
||||
//! memcpy(vec.data(1), a, 2 * sizeof(int));
|
||||
//! piCout << v; // {2, 12, 13, 2}
|
||||
//! \endcode
|
||||
inline T * data(size_t index = 0) {return &(pid_data[pid_start + index]);}
|
||||
inline T * data(size_t index = 0) { return &(pid_data[pid_start + index]); }
|
||||
|
||||
//! \~english Read only pointer to array
|
||||
//! \~russian Указатель на память массива только для чтения.
|
||||
@@ -1153,7 +1125,7 @@ public:
|
||||
//! memcpy(a, v.data(), a.size() * sizeof(int));
|
||||
//! piCout << a[0] << a[1] << a[2]; // 1 3 5
|
||||
//! \endcode
|
||||
inline const T * data(size_t index = 0) const {return &(pid_data[pid_start + index]);}
|
||||
inline const T * data(size_t index = 0) const { return &(pid_data[pid_start + index]); }
|
||||
|
||||
//! \~english Creates sub-array of this array.
|
||||
//! \~russian Создает подмассив, то есть кусок из текущего массива.
|
||||
@@ -1184,18 +1156,14 @@ public:
|
||||
//! \~english Reserved memory will not be released.
|
||||
//! \~russian Зарезервированная память не освободится.
|
||||
//! \~\sa \a resize()
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIDeque<T> & clear() {
|
||||
deleteT(pid_data + pid_start, pid_size);
|
||||
pid_size = 0;
|
||||
pid_start = (pid_rsize - pid_size) / 2;
|
||||
return *this;
|
||||
}
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIDeque<T> & clear() {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, pid_size)
|
||||
pid_size = 0;
|
||||
@@ -1242,21 +1210,17 @@ public:
|
||||
//! \~english Same as \a fill().
|
||||
//! \~russian Тоже самое что и \a fill().
|
||||
//! \~\sa \a fill(), \a resize()
|
||||
inline PIDeque<T> & assign(const T & e = T()) {return fill(e);}
|
||||
inline PIDeque<T> & assign(const T & e = T()) { return fill(e); }
|
||||
|
||||
//! \~english First does `resize(new_size)` then `fill(e)`.
|
||||
//! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`.
|
||||
//! \~\sa \a fill(), \a resize()
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIDeque<T> & assign(size_t new_size, const T & e) {
|
||||
resize(new_size);
|
||||
return fill(e);
|
||||
}
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIDeque<T> & assign(size_t new_size, const T & e) {
|
||||
_resizeRaw(new_size);
|
||||
return fill(e);
|
||||
@@ -1278,7 +1242,7 @@ public:
|
||||
if (new_size < pid_size) {
|
||||
deleteT(pid_data + pid_start + new_size, pid_size - new_size);
|
||||
pid_size = new_size;
|
||||
}else if (new_size > pid_size) {
|
||||
} else if (new_size > pid_size) {
|
||||
expand(new_size, e);
|
||||
}
|
||||
return *this;
|
||||
@@ -1306,25 +1270,21 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIDeque<T> & _resizeRaw(size_t new_size) {
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
if (new_size > pid_size) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-pid_size));
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - pid_size));
|
||||
}
|
||||
if (new_size < pid_size) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, (pid_size-new_size));
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, (pid_size - new_size));
|
||||
}
|
||||
#endif
|
||||
alloc_forward(new_size);
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline void _copyRaw(T * dst, const T * src, size_t size) {
|
||||
newT(dst, src, size);
|
||||
}
|
||||
inline void _copyRaw(T * dst, const T * src, size_t size) { newT(dst, src, size); }
|
||||
|
||||
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
||||
//! \~russian Резервируется память под как минимум `new_size` элементов.
|
||||
@@ -1367,12 +1327,12 @@ public:
|
||||
alloc_forward(pid_size + 1);
|
||||
if (index < pid_size - 1) {
|
||||
size_t os = pid_size - index - 1;
|
||||
memmove((void*)(pid_data + pid_start + index + 1), (const void*)(pid_data + pid_start + index), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index + 1), (const void *)(pid_data + pid_start + index), os * sizeof(T));
|
||||
}
|
||||
} else {
|
||||
alloc_backward(pid_size + 1, -1);
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start), (const void*)(pid_data + pid_start + 1), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + 1), index * sizeof(T));
|
||||
}
|
||||
}
|
||||
elementNew(pid_data + pid_start + index, e);
|
||||
@@ -1393,12 +1353,12 @@ public:
|
||||
alloc_forward(pid_size + 1);
|
||||
if (index < pid_size - 1) {
|
||||
size_t os = pid_size - index - 1;
|
||||
memmove((void*)(pid_data + pid_start + index + 1), (const void*)(pid_data + pid_start + index), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index + 1), (const void *)(pid_data + pid_start + index), os * sizeof(T));
|
||||
}
|
||||
} else {
|
||||
alloc_backward(pid_size + 1, -1);
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start), (const void*)(pid_data + pid_start + 1), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + 1), index * sizeof(T));
|
||||
}
|
||||
}
|
||||
elementNew(pid_data + pid_start + index, std::move(e));
|
||||
@@ -1424,12 +1384,12 @@ public:
|
||||
ssize_t os = pid_size - index;
|
||||
alloc_forward(pid_size + v.pid_size);
|
||||
if (os > 0) {
|
||||
memmove((void*)(pid_data + pid_start + index + v.pid_size), (const void*)(pid_data + pid_start + index), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index + v.pid_size), (const void *)(pid_data + pid_start + index), os * sizeof(T));
|
||||
}
|
||||
} else {
|
||||
alloc_backward(pid_size + v.pid_size, -v.pid_size);
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start), (const void*)(pid_data + pid_start + v.pid_size), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + v.pid_size), index * sizeof(T));
|
||||
}
|
||||
}
|
||||
newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size);
|
||||
@@ -1453,12 +1413,14 @@ public:
|
||||
ssize_t os = ssize_t(pid_size) - index;
|
||||
alloc_forward(pid_size + init_list.size());
|
||||
if (os > 0) {
|
||||
memmove((void*)(pid_data + pid_start + index + init_list.size()), (const void*)(pid_data + pid_start + index), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index + init_list.size()),
|
||||
(const void *)(pid_data + pid_start + index),
|
||||
os * sizeof(T));
|
||||
}
|
||||
} else {
|
||||
alloc_backward(pid_size + init_list.size(), -init_list.size());
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start), (const void*)(pid_data + pid_start + init_list.size()), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start), (const void *)(pid_data + pid_start + init_list.size()), index * sizeof(T));
|
||||
}
|
||||
}
|
||||
newT(pid_data + pid_start + index, init_list.begin(), init_list.size());
|
||||
@@ -1485,10 +1447,10 @@ public:
|
||||
size_t os = pid_size - index - count;
|
||||
deleteT(pid_data + pid_start + index, count);
|
||||
if (os <= index) {
|
||||
memmove((void*)(pid_data + pid_start + index), (const void*)(pid_data + pid_start + index + count), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index), (const void *)(pid_data + pid_start + index + count), os * sizeof(T));
|
||||
} else {
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start + count), (const void*)(pid_data + pid_start), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + count), (const void *)(pid_data + pid_start), index * sizeof(T));
|
||||
}
|
||||
pid_start += count;
|
||||
}
|
||||
@@ -1503,7 +1465,7 @@ public:
|
||||
//! \~english This operation is very fast and never fails.
|
||||
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
|
||||
inline 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_rsize, other.pid_rsize);
|
||||
piSwap<size_t>(pid_start, other.pid_start);
|
||||
@@ -1548,23 +1510,18 @@ public:
|
||||
//! Complexity `O(N·log(N))`.
|
||||
//! \~russian Сохранность порядка элементов, имеющих одинаковое значение, не гарантируется.
|
||||
//! Для сравнения элементов используется функция сравнения `comp`.
|
||||
//! Функция сравнения, возвращает `true` если первый аргумент меньше второго.
|
||||
//! Сигнатура функции сравнения должна быть эквивалентна следующей:
|
||||
//! \code
|
||||
//! bool comp(const T &a, const T &b);
|
||||
//! \endcode
|
||||
//! Сигнатура не обязана содержать const &, однако, функция не может изменять переданные объекты.
|
||||
//! Функция обязана возвращать `false` для одинаковых элементов,
|
||||
//! иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
//! Для сортировки используется функция [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort).
|
||||
//! Сложность сортировки `O(N·log(N))`.
|
||||
//! Функция сравнения, возвращает `true` если первый аргумент меньше
|
||||
//! второго. Сигнатура функции сравнения должна быть эквивалентна следующей: \code bool comp(const T &a, const T &b); \endcode Сигнатура
|
||||
//! не обязана содержать const &, однако, функция не может изменять переданные объекты. Функция обязана возвращать `false` для
|
||||
//! одинаковых элементов, иначе это приведёт к неопределённому поведению программы и ошибкам памяти. Для сортировки используется функция
|
||||
//! [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort). Сложность сортировки `O(N·log(N))`.
|
||||
//! \~\code
|
||||
//! PIDeque<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
|
||||
//! v.sort([](const int & a, const int & b){return a > b;});
|
||||
//! piCout << v; // 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
|
||||
//! \endcode
|
||||
//! \~\sa \a sort()
|
||||
inline PIDeque<T> & sort(std::function<bool(const T &a, const T &b)> comp) {
|
||||
inline PIDeque<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
|
||||
std::sort(begin(), end(), comp);
|
||||
return *this;
|
||||
}
|
||||
@@ -1587,9 +1544,9 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a reversed()
|
||||
inline PIDeque<T> & reverse() {
|
||||
size_t s2 = pid_size/2;
|
||||
size_t s2 = pid_size / 2;
|
||||
for (size_t i = 0; i < s2; ++i) {
|
||||
piSwap<T>(pid_data[pid_start+i], pid_data[pid_start+pid_size-i-1]);
|
||||
piSwap<T>(pid_data[pid_start + i], pid_data[pid_start + pid_size - i - 1]);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -1619,8 +1576,10 @@ public:
|
||||
//! \~\sa \a resize()
|
||||
inline PIDeque<T> & enlarge(ssize_t add_size, const T & e = T()) {
|
||||
ssize_t ns = size_s() + add_size;
|
||||
if (ns <= 0) clear();
|
||||
else resize(size_t(ns), e);
|
||||
if (ns <= 0)
|
||||
clear();
|
||||
else
|
||||
resize(size_t(ns), e);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -1789,7 +1748,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a prepend(), \a push_front(), \a push_back(), \a insert()
|
||||
inline PIDeque<T> & append(const T & e) {return push_back(e);}
|
||||
inline PIDeque<T> & append(const T & e) { return push_back(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1797,7 +1756,7 @@ public:
|
||||
//! \~english Overloaded function.
|
||||
//! \~russian Перегруженая функция.
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & append(T && e) {return push_back(std::move(e));}
|
||||
inline PIDeque<T> & append(T && e) { return push_back(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given elements to the end of the array.
|
||||
//! \~russian Добавляет элементы в конец массива.
|
||||
@@ -1809,7 +1768,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & append(std::initializer_list<T> init_list) {return push_back(init_list);}
|
||||
inline PIDeque<T> & append(std::initializer_list<T> init_list) { return push_back(init_list); }
|
||||
|
||||
//! \~english Appends the given array `v` to the end of the array.
|
||||
//! \~russian Добавляет массив `v` в конец массива.
|
||||
@@ -1822,7 +1781,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & append(const PIDeque<T> & v) {return push_back(v);}
|
||||
inline PIDeque<T> & append(const PIDeque<T> & v) { return push_back(v); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1833,7 +1792,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & operator <<(const T & e) {return push_back(e);}
|
||||
inline PIDeque<T> & operator<<(const T & e) { return push_back(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1844,7 +1803,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & operator <<(T && e) {return push_back(std::move(e));}
|
||||
inline PIDeque<T> & operator<<(T && e) { return push_back(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given array `v` to the end of the array.
|
||||
//! \~russian Добавляет массив `v` в конец массива.
|
||||
@@ -1855,7 +1814,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append(), \a push_back()
|
||||
inline PIDeque<T> & operator <<(const PIDeque<T> & v) {return append(v);}
|
||||
inline PIDeque<T> & operator<<(const PIDeque<T> & v) { return append(v); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1912,9 +1871,7 @@ public:
|
||||
//! piCout << v; // {4, 5, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a push_front()
|
||||
inline PIDeque<T> & push_front(const PIDeque<T> & v) {
|
||||
return insert(0, v);
|
||||
}
|
||||
inline PIDeque<T> & push_front(const PIDeque<T> & v) { return insert(0, v); }
|
||||
|
||||
//! \~english Appends the given elements to the begin of the array.
|
||||
//! \~russian Добавляет элементы в начало массива.
|
||||
@@ -1926,9 +1883,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & push_front(std::initializer_list<T> init_list) {
|
||||
return insert(0, init_list);
|
||||
}
|
||||
inline PIDeque<T> & push_front(std::initializer_list<T> init_list) { return insert(0, init_list); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1954,7 +1909,7 @@ public:
|
||||
//! piCout << v; // {5, 4, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a push_back(), \a append(), \a prepend(), \a insert()
|
||||
inline PIDeque<T> & prepend(const T & e) {return push_front(e);}
|
||||
inline PIDeque<T> & prepend(const T & e) { return push_front(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1962,7 +1917,7 @@ public:
|
||||
//! \~english Overloaded function.
|
||||
//! \~russian Перегруженая функция.
|
||||
//! \~\sa \a prepend()
|
||||
inline PIDeque<T> & prepend(T && e) {return push_front(std::move(e));}
|
||||
inline PIDeque<T> & prepend(T && e) { return push_front(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given array `v` to the begin of the array.
|
||||
//! \~russian Добавляет массив `v` в начало массива.
|
||||
@@ -1975,7 +1930,7 @@ public:
|
||||
//! piCout << v; // {4, 5, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a prepend()
|
||||
inline PIDeque<T> & prepend(const PIDeque<T> & v) {return push_front(v);}
|
||||
inline PIDeque<T> & prepend(const PIDeque<T> & v) { return push_front(v); }
|
||||
|
||||
//! \~english Appends the given elements to the begin of the array.
|
||||
//! \~russian Добавляет элементы в начало массива.
|
||||
@@ -1987,7 +1942,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIDeque<T> & prepend(std::initializer_list<T> init_list) {return push_front(init_list);}
|
||||
inline PIDeque<T> & prepend(std::initializer_list<T> init_list) { return push_front(init_list); }
|
||||
|
||||
//! \~english Remove one element from the end of the array.
|
||||
//! \~russian Удаляет один элемент с конца массива.
|
||||
@@ -2071,7 +2026,7 @@ public:
|
||||
//! piCout << v2; // {1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIDeque<ST> toType() const {
|
||||
PIDeque<ST> ret(pid_size);
|
||||
ret.reserve(pid_size);
|
||||
@@ -2116,7 +2071,7 @@ public:
|
||||
//! \~\sa \a filter()
|
||||
inline PIDeque<T> filterReverse(std::function<bool(const T & e)> test) const {
|
||||
PIDeque<T> ret;
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
if (test(pid_data[i])) ret << pid_data[i];
|
||||
}
|
||||
return ret;
|
||||
@@ -2127,7 +2082,7 @@ public:
|
||||
//! \~\sa \a filterReverse()
|
||||
inline PIDeque<T> filterReverseIndexed(std::function<bool(size_t index, const T & e)> test) const {
|
||||
PIDeque<T> ret;
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
if (test(i - pid_start, pid_data[i])) ret << pid_data[i];
|
||||
}
|
||||
return ret;
|
||||
@@ -2196,7 +2151,7 @@ public:
|
||||
//! \~russian Аналогично \a forEach() но от конца до начала (справа на лево).
|
||||
//! \~\sa \a forEach()
|
||||
inline void forEachReverse(std::function<void(const T & e)> f) const {
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
f(pid_data[i]);
|
||||
}
|
||||
}
|
||||
@@ -2205,7 +2160,7 @@ public:
|
||||
//! \~russian Аналогично \a forEachReverse(), но позволяет изменять элементы массива.
|
||||
//! \~\sa \a forEach(), \a forEachReverse()
|
||||
inline PIDeque<T> & forEachReverse(std::function<void(T & e)> f) {
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
f(pid_data[i]);
|
||||
}
|
||||
return *this;
|
||||
@@ -2215,7 +2170,7 @@ public:
|
||||
//! \~russian Аналогично \a forEachIndexed() но от конца до начала (справа на лево).
|
||||
//! \~\sa \a forEachIndexed(), \a forEachReverse(), \a forEach()
|
||||
inline void forEachReverseIndexed(std::function<void(size_t index, const T & e)> f) const {
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
f(i - pid_start, pid_data[i]);
|
||||
}
|
||||
}
|
||||
@@ -2224,7 +2179,7 @@ public:
|
||||
//! \~russian Аналогично \a forEachReverseIndexed(), но позволяет изменять элементы массива.
|
||||
//! \~\sa \a forEachReverseIndexed(), \a forEachIndexed(), \a forEachReverse(), \a forEach()
|
||||
inline PIDeque<T> & forEachReverseIndexed(std::function<void(size_t index, T & e)> f) {
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
f(i - pid_start, pid_data[i]);
|
||||
}
|
||||
return *this;
|
||||
@@ -2247,9 +2202,10 @@ public:
|
||||
//! piCout << sl; // {"1", "2", "3"}
|
||||
//! \endcode
|
||||
//! \~\sa \a forEach(), \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIDeque<ST> map(std::function<ST(const T & e)> f) const {
|
||||
PIDeque<ST> ret; ret.reserve(pid_size);
|
||||
PIDeque<ST> ret;
|
||||
ret.reserve(pid_size);
|
||||
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
|
||||
ret << f(pid_data[i]);
|
||||
}
|
||||
@@ -2264,9 +2220,10 @@ public:
|
||||
//! piCout << sl; // {"0", "1", "2"}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIDeque<ST> mapIndexed(std::function<ST(size_t index, const T & e)> f) const {
|
||||
PIDeque<ST> ret; ret.reserve(pid_size);
|
||||
PIDeque<ST> ret;
|
||||
ret.reserve(pid_size);
|
||||
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
|
||||
ret << f(i - pid_start, pid_data[i]);
|
||||
}
|
||||
@@ -2281,10 +2238,11 @@ public:
|
||||
//! piCout << sl; // {"3", "2", "1"}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIDeque<ST> mapReverse(std::function<ST(const T & e)> f) const {
|
||||
PIDeque<ST> ret; ret.reserve(pid_size);
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
PIDeque<ST> ret;
|
||||
ret.reserve(pid_size);
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
ret << f(pid_data[i]);
|
||||
}
|
||||
return ret;
|
||||
@@ -2298,10 +2256,11 @@ public:
|
||||
//! piCout << sl; // {"2", "1", "0"}
|
||||
//! \endcode
|
||||
//! \~\sa \a mapReverse()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIDeque<ST> mapReverseIndexed(std::function<ST(size_t index, const T & e)> f) const {
|
||||
PIDeque<ST> ret; ret.reserve(pid_size);
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
PIDeque<ST> ret;
|
||||
ret.reserve(pid_size);
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
ret << f(size_t(i) - pid_start, pid_data[i]);
|
||||
}
|
||||
return ret;
|
||||
@@ -2348,7 +2307,7 @@ public:
|
||||
//! piCout << s; // 15
|
||||
//! \endcode
|
||||
//! \~\sa \a reduceIndexed(), \a reduceReverse(), \a reduceReverseIndexed(), \a forEach(), \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduce(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
|
||||
@@ -2360,7 +2319,7 @@ public:
|
||||
//! \~english Same as \a reduce() but with `index` parameter in `f`.
|
||||
//! \~russian Аналогично \a reduce() но с параметром индекса `index` в функции `f`.
|
||||
//! \~\sa \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceIndexed(std::function<ST(size_t index, const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
|
||||
@@ -2372,10 +2331,10 @@ public:
|
||||
//! \~english Same as \a reduce() but from end to begin (from right to left).
|
||||
//! \~russian Аналогично \a reduce() но от конца до начала (справа на лево).
|
||||
//! \~\sa \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceReverse(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
ret = f(pid_data[i], ret);
|
||||
}
|
||||
return ret;
|
||||
@@ -2384,10 +2343,10 @@ public:
|
||||
//! \~english Same as \a reduceReverse() but with `index` parameter in `f`.
|
||||
//! \~russian Аналогично \a reduceReverse() но с параметром индекса `index` в функции `f`.
|
||||
//! \~\sa \a reduceReverse()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceReverseIndexed(std::function<ST(size_t index, const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (ssize_t i = ssize_t(pid_start+pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
for (ssize_t i = ssize_t(pid_start + pid_size) - 1; i >= ssize_t(pid_start); --i) {
|
||||
ret = f(size_t(i) - pid_start, pid_data[i], ret);
|
||||
}
|
||||
return ret;
|
||||
@@ -2416,22 +2375,22 @@ public:
|
||||
PIDeque<PIDeque<T>> ret;
|
||||
if (isEmpty()) return ret;
|
||||
#ifndef NDEBUG
|
||||
if (rows*cols != pid_size) {
|
||||
if (rows * cols != pid_size) {
|
||||
printf("error with PIDeque<%s>::reshape\n", __PIP_TYPENAME__(T));
|
||||
}
|
||||
#endif
|
||||
assert(rows*cols == pid_size);
|
||||
assert(rows * cols == pid_size);
|
||||
ret.expand(rows);
|
||||
if (order == ReshapeByRow) {
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
ret[r] = PIDeque<T>(&(pid_data[r*cols]), cols);
|
||||
ret[r] = PIDeque<T>(&(pid_data[r * cols]), cols);
|
||||
}
|
||||
}
|
||||
if (order == ReshapeByColumn) {
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
ret[r].expand(cols);
|
||||
for (size_t c = 0; c < cols; c++) {
|
||||
ret[r][c] = pid_data[c*rows + r];
|
||||
ret[r][c] = pid_data[c * rows + r];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2452,9 +2411,7 @@ public:
|
||||
//! piCout << xv.flatten<int>(); // {1, 2, 3, 4, 5, 6}
|
||||
//! \endcode
|
||||
//! \~\sa \a map(), \a reduce(), \a reshape()
|
||||
template<typename C, typename std::enable_if<
|
||||
std::is_same<T, PIDeque<C>>::value
|
||||
, int>::type = 0>
|
||||
template<typename C, typename std::enable_if<std::is_same<T, PIDeque<C>>::value, int>::type = 0>
|
||||
inline PIDeque<C> flatten(ReshapeOrder order = ReshapeByRow) const {
|
||||
PIDeque<C> ret;
|
||||
if (isEmpty()) return ret;
|
||||
@@ -2495,9 +2452,7 @@ public:
|
||||
//! piCout << xv.reshape<int>(2,3); // {{1, 2, 3}, {4, 5, 6}}
|
||||
//! \endcode
|
||||
//! \~\sa \a map(), \a reduce(), \a reshape()
|
||||
template<typename C, typename std::enable_if<
|
||||
std::is_same<T, PIDeque<C>>::value
|
||||
, int>::type = 0>
|
||||
template<typename C, typename std::enable_if<std::is_same<T, PIDeque<C>>::value, int>::type = 0>
|
||||
inline PIDeque<PIDeque<C>> reshape(size_t rows, size_t cols, ReshapeOrder order = ReshapeByRow) const {
|
||||
PIDeque<C> fl = flatten<C>();
|
||||
return fl.reshape(rows, cols, order);
|
||||
@@ -2534,9 +2489,9 @@ public:
|
||||
if (isEmpty() || sz == 0) return ret;
|
||||
size_t ch = pid_size / sz;
|
||||
for (size_t i = 0; i < ch; ++i) {
|
||||
ret << PIDeque<T>(pid_data + pid_start + sz*i, sz);
|
||||
ret << PIDeque<T>(pid_data + pid_start + sz * i, sz);
|
||||
}
|
||||
size_t t = ch*sz;
|
||||
size_t t = ch * sz;
|
||||
if (t < pid_size) {
|
||||
ret << PIDeque<T>(pid_data + pid_start + t, pid_size - t);
|
||||
}
|
||||
@@ -2565,16 +2520,16 @@ public:
|
||||
if (index >= pid_size || count == 0) return ret;
|
||||
if (index + count > pid_size) count = pid_size - index;
|
||||
ret.alloc_forward(count);
|
||||
memcpy((void*)(ret.pid_data + ret.pid_start), (const void*)(pid_data + pid_start + index), count * sizeof(T));
|
||||
memcpy((void *)(ret.pid_data + ret.pid_start), (const void *)(pid_data + pid_start + index), count * sizeof(T));
|
||||
|
||||
size_t os = pid_size - index - count;
|
||||
if (os <= index) {
|
||||
if (os > 0) {
|
||||
memmove((void*)(pid_data + pid_start + index), (const void*)(pid_data + pid_start + index + count), os * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + index), (const void *)(pid_data + pid_start + index + count), os * sizeof(T));
|
||||
}
|
||||
} else {
|
||||
if (index > 0) {
|
||||
memmove((void*)(pid_data + pid_start + count), (const void*)(pid_data + pid_start), index * sizeof(T));
|
||||
memmove((void *)(pid_data + pid_start + count), (const void *)(pid_data + pid_start), index * sizeof(T));
|
||||
}
|
||||
pid_start += count;
|
||||
}
|
||||
@@ -2597,13 +2552,12 @@ private:
|
||||
}
|
||||
size_t t = _PIContainerConstants<T>::minCountPoT();
|
||||
size_t s_ = s - 1;
|
||||
while (s_ >> t) ++t;
|
||||
while (s_ >> t)
|
||||
++t;
|
||||
return (1 << t);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void newT(T * dst, const T * src, size_t s) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, s)
|
||||
for (size_t i = 0; i < s; ++i) {
|
||||
@@ -2611,17 +2565,13 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void newT(T * dst, const T * src, size_t s) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, s)
|
||||
memcpy((void*)(dst), (const void*)(src), s * sizeof(T));
|
||||
memcpy((void *)(dst), (const void *)(src), s * sizeof(T));
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void deleteT(T * d, size_t sz) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, sz)
|
||||
if (d != nullptr) {
|
||||
@@ -2631,56 +2581,42 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void deleteT(T * d, size_t sz) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, sz)
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, const T & from) {
|
||||
new(to)T(from);
|
||||
new (to) T(from);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, T && from) {
|
||||
new(to)T(std::move(from));
|
||||
new (to) T(std::move(from));
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T1 * to, const T & from) {
|
||||
(*to) = from;
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, T && from) {
|
||||
(*to) = std::move(from);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementDelete(T & from) {
|
||||
from.~T();
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementDelete(T & from) {}
|
||||
|
||||
inline void dealloc() {
|
||||
if (pid_data != nullptr) {
|
||||
free((void*)pid_data);
|
||||
free((void *)pid_data);
|
||||
pid_data = nullptr;
|
||||
}
|
||||
}
|
||||
@@ -2691,7 +2627,7 @@ private:
|
||||
if (pid_start < (pid_size * 2) || ssize_t(pid_start) > (ssize_t(pid_rsize) - (ssize_t(pid_size) * 2))) {
|
||||
size_t ns = (pid_rsize - pid_size) / 2;
|
||||
if (pid_start != ns) {
|
||||
memmove((void*)(pid_data + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
memmove((void *)(pid_data + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
pid_start = ns;
|
||||
}
|
||||
}
|
||||
@@ -2699,7 +2635,7 @@ private:
|
||||
} else {
|
||||
size_t ns = (pid_rsize - pid_size) / 2;
|
||||
if (pid_start != ns) {
|
||||
memmove((void*)(pid_data + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
memmove((void *)(pid_data + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
pid_start = ns;
|
||||
}
|
||||
}
|
||||
@@ -2714,8 +2650,8 @@ private:
|
||||
pid_size = new_size;
|
||||
size_t as = asize(pid_start + new_size);
|
||||
if (as != pid_rsize) {
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as-pid_rsize))
|
||||
T * p_d = (T*)(realloc((void*)(pid_data), as*sizeof(T)));
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize))
|
||||
T * p_d = (T *)(realloc((void *)(pid_data), as * sizeof(T)));
|
||||
#ifndef NDEBUG
|
||||
if (!p_d) {
|
||||
printf("error with PIDeque<%s>::alloc\n", __PIP_TYPENAME__(T));
|
||||
@@ -2735,11 +2671,11 @@ private:
|
||||
as = pid_rsize;
|
||||
}
|
||||
if (as > pid_rsize) {
|
||||
T * td = (T*)(malloc(as * sizeof(T)));
|
||||
T * td = (T *)(malloc(as * sizeof(T)));
|
||||
size_t ns = pid_start + as - pid_rsize;
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as-pid_rsize))
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize))
|
||||
if (pid_rsize > 0 && pid_data != 0) {
|
||||
memcpy((void*)(td + ns), (const void*)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
memcpy((void *)(td + ns), (const void *)(pid_data + pid_start), pid_size * sizeof(T));
|
||||
dealloc();
|
||||
}
|
||||
pid_data = td;
|
||||
@@ -2754,7 +2690,7 @@ private:
|
||||
inline void expand(size_t new_size, const T & e = T()) {
|
||||
size_t os = pid_size;
|
||||
alloc_forward(new_size);
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-os))
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - os))
|
||||
for (size_t i = os + pid_start; i < new_size + pid_start; ++i) {
|
||||
elementNew(pid_data + i, e);
|
||||
}
|
||||
@@ -2763,7 +2699,7 @@ private:
|
||||
inline void expand(size_t new_size, std::function<T(size_t i)> f) {
|
||||
size_t os = pid_size;
|
||||
alloc_forward(new_size);
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-os))
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - os))
|
||||
for (size_t i = os + pid_start; i < new_size + pid_start; ++i) {
|
||||
elementNew(pid_data + i, f(i));
|
||||
}
|
||||
@@ -2780,7 +2716,7 @@ private:
|
||||
//! \~english Output operator to [std::ostream](https://en.cppreference.com/w/cpp/io/basic_ostream).
|
||||
//! \~russian Оператор вывода в [std::ostream](https://ru.cppreference.com/w/cpp/io/basic_ostream).
|
||||
template<typename T>
|
||||
inline std::ostream & operator <<(std::ostream & s, const PIDeque<T> & v) {
|
||||
inline std::ostream & operator<<(std::ostream & s, const PIDeque<T> & v) {
|
||||
s << "{";
|
||||
for (size_t i = 0; i < v.size(); ++i) {
|
||||
s << v[i];
|
||||
@@ -2796,7 +2732,7 @@ inline std::ostream & operator <<(std::ostream & s, const PIDeque<T> & v) {
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
template<typename T>
|
||||
inline PICout operator <<(PICout s, const PIDeque<T> & v) {
|
||||
inline PICout operator<<(PICout s, const PIDeque<T> & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "{";
|
||||
@@ -2810,7 +2746,9 @@ inline PICout operator <<(PICout s, const PIDeque<T> & v) {
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void piSwap(PIDeque<T> & f, PIDeque<T> & s) {f.swap(s);}
|
||||
inline void piSwap(PIDeque<T> & f, PIDeque<T> & s) {
|
||||
f.swap(s);
|
||||
}
|
||||
|
||||
|
||||
#endif // PIDEQUE_H
|
||||
|
||||
@@ -34,15 +34,19 @@
|
||||
#ifndef PIMAP_H
|
||||
#define PIMAP_H
|
||||
|
||||
#include "pivector.h"
|
||||
#include "pideque.h"
|
||||
#include "pipair.h"
|
||||
#include "pivector.h"
|
||||
|
||||
|
||||
template <typename Key, typename T> class PIMapIteratorConst;
|
||||
template <typename Key, typename T> class PIMapIteratorConstReverse;
|
||||
template <typename Key, typename T> class PIMapIterator;
|
||||
template <typename Key, typename T> class PIMapIteratorReverse;
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorConst;
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorConstReverse;
|
||||
template<typename Key, typename T>
|
||||
class PIMapIterator;
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorReverse;
|
||||
|
||||
|
||||
//! \addtogroup Containers
|
||||
@@ -74,16 +78,21 @@ template <typename Key, typename T> class PIMapIteratorReverse;
|
||||
//! по которым их можно найти, которыми могут выступать значения любого типа.
|
||||
//! \a operator [] позволяет получить доступ к элементу по ключу,
|
||||
//! и если такого эелемента не было, то он будет создан.
|
||||
template <typename Key, typename T>
|
||||
template<typename Key, typename T>
|
||||
class PIMap {
|
||||
template <typename Key1, typename T1> friend class PIMapIteratorConst;
|
||||
template <typename Key1, typename T1> friend class PIMapIteratorConstReverse;
|
||||
template <typename Key1, typename T1> friend class PIMapIterator;
|
||||
template <typename Key1, typename T1> friend class PIMapIteratorReverse;
|
||||
template <typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator <<(PIBinaryStream<P> & s, const PIMap<Key1, T1> & v);
|
||||
template <typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIMap<Key1, T1> & v);
|
||||
template<typename Key1, typename T1>
|
||||
friend class PIMapIteratorConst;
|
||||
template<typename Key1, typename T1>
|
||||
friend class PIMapIteratorConstReverse;
|
||||
template<typename Key1, typename T1>
|
||||
friend class PIMapIterator;
|
||||
template<typename Key1, typename T1>
|
||||
friend class PIMapIteratorReverse;
|
||||
template<typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIMap<Key1, T1> & v);
|
||||
template<typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMap<Key1, T1> & v);
|
||||
|
||||
public:
|
||||
typedef T mapped_type;
|
||||
typedef Key key_type;
|
||||
@@ -95,11 +104,11 @@ public:
|
||||
|
||||
//! \~english Copy constructor.
|
||||
//! \~russian Копирующий конструктор.
|
||||
inline PIMap(const PIMap<Key, T> & other) : pim_content(other.pim_content), pim_index(other.pim_index) {}
|
||||
inline PIMap(const PIMap<Key, T> & other): pim_content(other.pim_content), pim_index(other.pim_index) {}
|
||||
|
||||
//! \~english Move constructor.
|
||||
//! \~russian Перемещающий конструктор.
|
||||
inline PIMap(PIMap<Key, T> && other) : pim_content(std::move(other.pim_content)), pim_index(std::move(other.pim_index)) {}
|
||||
inline PIMap(PIMap<Key, T> && other): pim_content(std::move(other.pim_content)), pim_index(std::move(other.pim_index)) {}
|
||||
|
||||
//! \~english Contructs map from
|
||||
//! [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list).
|
||||
@@ -118,7 +127,7 @@ public:
|
||||
|
||||
//! \~english Assign operator.
|
||||
//! \~russian Оператор присваивания.
|
||||
inline PIMap<Key, T> & operator =(const PIMap<Key, T> & other) {
|
||||
inline PIMap<Key, T> & operator=(const PIMap<Key, T> & other) {
|
||||
if (this == &other) return *this;
|
||||
clear();
|
||||
pim_content = other.pim_content;
|
||||
@@ -128,140 +137,148 @@ public:
|
||||
|
||||
//! \~english Assign move operator.
|
||||
//! \~russian Оператор перемещающего присваивания.
|
||||
inline PIMap<Key, T> & operator =(PIMap<Key, T> && other) {
|
||||
inline PIMap<Key, T> & operator=(PIMap<Key, T> && other) {
|
||||
swap(other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
class iterator {
|
||||
friend class PIMap<Key, T>;
|
||||
|
||||
private:
|
||||
iterator(const PIMap<Key, T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIMap<Key, T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
iterator(): parent(nullptr), pos(0) {}
|
||||
const Key & key() const {return const_cast<PIMap<Key, T> * >(parent)->_key(pos);}
|
||||
T & value() {return const_cast<PIMap<Key, T> * >(parent)->_value(pos);}
|
||||
inline PIPair<Key, T> operator *() const {
|
||||
return PIPair<Key, T>(const_cast<PIMap<Key, T> * >(parent)->_key(pos), const_cast<PIMap<Key, T> * >(parent)->_value(pos));
|
||||
const Key & key() const { return const_cast<PIMap<Key, T> *>(parent)->_key(pos); }
|
||||
T & value() { return const_cast<PIMap<Key, T> *>(parent)->_value(pos); }
|
||||
inline PIPair<Key, T> operator*() const {
|
||||
return PIPair<Key, T>(const_cast<PIMap<Key, T> *>(parent)->_key(pos), const_cast<PIMap<Key, T> *>(parent)->_value(pos));
|
||||
}
|
||||
void operator ++() {++pos;}
|
||||
void operator ++(int) {++pos;}
|
||||
void operator --() {--pos;}
|
||||
void operator --(int) {--pos;}
|
||||
bool operator ==(const iterator & it) const {return (pos == it.pos);}
|
||||
bool operator !=(const iterator & it) const {return (pos != it.pos);}
|
||||
void operator++() { ++pos; }
|
||||
void operator++(int) { ++pos; }
|
||||
void operator--() { --pos; }
|
||||
void operator--(int) { --pos; }
|
||||
bool operator==(const iterator & it) const { return (pos == it.pos); }
|
||||
bool operator!=(const iterator & it) const { return (pos != it.pos); }
|
||||
};
|
||||
|
||||
class reverse_iterator {
|
||||
friend class PIMap<Key, T>;
|
||||
|
||||
private:
|
||||
reverse_iterator(const PIMap<Key, T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIMap<Key, T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
reverse_iterator(): parent(nullptr), pos(0) {}
|
||||
const Key & key() const {return const_cast<PIMap<Key, T> * >(parent)->_key(pos);}
|
||||
T & value() const {return const_cast<PIMap<Key, T> * >(parent)->_value(pos);}
|
||||
inline PIPair<Key, T> operator *() const {
|
||||
return PIPair<Key, T>(const_cast<PIMap<Key, T> * >(parent)->_key(pos), const_cast<PIMap<Key, T> * >(parent)->_value(pos));
|
||||
const Key & key() const { return const_cast<PIMap<Key, T> *>(parent)->_key(pos); }
|
||||
T & value() const { return const_cast<PIMap<Key, T> *>(parent)->_value(pos); }
|
||||
inline PIPair<Key, T> operator*() const {
|
||||
return PIPair<Key, T>(const_cast<PIMap<Key, T> *>(parent)->_key(pos), const_cast<PIMap<Key, T> *>(parent)->_value(pos));
|
||||
}
|
||||
void operator ++() {--pos;}
|
||||
void operator ++(int) {--pos;}
|
||||
void operator --() {++pos;}
|
||||
void operator --(int) {++pos;}
|
||||
bool operator ==(const reverse_iterator & it) const {return (pos == it.pos);}
|
||||
bool operator !=(const reverse_iterator & it) const {return (pos != it.pos);}
|
||||
void operator++() { --pos; }
|
||||
void operator++(int) { --pos; }
|
||||
void operator--() { ++pos; }
|
||||
void operator--(int) { ++pos; }
|
||||
bool operator==(const reverse_iterator & it) const { return (pos == it.pos); }
|
||||
bool operator!=(const reverse_iterator & it) const { return (pos != it.pos); }
|
||||
};
|
||||
|
||||
class const_iterator {
|
||||
friend class PIMap<Key, T>;
|
||||
|
||||
private:
|
||||
const_iterator(const PIMap<Key, T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIMap<Key, T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
const_iterator(): parent(nullptr), pos(0) {}
|
||||
const value_type operator *() const {return parent->_pair(pos);}
|
||||
const Key & key() const {return const_cast<PIMap<Key, T> * >(parent)->_key(pos);}
|
||||
const T & value() const {return const_cast<PIMap<Key, T> * >(parent)->_value(pos);}
|
||||
void operator ++() {++pos;}
|
||||
void operator ++(int) {++pos;}
|
||||
void operator --() {--pos;}
|
||||
void operator --(int) {--pos;}
|
||||
bool operator ==(const const_iterator & it) const {return (pos == it.pos);}
|
||||
bool operator !=(const const_iterator & it) const {return (pos != it.pos);}
|
||||
const value_type operator*() const { return parent->_pair(pos); }
|
||||
const Key & key() const { return const_cast<PIMap<Key, T> *>(parent)->_key(pos); }
|
||||
const T & value() const { return const_cast<PIMap<Key, T> *>(parent)->_value(pos); }
|
||||
void operator++() { ++pos; }
|
||||
void operator++(int) { ++pos; }
|
||||
void operator--() { --pos; }
|
||||
void operator--(int) { --pos; }
|
||||
bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
||||
bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
||||
};
|
||||
|
||||
class const_reverse_iterator {
|
||||
friend class PIMap<Key, T>;
|
||||
|
||||
private:
|
||||
const_reverse_iterator(const PIMap<Key, T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIMap<Key, T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
const_reverse_iterator(): parent(nullptr), pos(0) {}
|
||||
const value_type operator *() const {return parent->_pair(pos);}
|
||||
void operator ++() {--pos;}
|
||||
void operator ++(int) {--pos;}
|
||||
void operator --() {++pos;}
|
||||
void operator --(int) {++pos;}
|
||||
bool operator ==(const const_reverse_iterator & it) const {return (pos == it.pos);}
|
||||
bool operator !=(const const_reverse_iterator & it) const {return (pos != it.pos);}
|
||||
const value_type operator*() const { return parent->_pair(pos); }
|
||||
void operator++() { --pos; }
|
||||
void operator++(int) { --pos; }
|
||||
void operator--() { ++pos; }
|
||||
void operator--(int) { ++pos; }
|
||||
bool operator==(const const_reverse_iterator & it) const { return (pos == it.pos); }
|
||||
bool operator!=(const const_reverse_iterator & it) const { return (pos != it.pos); }
|
||||
};
|
||||
|
||||
|
||||
//! \~english Iterator to the first element.
|
||||
//! \~russian Итератор на первый элемент.
|
||||
inline iterator begin() {return iterator(this, 0);}
|
||||
inline iterator begin() { return iterator(this, 0); }
|
||||
|
||||
//! \~english Iterator to the element following the last element.
|
||||
//! \~russian Итератор на элемент, следующий за последним элементом.
|
||||
inline iterator end() {return iterator(this, size());}
|
||||
inline iterator end() { return iterator(this, size()); }
|
||||
|
||||
inline const_iterator begin() const {return const_iterator(this, 0);}
|
||||
inline const_iterator end() const {return const_iterator(this, size());}
|
||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||
inline const_iterator end() const { return const_iterator(this, size()); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the first element of the reversed array.
|
||||
//! \~russian Обратный итератор на первый элемент.
|
||||
inline reverse_iterator rbegin() {return reverse_iterator(this, size() - 1);}
|
||||
inline reverse_iterator rbegin() { return reverse_iterator(this, size() - 1); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the element.
|
||||
//! following the last element of the reversed array.
|
||||
//! \~russian Обратный итератор на элемент,
|
||||
//! следующий за последним элементом.
|
||||
inline reverse_iterator rend() {return reverse_iterator(this, -1);}
|
||||
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
||||
|
||||
inline const_reverse_iterator rbegin() const {return const_reverse_iterator(this, size() - 1);}
|
||||
inline const_reverse_iterator rend() const {return const_reverse_iterator(this, -1);}
|
||||
inline const_reverse_iterator rbegin() const { return const_reverse_iterator(this, size() - 1); }
|
||||
inline const_reverse_iterator rend() const { return const_reverse_iterator(this, -1); }
|
||||
|
||||
//! \relatesalso PIMapIteratorConst
|
||||
inline PIMapIteratorConst<Key, T> makeIterator() const {return PIMapIteratorConst<Key, T>(*this);}
|
||||
inline PIMapIteratorConst<Key, T> makeIterator() const { return PIMapIteratorConst<Key, T>(*this); }
|
||||
|
||||
//! \relatesalso PIMapIterator
|
||||
inline PIMapIterator<Key, T> makeIterator() {return PIMapIterator<Key, T>(*this);}
|
||||
inline PIMapIterator<Key, T> makeIterator() { return PIMapIterator<Key, T>(*this); }
|
||||
|
||||
//! \relatesalso PIMapIteratorConstReverse
|
||||
inline PIMapIteratorConstReverse<Key, T> makeReverseIterator() const {return PIMapIteratorConstReverse<Key, T>(*this);}
|
||||
inline PIMapIteratorConstReverse<Key, T> makeReverseIterator() const { return PIMapIteratorConstReverse<Key, T>(*this); }
|
||||
|
||||
//! \relatesalso PIMapIteratorReverse
|
||||
inline PIMapIteratorReverse<Key, T> makeReverseIterator() {return PIMapIteratorReverse<Key, T>(*this);}
|
||||
inline PIMapIteratorReverse<Key, T> makeReverseIterator() { return PIMapIteratorReverse<Key, T>(*this); }
|
||||
|
||||
//! \~english Number of elements in the container.
|
||||
//! \~russian Количество элементов массива.
|
||||
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t size() const {return pim_content.size();}
|
||||
inline size_t size() const { return pim_content.size(); }
|
||||
|
||||
//! \~english Number of elements in the container as signed value.
|
||||
//! \~russian Количество элементов массива в виде знакового числа.
|
||||
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline int size_s() const {return pim_content.size_s();}
|
||||
inline int size_s() const { return pim_content.size_s(); }
|
||||
|
||||
//! \~english Same as \a size().
|
||||
//! \~russian Синоним \a size().
|
||||
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t length() const {return pim_content.size();}
|
||||
inline size_t length() const { return pim_content.size(); }
|
||||
|
||||
//! \~english Checks if the container has no elements.
|
||||
//! \~russian Проверяет пуст ли массив.
|
||||
@@ -269,7 +286,7 @@ public:
|
||||
//! \~english **true** if the container is empty, **false** otherwise
|
||||
//! \~russian **true** если массив пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isEmpty() const {return (pim_content.size() == 0);}
|
||||
inline bool isEmpty() const { return (pim_content.size() == 0); }
|
||||
|
||||
//! \~english Checks if the container has elements.
|
||||
//! \~russian Проверяет не пуст ли массив.
|
||||
@@ -277,7 +294,7 @@ public:
|
||||
//! \~english **true** if the container is not empty, **false** otherwise
|
||||
//! \~russian **true** если массив не пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isNotEmpty() const {return (pim_content.size() > 0);}
|
||||
inline bool isNotEmpty() const { return (pim_content.size() > 0); }
|
||||
|
||||
|
||||
//! \~english Full access to element key `key`.
|
||||
@@ -299,7 +316,7 @@ public:
|
||||
//! piCout << m; // {огурец: 350, лук: 25}
|
||||
//! \endcode
|
||||
//! \~\sa \a insert(), \a value(), \a key()
|
||||
inline T & operator [](const Key & key) {
|
||||
inline T & operator[](const Key & key) {
|
||||
bool f(false);
|
||||
ssize_t i = _find(key, f);
|
||||
if (f) return pim_content[pim_index[i].index];
|
||||
@@ -311,7 +328,7 @@ public:
|
||||
//! \~english Same as \a value().
|
||||
//! \~russian Синоним \a value().
|
||||
//! \~\sa \a operator[](), \a value(), \a key()
|
||||
inline T at(const Key & key) const {return value(key);}
|
||||
inline T at(const Key & key) const { return value(key); }
|
||||
|
||||
//! \~english Remove element with key `key` from the array and return it.
|
||||
//! \~russian Удаляет элемент с ключом `key` из массива и возвращает его.
|
||||
@@ -326,7 +343,7 @@ public:
|
||||
|
||||
//! \~english Inserts all elements in array `other` to this array with overwrite.
|
||||
//! \~russian Вставляет все элементы `other` этот массив с перезаписью.
|
||||
inline PIMap<Key, T> & operator <<(const PIMap<Key, T> & other) {
|
||||
inline PIMap<Key, T> & operator<<(const PIMap<Key, T> & other) {
|
||||
#ifndef NDEBUG
|
||||
if (&other == this) {
|
||||
printf("error with PIMap<%s, %s>::<<\n", __PIP_TYPENAME__(Key), __PIP_TYPENAME__(T));
|
||||
@@ -351,28 +368,23 @@ public:
|
||||
|
||||
//! \~english Compare operator with array `m`.
|
||||
//! \~russian Оператор сравнения с массивом `m`.
|
||||
inline bool operator ==(const PIMap<Key, T> & m) const {
|
||||
return (pim_content == m.pim_content && pim_index == m.pim_index);
|
||||
}
|
||||
inline bool operator==(const PIMap<Key, T> & m) const { return (pim_content == m.pim_content && pim_index == m.pim_index); }
|
||||
|
||||
//! \~english Compare operator with array `m`.
|
||||
//! \~russian Оператор сравнения с массивом `m`.
|
||||
inline bool operator !=(const PIMap<Key, T> & m) const {
|
||||
return (pim_content != m.pim_content || pim_index != m.pim_index);
|
||||
}
|
||||
inline bool operator!=(const PIMap<Key, T> & m) const { return (pim_content != m.pim_content || pim_index != m.pim_index); }
|
||||
|
||||
//! \~english Tests if element with key `key` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента с ключом `key` в массиве.
|
||||
inline bool contains(const Key & key) const {
|
||||
bool f(false); _find(key, f);
|
||||
bool f(false);
|
||||
_find(key, f);
|
||||
return f;
|
||||
}
|
||||
|
||||
//! \~english Tests if element with value `value` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента со значением `value` в массиве.
|
||||
inline bool containsValue(const T & value) const {
|
||||
return pim_content.contains(value);
|
||||
}
|
||||
inline bool containsValue(const T & value) const { return pim_content.contains(value); }
|
||||
|
||||
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
||||
//! \~russian Резервируется память под как минимум `new_size` элементов.
|
||||
@@ -407,9 +419,7 @@ public:
|
||||
|
||||
//! \~english Same as \a remove().
|
||||
//! \~russian Синоним функции \a remove().
|
||||
inline PIMap<Key, T> & erase(const Key & key) {
|
||||
return remove(key);
|
||||
}
|
||||
inline PIMap<Key, T> & erase(const Key & key) { return remove(key); }
|
||||
|
||||
|
||||
//! \~english Clear array, remove all elements.
|
||||
@@ -507,7 +517,7 @@ public:
|
||||
|
||||
//! \~english Returns an array of values of all elements
|
||||
//! \~russian Возвращает массив значений всех эелметнов
|
||||
inline PIVector<T> values() const {return pim_content;}
|
||||
inline PIVector<T> values() const { return pim_content; }
|
||||
|
||||
//! \~english Returns the key of the first element
|
||||
//! whose value matches `value` or `default_` if there is no such element.
|
||||
@@ -545,9 +555,10 @@ public:
|
||||
//! of calling a provided function `PIPair<Key2, T2> f(const Key & key, const T & value)` on every element in the calling array.
|
||||
//! \~russian Создаёт новый словарь PIMap<Key2, T2> с результатом вызова указанной функции
|
||||
//! `PIPair<Key2, T2> f(const Key & key, const T & value)` для каждого элемента массива.
|
||||
template <typename Key2, typename T2>
|
||||
template<typename Key2, typename T2>
|
||||
inline PIMap<Key2, T2> map(std::function<PIPair<Key2, T2>(const Key & key, const T & value)> f) const {
|
||||
PIMap<Key2, T2> ret; ret.reserve(size());
|
||||
PIMap<Key2, T2> ret;
|
||||
ret.reserve(size());
|
||||
for (int i = 0; i < pim_index.size_s(); ++i) {
|
||||
ret.insert(f(pim_index[i].key, pim_content[pim_index[i].index]));
|
||||
}
|
||||
@@ -558,9 +569,10 @@ public:
|
||||
//! of calling a provided function `ST f(const Key & key, const T & value)` on every element in the calling array.
|
||||
//! \~russian Создаёт новый массив PIVector<ST> с результатом вызова указанной функции
|
||||
//! `ST f(const Key & key, const T & value)` для каждого элемента массива.
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> map(std::function<ST(const Key & key, const T & value)> f) const {
|
||||
PIVector<ST> ret; ret.reserve(size());
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(size());
|
||||
for (int i = 0; i < pim_index.size_s(); ++i) {
|
||||
ret << f(pim_index[i].key, pim_content[pim_index[i].index]);
|
||||
}
|
||||
@@ -587,24 +599,29 @@ private:
|
||||
MapIndex(Key && k, size_t i = 0): key(std::move(k)), index(i) {}
|
||||
Key key;
|
||||
size_t index;
|
||||
bool operator ==(const MapIndex & s) const {return key == s.key;}
|
||||
bool operator !=(const MapIndex & s) const {return key != s.key;}
|
||||
bool operator <(const MapIndex & s) const {return key < s.key;}
|
||||
bool operator >(const MapIndex & s) const {return key > s.key;}
|
||||
bool operator==(const MapIndex & s) const { return key == s.key; }
|
||||
bool operator!=(const MapIndex & s) const { return key != s.key; }
|
||||
bool operator<(const MapIndex & s) const { return key < s.key; }
|
||||
bool operator>(const MapIndex & s) const { return key > s.key; }
|
||||
};
|
||||
|
||||
template <typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator >>(PIBinaryStream<P> & s, PIDeque<typename PIMap<Key1, T1>::MapIndex> & v);
|
||||
template <typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator <<(PIBinaryStream<P> & s, const PIDeque<typename PIMap<Key1, T1>::MapIndex> & v);
|
||||
template<typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIDeque<typename PIMap<Key1, T1>::MapIndex> & v);
|
||||
template<typename P, typename Key1, typename T1>
|
||||
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIDeque<typename PIMap<Key1, T1>::MapIndex> & v);
|
||||
|
||||
inline ssize_t _binarySearch(ssize_t first, ssize_t last, const Key & key, bool & found) const {
|
||||
ssize_t mid;
|
||||
while (first <= last) {
|
||||
mid = (first + last) / 2;
|
||||
if (key > pim_index[mid].key) first = mid + 1;
|
||||
else if (key < pim_index[mid].key) last = mid - 1;
|
||||
else {found = true; return mid;}
|
||||
if (key > pim_index[mid].key)
|
||||
first = mid + 1;
|
||||
else if (key < pim_index[mid].key)
|
||||
last = mid - 1;
|
||||
else {
|
||||
found = true;
|
||||
return mid;
|
||||
}
|
||||
}
|
||||
found = false;
|
||||
return first;
|
||||
@@ -636,13 +653,13 @@ private:
|
||||
return value_type(pim_index[index].key, pim_content[pim_index[index].index]);
|
||||
}
|
||||
|
||||
inline Key & _key(ssize_t index) {return pim_index[index].key;}
|
||||
inline Key & _key(ssize_t index) { return pim_index[index].key; }
|
||||
|
||||
inline const Key & _key(ssize_t index) const {return pim_index[index].key;}
|
||||
inline const Key & _key(ssize_t index) const { return pim_index[index].key; }
|
||||
|
||||
inline T & _value(ssize_t index) {return pim_content[pim_index[index].index];}
|
||||
inline T & _value(ssize_t index) { return pim_content[pim_index[index].index]; }
|
||||
|
||||
inline const T & _value(ssize_t index) const {return pim_content[pim_index[index].index];}
|
||||
inline const T & _value(ssize_t index) const { return pim_content[pim_index[index].index]; }
|
||||
|
||||
|
||||
PIVector<T> pim_content;
|
||||
@@ -678,33 +695,28 @@ private:
|
||||
//! // 2 two
|
||||
//! // 4 four
|
||||
//! \endcode
|
||||
template <typename Key, typename T>
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorConst {
|
||||
typedef PIMap<Key, T> MapType;
|
||||
|
||||
public:
|
||||
inline PIMapIteratorConst(const PIMap<Key, T> & map): m(map), pos(-1) {}
|
||||
|
||||
//! \~english Returns current key.
|
||||
//! \~russian Возвращает ключ текущего элемента.
|
||||
//! \~\sa \a value()
|
||||
inline const Key & key() const {
|
||||
return m._key(pos);
|
||||
}
|
||||
inline const Key & key() const { return m._key(pos); }
|
||||
|
||||
//! \~english Returns current value.
|
||||
//! \~russian Возвращает значение текущего элемента.
|
||||
//! \~\sa \a key()
|
||||
inline const T & value() const {
|
||||
return m._value(pos);
|
||||
}
|
||||
inline const T & value() const { return m._value(pos); }
|
||||
|
||||
|
||||
//! \~english Returns true if iterator can jump to next entry
|
||||
//! \~russian Возвращает true если итератор может перейти к следующему элементу.
|
||||
//! \~\sa \a next()
|
||||
inline bool hasNext() const {
|
||||
return pos < (m.size_s() - 1);
|
||||
}
|
||||
inline bool hasNext() const { return pos < (m.size_s() - 1); }
|
||||
|
||||
//! \~english Jump to next entry and return true if new position is valid.
|
||||
//! \~russian Переходит к следующему элементу и возвращает true если он существует.
|
||||
@@ -717,9 +729,8 @@ public:
|
||||
//! \~english Reset iterator to initial position.
|
||||
//! \~russian Переходит на начало.
|
||||
//! \~\sa \a next()
|
||||
inline void reset() {
|
||||
pos = -1;
|
||||
}
|
||||
inline void reset() { pos = -1; }
|
||||
|
||||
private:
|
||||
const MapType & m;
|
||||
ssize_t pos;
|
||||
@@ -754,32 +765,27 @@ private:
|
||||
//! // 2 two
|
||||
//! // 1 one
|
||||
//! \endcode
|
||||
template <typename Key, typename T>
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorConstReverse {
|
||||
typedef PIMap<Key, T> MapType;
|
||||
|
||||
public:
|
||||
inline PIMapIteratorConstReverse(const PIMap<Key, T> & map): m(map), pos(m.size_s()) {}
|
||||
|
||||
//! \~english Returns current key.
|
||||
//! \~russian Возвращает ключ текущего элемента.
|
||||
//! \~\sa \a value()
|
||||
inline const Key & key() const {
|
||||
return m._key(pos);
|
||||
}
|
||||
inline const Key & key() const { return m._key(pos); }
|
||||
|
||||
//! \~english Returns current value.
|
||||
//! \~russian Возвращает значение текущего элемента.
|
||||
//! \~\sa \a key()
|
||||
inline const T & value() const {
|
||||
return m._value(pos);
|
||||
}
|
||||
inline const T & value() const { return m._value(pos); }
|
||||
|
||||
//! \~english Returns true if iterator can jump to next entry
|
||||
//! \~russian Возвращает true если итератор может перейти к следующему элементу.
|
||||
//! \~\sa \a next()
|
||||
inline bool hasNext() const {
|
||||
return pos > 0;
|
||||
}
|
||||
inline bool hasNext() const { return pos > 0; }
|
||||
|
||||
//! \~english Jump to next entry and return true if new position is valid.
|
||||
//! \~russian Переходит к следующему элементу и возвращает true если он существует.
|
||||
@@ -792,9 +798,8 @@ public:
|
||||
//! \~english Reset iterator to initial position.
|
||||
//! \~russian Переходит на начало.
|
||||
//! \~\sa \a next()
|
||||
inline void reset() {
|
||||
pos = m.size_s();
|
||||
}
|
||||
inline void reset() { pos = m.size_s(); }
|
||||
|
||||
private:
|
||||
const MapType & m;
|
||||
ssize_t pos;
|
||||
@@ -830,32 +835,27 @@ private:
|
||||
//! // 2 two_!
|
||||
//! // 4 four_!
|
||||
//! \endcode
|
||||
template <typename Key, typename T>
|
||||
template<typename Key, typename T>
|
||||
class PIMapIterator {
|
||||
typedef PIMap<Key, T> MapType;
|
||||
|
||||
public:
|
||||
inline PIMapIterator(PIMap<Key, T> & map): m(map), pos(-1) {}
|
||||
|
||||
//! \~english Returns current key.
|
||||
//! \~russian Возвращает ключ текущего элемента.
|
||||
//! \~\sa \a value()
|
||||
inline const Key & key() const {
|
||||
return m._key(pos);
|
||||
}
|
||||
inline const Key & key() const { return m._key(pos); }
|
||||
|
||||
//! \~english Returns current value.
|
||||
//! \~russian Возвращает значение текущего элемента.
|
||||
//! \~\sa \a key()
|
||||
inline T & value() {
|
||||
return m._value(pos);
|
||||
}
|
||||
inline T & value() { return m._value(pos); }
|
||||
|
||||
//! \~english Returns true if iterator can jump to next entry
|
||||
//! \~russian Возвращает true если итератор может перейти к следующему элементу.
|
||||
//! \~\sa \a next()
|
||||
inline bool hasNext() const {
|
||||
return pos < (m.size_s() - 1);
|
||||
}
|
||||
inline bool hasNext() const { return pos < (m.size_s() - 1); }
|
||||
|
||||
//! \~english Jump to next entry and return true if new position is valid.
|
||||
//! \~russian Переходит к следующему элементу и возвращает true если он существует.
|
||||
@@ -868,9 +868,8 @@ public:
|
||||
//! \~english Reset iterator to initial position.
|
||||
//! \~russian Переходит на начало.
|
||||
//! \~\sa \a next()
|
||||
inline void reset() {
|
||||
pos = -1;
|
||||
}
|
||||
inline void reset() { pos = -1; }
|
||||
|
||||
private:
|
||||
MapType & m;
|
||||
ssize_t pos;
|
||||
@@ -906,32 +905,27 @@ private:
|
||||
//! // 2 two_!
|
||||
//! // 1 one_!
|
||||
//! \endcode
|
||||
template <typename Key, typename T>
|
||||
template<typename Key, typename T>
|
||||
class PIMapIteratorReverse {
|
||||
typedef PIMap<Key, T> MapType;
|
||||
|
||||
public:
|
||||
inline PIMapIteratorReverse(PIMap<Key, T> & map): m(map), pos(m.size_s()) {}
|
||||
|
||||
//! \~english Returns current key.
|
||||
//! \~russian Возвращает ключ текущего элемента.
|
||||
//! \~\sa \a value()
|
||||
inline const Key & key() const {
|
||||
return m._key(pos);
|
||||
}
|
||||
inline const Key & key() const { return m._key(pos); }
|
||||
|
||||
//! \~english Returns current value.
|
||||
//! \~russian Возвращает значение текущего элемента.
|
||||
//! \~\sa \a key()
|
||||
inline T & value() {
|
||||
return m._value(pos);
|
||||
}
|
||||
inline T & value() { return m._value(pos); }
|
||||
|
||||
//! \~english Returns true if iterator can jump to next entry
|
||||
//! \~russian Возвращает true если итератор может перейти к следующему элементу.
|
||||
//! \~\sa \a next()
|
||||
inline bool hasNext() const {
|
||||
return pos > 0;
|
||||
}
|
||||
inline bool hasNext() const { return pos > 0; }
|
||||
|
||||
//! \~english Jump to next entry and return true if new position is valid.
|
||||
//! \~russian Переходит к следующему элементу и возвращает true если он существует.
|
||||
@@ -944,9 +938,8 @@ public:
|
||||
//! \~english Reset iterator to initial position.
|
||||
//! \~russian Переходит на начало.
|
||||
//! \~\sa \a next()
|
||||
inline void reset() {
|
||||
pos = m.size_s();
|
||||
}
|
||||
inline void reset() { pos = m.size_s(); }
|
||||
|
||||
private:
|
||||
MapType & m;
|
||||
ssize_t pos;
|
||||
@@ -957,12 +950,11 @@ private:
|
||||
//! \~english Output operator to [std::ostream](https://en.cppreference.com/w/cpp/io/basic_ostream).
|
||||
//! \~russian Оператор вывода в [std::ostream](https://ru.cppreference.com/w/cpp/io/basic_ostream).
|
||||
template<typename Key, typename Type>
|
||||
inline std::ostream & operator <<(std::ostream & s, const PIMap<Key, Type> & v) {
|
||||
inline std::ostream & operator<<(std::ostream & s, const PIMap<Key, Type> & v) {
|
||||
s << "{";
|
||||
bool first = true;
|
||||
for (typename PIMap<Key, Type>::const_iterator i = v.begin(); i != v.end(); ++i) {
|
||||
if (!first)
|
||||
s << ", ";
|
||||
if (!first) s << ", ";
|
||||
first = false;
|
||||
s << i.key() << ": " << i.value();
|
||||
}
|
||||
@@ -976,14 +968,13 @@ inline std::ostream & operator <<(std::ostream & s, const PIMap<Key, Type> & v)
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
template<typename Key, typename Type>
|
||||
inline PICout operator <<(PICout s, const PIMap<Key, Type> & v) {
|
||||
inline PICout operator<<(PICout s, const PIMap<Key, Type> & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "{";
|
||||
bool first = true;
|
||||
for (typename PIMap<Key, Type>::const_iterator i = v.begin(); i != v.end(); ++i) {
|
||||
if (!first)
|
||||
s << ", ";
|
||||
if (!first) s << ", ";
|
||||
first = false;
|
||||
s << i.key() << ": " << i.value();
|
||||
}
|
||||
@@ -993,7 +984,9 @@ inline PICout operator <<(PICout s, const PIMap<Key, Type> & v) {
|
||||
}
|
||||
|
||||
template<typename Key, typename Type>
|
||||
inline void piSwap(PIMap<Key, Type> & f, PIMap<Key, Type> & s) {f.swap(s);}
|
||||
inline void piSwap(PIMap<Key, Type> & f, PIMap<Key, Type> & s) {
|
||||
f.swap(s);
|
||||
}
|
||||
|
||||
|
||||
#endif // PIMAP_H
|
||||
|
||||
@@ -48,10 +48,9 @@
|
||||
template<typename Type0, typename Type1>
|
||||
class PIPair {
|
||||
public:
|
||||
|
||||
//! \~english Constructs an empty PIPair.
|
||||
//! \~russian Создает пустой PIPair.
|
||||
PIPair() : first(), second() {}
|
||||
PIPair(): first(), second() {}
|
||||
|
||||
//! \~english Constructs PIPair from [std::tuple](https://en.cppreference.com/w/cpp/utility/tuple).
|
||||
//! \~russian Создает PIPair из [std::tuple](https://ru.cppreference.com/w/cpp/utility/tuple).
|
||||
@@ -86,20 +85,20 @@ public:
|
||||
//! \~english Compare operator with PIPair.
|
||||
//! \~russian Оператор сравнения с PIPair.
|
||||
template<typename Type0, typename Type1>
|
||||
inline bool operator ==(const PIPair<Type0, Type1> & value0, const PIPair<Type0, Type1> & value1) {
|
||||
inline bool operator==(const PIPair<Type0, Type1> & value0, const PIPair<Type0, Type1> & value1) {
|
||||
return (value0.first == value1.first) && (value0.second == value1.second);
|
||||
}
|
||||
|
||||
//! \~english Compare operator with PIPair.
|
||||
//! \~russian Оператор сравнения с PIPair.
|
||||
template<typename Type0, typename Type1>
|
||||
inline bool operator !=(const PIPair<Type0, Type1> & value0, const PIPair<Type0, Type1> & value1) {
|
||||
inline bool operator!=(const PIPair<Type0, Type1> & value0, const PIPair<Type0, Type1> & value1) {
|
||||
return (value0.first != value1.first) || (value0.second != value1.second);
|
||||
}
|
||||
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
template<typename Type0, typename Type1>
|
||||
inline std::ostream & operator <<(std::ostream & s, const PIPair<Type0, Type1> & v) {
|
||||
inline std::ostream & operator<<(std::ostream & s, const PIPair<Type0, Type1> & v) {
|
||||
s << "(" << v.first << ", " << v.second << ")";
|
||||
return s;
|
||||
}
|
||||
@@ -109,7 +108,7 @@ inline std::ostream & operator <<(std::ostream & s, const PIPair<Type0, Type1> &
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
template<typename Type0, typename Type1>
|
||||
inline PICout operator <<(PICout s, const PIPair<Type0, Type1> & v) {
|
||||
inline PICout operator<<(PICout s, const PIPair<Type0, Type1> & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "(" << v.first << ", " << v.second << ")";
|
||||
@@ -125,18 +124,18 @@ inline PICout operator <<(PICout s, const PIPair<Type0, Type1> & v) {
|
||||
//! auto p = createPIPair(1, 'a');
|
||||
//! piCout << p; // (1, a)
|
||||
//! \endcode
|
||||
template< class T1, class T2 >
|
||||
PIPair<T1,T2> createPIPair(const T1 & f, const T2 & s) {
|
||||
return PIPair<T1,T2>(f, s);
|
||||
template<class T1, class T2>
|
||||
PIPair<T1, T2> createPIPair(const T1 & f, const T2 & s) {
|
||||
return PIPair<T1, T2>(f, s);
|
||||
}
|
||||
|
||||
|
||||
//! \~english Creates \a PIPair object, deducing the target type from the types of arguments.
|
||||
//! \~russian Создает \a PIPair выводя типы из аргументов.
|
||||
//! \sa \a createPIPair()
|
||||
template< class T1, class T2 >
|
||||
PIPair<T1,T2> createPIPair(T1 && f, T2 && s) {
|
||||
return PIPair<T1,T2>(std::move(f), std::move(s));
|
||||
template<class T1, class T2>
|
||||
PIPair<T1, T2> createPIPair(T1 && f, T2 && s) {
|
||||
return PIPair<T1, T2>(std::move(f), std::move(s));
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -53,18 +53,23 @@
|
||||
template<typename T>
|
||||
class PIQueue: public PIDeque<T> {
|
||||
public:
|
||||
|
||||
//! \~english Constructs an empty array.
|
||||
//! \~russian Создает пустой массив.
|
||||
PIQueue() {}
|
||||
|
||||
//! \~english Puts an element on the queue.
|
||||
//! \~russian Кладёт элемент в очередь.
|
||||
PIDeque<T> & enqueue(const T & v) {PIDeque<T>::push_front(v); return *this;}
|
||||
PIDeque<T> & enqueue(const T & v) {
|
||||
PIDeque<T>::push_front(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Move an element on the queue.
|
||||
//! \~russian Перемещает элемент в очередь.
|
||||
PIDeque<T> & enqueue(T && v) {PIDeque<T>::push_front(std::move(v)); return *this;}
|
||||
PIDeque<T> & enqueue(T && v) {
|
||||
PIDeque<T>::push_front(std::move(v));
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Retrieves and returns an element from the queue.
|
||||
//! \~russian Забирает и возвращает элемент из очереди.
|
||||
@@ -74,7 +79,7 @@ public:
|
||||
//! Otherwise will be undefined behavior.
|
||||
//! \~russian Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T dequeue() {return PIDeque<T>::take_back();}
|
||||
T dequeue() { return PIDeque<T>::take_back(); }
|
||||
|
||||
//! \~english Head element of the queue.
|
||||
//! \~russian Головной (верхний) элемент очереди.
|
||||
@@ -86,8 +91,8 @@ public:
|
||||
//! \~russian Возвращает ссылку на головной (верхний) элемент очереди.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T & head() {return PIDeque<T>::back();}
|
||||
const T & head() const {return PIDeque<T>::back();}
|
||||
T & head() { return PIDeque<T>::back(); }
|
||||
const T & head() const { return PIDeque<T>::back(); }
|
||||
|
||||
//! \~english Tail element of the queue.
|
||||
//! \~russian Хвостовой (нижний) элемент очереди.
|
||||
@@ -98,16 +103,16 @@ public:
|
||||
//! \~russian Возвращает ссылку на хвостовой (нижний) элемент очереди.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T & tail() {return PIDeque<T>::front();}
|
||||
const T & tail() const {return PIDeque<T>::front();}
|
||||
T & tail() { return PIDeque<T>::front(); }
|
||||
const T & tail() const { return PIDeque<T>::front(); }
|
||||
|
||||
//! \~english Converts \a PIQueue to \a PIVector.
|
||||
//! \~russian Преобразует \a PIQueue в \a PIVector.
|
||||
PIVector<T> toVector() const {return PIVector<T>(PIDeque<T>::data(), PIDeque<T>::size());}
|
||||
PIVector<T> toVector() const { return PIVector<T>(PIDeque<T>::data(), PIDeque<T>::size()); }
|
||||
|
||||
//! \~english Converts \a PIQueue to \a PIDeque.
|
||||
//! \~russian Преобразует \a PIQueue в \a PIDeque.
|
||||
PIDeque<T> toDeque() const {return PIDeque<T>(*this);}
|
||||
PIDeque<T> toDeque() const { return PIDeque<T>(*this); }
|
||||
};
|
||||
|
||||
#endif // PIQUEUE_H
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* \brief Set container
|
||||
*
|
||||
* This file declare PISet
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Set container
|
||||
@@ -34,25 +34,37 @@
|
||||
* set with \a operator[] or with function \a find(). These function
|
||||
* has logarithmic complexity.
|
||||
*/
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
class PISet: public PIMap<T, uchar> {
|
||||
typedef PIMap<T, uchar> _CSet;
|
||||
public:
|
||||
|
||||
public:
|
||||
//! Contructs an empty set
|
||||
PISet() {}
|
||||
|
||||
//! Contructs set with one element "value"
|
||||
PISet(const T & value) {_CSet::insert(value, 0);}
|
||||
PISet(const T & value) { _CSet::insert(value, 0); }
|
||||
|
||||
//! Contructs set with elements "v0" and "v1"
|
||||
PISet(const T & v0, const T & v1) {_CSet::insert(v0, 0); _CSet::insert(v1, 0);}
|
||||
PISet(const T & v0, const T & v1) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
}
|
||||
|
||||
//! Contructs set with elements "v0", "v1" and "v2"
|
||||
PISet(const T & v0, const T & v1, const T & v2) {_CSet::insert(v0, 0); _CSet::insert(v1, 0); _CSet::insert(v2, 0);}
|
||||
PISet(const T & v0, const T & v1, const T & v2) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
_CSet::insert(v2, 0);
|
||||
}
|
||||
|
||||
//! Contructs set with elements "v0", "v1", "v2" and "v3"
|
||||
PISet(const T & v0, const T & v1, const T & v2, const T & v3) {_CSet::insert(v0, 0); _CSet::insert(v1, 0); _CSet::insert(v2, 0); _CSet::insert(v3, 0);}
|
||||
PISet(const T & v0, const T & v1, const T & v2, const T & v3) {
|
||||
_CSet::insert(v0, 0);
|
||||
_CSet::insert(v1, 0);
|
||||
_CSet::insert(v2, 0);
|
||||
_CSet::insert(v3, 0);
|
||||
}
|
||||
|
||||
//! Contructs set from vector of elements
|
||||
PISet(const PIVector<T> & values) {
|
||||
@@ -72,15 +84,27 @@ public:
|
||||
|
||||
typedef T key_type;
|
||||
|
||||
PISet<T> & operator <<(const T & t) {_CSet::insert(t, 0); return *this;}
|
||||
PISet<T> & operator <<(T && t) {_CSet::insert(std::move(t), 0); return *this;}
|
||||
PISet<T> & operator <<(const PISet<T> & other) {(*(_CSet*)this) << *((_CSet*)&other); return *this;}
|
||||
PISet<T> & operator<<(const T & t) {
|
||||
_CSet::insert(t, 0);
|
||||
return *this;
|
||||
}
|
||||
PISet<T> & operator<<(T && t) {
|
||||
_CSet::insert(std::move(t), 0);
|
||||
return *this;
|
||||
}
|
||||
PISet<T> & operator<<(const PISet<T> & other) {
|
||||
(*(_CSet *)this) << *((_CSet *)&other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Returns if element "t" exists in this set
|
||||
bool operator [](const T & t) const {return _CSet::contains(t);}
|
||||
bool operator[](const T & t) const { return _CSet::contains(t); }
|
||||
|
||||
//! Returns if element "t" exists in this set
|
||||
PISet<T> & remove(const T & t) {_CSet::remove(t); return *this;}
|
||||
PISet<T> & remove(const T & t) {
|
||||
_CSet::remove(t);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Unite set with "v"
|
||||
PISet<T> & unite(const PISet<T> & v) {
|
||||
@@ -107,48 +131,76 @@ public:
|
||||
}
|
||||
|
||||
//! Unite set with "v"
|
||||
PISet<T> & operator +=(const PISet<T> & v) {return unite(v);}
|
||||
PISet<T> & operator+=(const PISet<T> & v) { return unite(v); }
|
||||
|
||||
//! Unite set with "v"
|
||||
PISet<T> & operator |=(const PISet<T> & v) {return unite(v);}
|
||||
PISet<T> & operator|=(const PISet<T> & v) { return unite(v); }
|
||||
|
||||
//! Subtract set with "v"
|
||||
PISet<T> & operator -=(const PISet<T> & v) {return subtract(v);}
|
||||
PISet<T> & operator-=(const PISet<T> & v) { return subtract(v); }
|
||||
|
||||
//! Intersect set with "v"
|
||||
PISet<T> & operator &=(const PISet<T> & v) {return intersect(v);}
|
||||
PISet<T> & operator&=(const PISet<T> & v) { return intersect(v); }
|
||||
|
||||
//! Returns content of set as PIVector
|
||||
PIVector<T> toVector() const {PIVector<T> ret; for (typename _CSet::const_iterator i = _CSet::begin(); i != _CSet::end(); ++i) ret << i.key(); return ret;}
|
||||
PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
for (typename _CSet::const_iterator i = _CSet::begin(); i != _CSet::end(); ++i)
|
||||
ret << i.key();
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! Returns content of set as PIDeque
|
||||
PIDeque<T> toDeque() const {PIDeque<T> ret; for (typename _CSet::const_iterator i = _CSet::begin(); i != _CSet::end(); ++i) ret << i.key(); return ret;}
|
||||
|
||||
PIDeque<T> toDeque() const {
|
||||
PIDeque<T> ret;
|
||||
for (typename _CSet::const_iterator i = _CSet::begin(); i != _CSet::end(); ++i)
|
||||
ret << i.key();
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PISet \brief Returns unite of two sets
|
||||
template <typename T> PISet<T> operator +(const PISet<T> & v0, const PISet<T> & v1) {PISet<T> ret(v0); ret.unite(v1); return ret;}
|
||||
template<typename T>
|
||||
PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
ret.unite(v1);
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns subtraction of two sets
|
||||
template <typename T> PISet<T> operator -(const PISet<T> & v0, const PISet<T> & v1) {PISet<T> ret(v0); ret.subtract(v1); return ret;}
|
||||
template<typename T>
|
||||
PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
ret.subtract(v1);
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns unite of two sets
|
||||
template <typename T> PISet<T> operator |(const PISet<T> & v0, const PISet<T> & v1) {PISet<T> ret(v0); ret.unite(v1); return ret;}
|
||||
template<typename T>
|
||||
PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
ret.unite(v1);
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \relatesalso PISet \brief Returns intersetion of two sets
|
||||
template <typename T> PISet<T> operator &(const PISet<T> & v0, const PISet<T> & v1) {PISet<T> ret(v0); ret.intersect(v1); return ret;}
|
||||
template<typename T>
|
||||
PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
||||
PISet<T> ret(v0);
|
||||
ret.intersect(v1);
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
template<typename Type>
|
||||
inline PICout operator <<(PICout s, const PISet<Type> & v) {
|
||||
inline PICout operator<<(PICout s, const PISet<Type> & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "{";
|
||||
bool first = true;
|
||||
for (typename PIMap<Type, uchar>::const_iterator i = v.begin(); i != v.end(); ++i) {
|
||||
if (!first)
|
||||
s << ", ";
|
||||
if (!first) s << ", ";
|
||||
first = false;
|
||||
s << i.key();
|
||||
}
|
||||
|
||||
@@ -34,8 +34,8 @@
|
||||
#ifndef PISTACK_H
|
||||
#define PISTACK_H
|
||||
|
||||
#include "pivector.h"
|
||||
#include "pideque.h"
|
||||
#include "pivector.h"
|
||||
|
||||
//! \addtogroup Containers
|
||||
//! \{
|
||||
@@ -53,18 +53,23 @@
|
||||
template<typename T>
|
||||
class PIStack: public PIVector<T> {
|
||||
public:
|
||||
|
||||
//! \~english Constructs an empty array.
|
||||
//! \~russian Создает пустой массив.
|
||||
PIStack() {}
|
||||
|
||||
//! \~english Puts an element on the stack.
|
||||
//! \~russian Кладёт элемент в стек.
|
||||
PIVector<T> & push(const T & v) {PIVector<T>::push_back(v); return *this;}
|
||||
PIVector<T> & push(const T & v) {
|
||||
PIVector<T>::push_back(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Move an element on the stack.
|
||||
//! \~russian Перемещает элемент в стек.
|
||||
PIVector<T> & push(T && v) {PIVector<T>::push_back(std::move(v)); return *this;}
|
||||
PIVector<T> & push(T && v) {
|
||||
PIVector<T>::push_back(std::move(v));
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Retrieves and returns an element from the stack.
|
||||
//! \~russian Забирает и возвращает элемент из стека.
|
||||
@@ -74,7 +79,7 @@ public:
|
||||
//! Otherwise will be undefined behavior.
|
||||
//! \~russian Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T pop() {return PIVector<T>::take_back();}
|
||||
T pop() { return PIVector<T>::take_back(); }
|
||||
|
||||
//! \~english Top element of the stack
|
||||
//! \~russian Верхний элемент стека.
|
||||
@@ -86,16 +91,16 @@ public:
|
||||
//! \~russian Возвращает ссылку на верхний элемент стека.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
T & top() {return PIVector<T>::back();}
|
||||
const T & top() const {return PIVector<T>::back();}
|
||||
T & top() { return PIVector<T>::back(); }
|
||||
const T & top() const { return PIVector<T>::back(); }
|
||||
|
||||
//! \~english Converts \a PIStack to \a PIVector.
|
||||
//! \~russian Преобразует \a PIStack в \a PIVector.
|
||||
PIVector<T> toVector() const {return PIVector<T>(*this);}
|
||||
PIVector<T> toVector() const { return PIVector<T>(*this); }
|
||||
|
||||
//! \~english Converts \a PIStack to \a PIDeque.
|
||||
//! \~russian Преобразует \a PIStack в \a PIDeque.
|
||||
PIDeque<T> toDeque() const {return PIDeque<T>(PIVector<T>::data(), PIVector<T>::size());}
|
||||
PIDeque<T> toDeque() const { return PIDeque<T>(PIVector<T>::data(), PIVector<T>::size()); }
|
||||
};
|
||||
|
||||
#endif // PISTACK_H
|
||||
|
||||
@@ -114,22 +114,20 @@
|
||||
//! - Вставка и удаление элементов — линейная по расстоянию до конца массива 𝓞(n)
|
||||
//!
|
||||
//! \~\sa \a PIDeque, \a PIMap
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
class PIVector {
|
||||
public:
|
||||
typedef bool (*CompareFunc)(const T & , const T & );
|
||||
typedef bool (*CompareFunc)(const T &, const T &);
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef const T* const_pointer;
|
||||
typedef T& reference;
|
||||
typedef const T& const_reference;
|
||||
typedef T * pointer;
|
||||
typedef const T * const_pointer;
|
||||
typedef T & reference;
|
||||
typedef const T & const_reference;
|
||||
typedef size_t size_type;
|
||||
|
||||
//! \~english Constructs an empty array.
|
||||
//! \~russian Создает пустой массив.
|
||||
inline PIVector() {
|
||||
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
|
||||
}
|
||||
inline PIVector() { PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) }
|
||||
|
||||
//! \~english Contructs array from raw `data`.
|
||||
//! This constructor reserve `size` and copy from `data` pointer.
|
||||
@@ -208,7 +206,7 @@ public:
|
||||
|
||||
//! \~english Assign operator.
|
||||
//! \~russian Оператор присваивания.
|
||||
inline PIVector<T> & operator =(const PIVector<T> & v) {
|
||||
inline PIVector<T> & operator=(const PIVector<T> & v) {
|
||||
if (this == &v) return *this;
|
||||
clear();
|
||||
alloc(v.piv_size);
|
||||
@@ -218,360 +216,330 @@ public:
|
||||
|
||||
//! \~english Assign move operator.
|
||||
//! \~russian Оператор перемещающего присваивания.
|
||||
inline PIVector<T> & operator =(PIVector<T> && v) {
|
||||
inline PIVector<T> & operator=(PIVector<T> && v) {
|
||||
swap(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
class iterator {
|
||||
friend class PIVector<T>;
|
||||
|
||||
private:
|
||||
inline iterator(PIVector<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
PIVector<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline T & operator *() {return (*parent)[pos];}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline T & operator ->() {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline T & operator*() { return (*parent)[pos]; }
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline T & operator->() { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline iterator & operator ++() {
|
||||
inline iterator & operator++() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator operator ++(int) {
|
||||
inline iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
inline iterator & operator --() {
|
||||
inline iterator & operator--() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator operator --(int) {
|
||||
inline iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline iterator & operator +=(const iterator & it) {
|
||||
inline iterator & operator+=(const iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator +=(size_t p) {
|
||||
inline iterator & operator+=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator -=(const iterator & it) {
|
||||
inline iterator & operator-=(const iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline iterator & operator -=(size_t p) {
|
||||
inline iterator & operator-=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline iterator operator -(size_t p, const iterator & it) {return it - p;}
|
||||
friend inline iterator operator -(const iterator & it, size_t p) {
|
||||
friend inline iterator operator-(size_t p, const iterator & it) { return it - p; }
|
||||
friend inline iterator operator-(const iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos - it2.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const iterator & it1, const iterator & it2) { return it1.pos - it2.pos; }
|
||||
|
||||
friend inline iterator operator +(size_t p, const iterator & it) {return it + p;}
|
||||
friend inline iterator operator +(const iterator & it, size_t p) {
|
||||
friend inline iterator operator+(size_t p, const iterator & it) { return it + p; }
|
||||
friend inline iterator operator+(const iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const iterator & it1, const iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const iterator & it1, const iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const iterator & it1, const iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const iterator & it1, const iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const iterator & it1, const iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class const_iterator {
|
||||
friend class PIVector<T>;
|
||||
|
||||
private:
|
||||
inline const_iterator(const PIVector<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIVector<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline const_iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline const_iterator & operator ++() {
|
||||
inline const_iterator & operator++() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator operator ++(int) {
|
||||
inline const_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
inline const_iterator & operator --() {
|
||||
inline const_iterator & operator--() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator operator --(int) {
|
||||
inline const_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline const_iterator & operator +=(const const_iterator & it) {
|
||||
inline const_iterator & operator+=(const const_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator +=(size_t p) {
|
||||
inline const_iterator & operator+=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator -=(const const_iterator & it) {
|
||||
inline const_iterator & operator-=(const const_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_iterator & operator -=(size_t p) {
|
||||
inline const_iterator & operator-=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline const_iterator operator -(size_t p, const const_iterator & it) {return it - p;}
|
||||
friend inline const_iterator operator -(const const_iterator & it, size_t p) {
|
||||
friend inline const_iterator operator-(size_t p, const const_iterator & it) { return it - p; }
|
||||
friend inline const_iterator operator-(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos - it2.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; }
|
||||
|
||||
friend inline const_iterator operator +(size_t p, const const_iterator & it) {return it + p;}
|
||||
friend inline const_iterator operator +(const const_iterator & it, size_t p) {
|
||||
friend inline const_iterator operator+(size_t p, const const_iterator & it) { return it + p; }
|
||||
friend inline const_iterator operator+(const const_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const const_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const const_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const const_iterator & it1, const const_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class reverse_iterator {
|
||||
friend class PIVector<T>;
|
||||
|
||||
private:
|
||||
inline reverse_iterator(PIVector<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
PIVector<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline reverse_iterator(): parent(0), pos(0) {}
|
||||
|
||||
inline T & operator *() {return (*parent)[pos];}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline T & operator ->() {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline T & operator*() { return (*parent)[pos]; }
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline T & operator->() { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline reverse_iterator & operator ++() {
|
||||
inline reverse_iterator & operator++() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator operator ++(int) {
|
||||
inline reverse_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
inline reverse_iterator & operator --() {
|
||||
inline reverse_iterator & operator--() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator operator --(int) {
|
||||
inline reverse_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline reverse_iterator & operator +=(const reverse_iterator & it) {
|
||||
inline reverse_iterator & operator+=(const reverse_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator +=(size_t p) {
|
||||
inline reverse_iterator & operator+=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator -=(const reverse_iterator & it) {
|
||||
inline reverse_iterator & operator-=(const reverse_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline reverse_iterator & operator -=(size_t p) {
|
||||
inline reverse_iterator & operator-=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline reverse_iterator operator -(size_t p, const reverse_iterator & it) {return it - p;}
|
||||
friend inline reverse_iterator operator -(const reverse_iterator & it, size_t p) {
|
||||
friend inline reverse_iterator operator-(size_t p, const reverse_iterator & it) { return it - p; }
|
||||
friend inline reverse_iterator operator-(const reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it2.pos - it1.pos;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator-(const reverse_iterator & it1, const reverse_iterator & it2) { return it2.pos - it1.pos; }
|
||||
|
||||
friend inline reverse_iterator operator +(size_t p, const reverse_iterator & it) {return it + p;}
|
||||
friend inline reverse_iterator operator +(const reverse_iterator & it, size_t p) {
|
||||
friend inline reverse_iterator operator+(size_t p, const reverse_iterator & it) { return it + p; }
|
||||
friend inline reverse_iterator operator+(const reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const reverse_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const reverse_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const reverse_iterator & it1, const reverse_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const reverse_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const reverse_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const reverse_iterator & it1, const reverse_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
class const_reverse_iterator {
|
||||
friend class PIVector<T>;
|
||||
|
||||
private:
|
||||
inline const_reverse_iterator(const PIVector<T> * v, ssize_t p): parent(v), pos(p) {}
|
||||
const PIVector<T> * parent;
|
||||
ssize_t pos;
|
||||
|
||||
public:
|
||||
typedef T value_type;
|
||||
typedef T* pointer;
|
||||
typedef T& reference;
|
||||
typedef T * pointer;
|
||||
typedef T & reference;
|
||||
typedef std::ptrdiff_t difference_type;
|
||||
typedef std::random_access_iterator_tag iterator_category;
|
||||
|
||||
inline const_reverse_iterator(): parent(0), pos(0) {}
|
||||
inline const T & operator *() const {return (*parent)[pos];}
|
||||
inline const T & operator ->() const {return (*parent)[pos];}
|
||||
inline const T & operator*() const { return (*parent)[pos]; }
|
||||
inline const T & operator->() const { return (*parent)[pos]; }
|
||||
|
||||
inline const_reverse_iterator & operator ++() {
|
||||
inline const_reverse_iterator & operator++() {
|
||||
--pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator operator ++(int) {
|
||||
inline const_reverse_iterator operator++(int) {
|
||||
auto tmp = *this;
|
||||
--*this;
|
||||
return tmp;
|
||||
}
|
||||
inline const_reverse_iterator & operator --() {
|
||||
inline const_reverse_iterator & operator--() {
|
||||
++pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator operator --(int) {
|
||||
inline const_reverse_iterator operator--(int) {
|
||||
auto tmp = *this;
|
||||
++*this;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline const_reverse_iterator & operator +=(const const_reverse_iterator & it) {
|
||||
inline const_reverse_iterator & operator+=(const const_reverse_iterator & it) {
|
||||
pos -= it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator +=(size_t p) {
|
||||
inline const_reverse_iterator & operator+=(size_t p) {
|
||||
pos -= p;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator -=(const const_reverse_iterator & it) {
|
||||
inline const_reverse_iterator & operator-=(const const_reverse_iterator & it) {
|
||||
pos += it.pos;
|
||||
return *this;
|
||||
}
|
||||
inline const_reverse_iterator & operator -=(size_t p) {
|
||||
inline const_reverse_iterator & operator-=(size_t p) {
|
||||
pos += p;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend inline const_reverse_iterator operator -(size_t p, const const_reverse_iterator & it) {return it - p;}
|
||||
friend inline const_reverse_iterator operator -(const const_reverse_iterator & it, size_t p) {
|
||||
friend inline const_reverse_iterator operator-(size_t p, const const_reverse_iterator & it) { return it - p; }
|
||||
friend inline const_reverse_iterator operator-(const const_reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp -= p;
|
||||
return tmp;
|
||||
}
|
||||
friend inline std::ptrdiff_t operator -(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
friend inline std::ptrdiff_t operator-(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it2.pos - it1.pos;
|
||||
}
|
||||
|
||||
friend inline const_reverse_iterator operator +(size_t p, const const_reverse_iterator & it) {return it + p;}
|
||||
friend inline const_reverse_iterator operator +(const const_reverse_iterator & it, size_t p) {
|
||||
friend inline const_reverse_iterator operator+(size_t p, const const_reverse_iterator & it) { return it + p; }
|
||||
friend inline const_reverse_iterator operator+(const const_reverse_iterator & it, size_t p) {
|
||||
auto tmp = it;
|
||||
tmp += p;
|
||||
return tmp;
|
||||
}
|
||||
|
||||
inline bool operator ==(const const_reverse_iterator & it) const {return (pos == it.pos);}
|
||||
inline bool operator !=(const const_reverse_iterator & it) const {return (pos != it.pos);}
|
||||
friend inline bool operator <(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos < it2.pos;
|
||||
}
|
||||
friend inline bool operator <=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos <= it2.pos;
|
||||
}
|
||||
friend inline bool operator >(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos > it2.pos;
|
||||
}
|
||||
friend inline bool operator >=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) {
|
||||
return it1.pos >= it2.pos;
|
||||
}
|
||||
inline bool operator==(const const_reverse_iterator & it) const { return (pos == it.pos); }
|
||||
inline bool operator!=(const const_reverse_iterator & it) const { return (pos != it.pos); }
|
||||
friend inline bool operator<(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos < it2.pos; }
|
||||
friend inline bool operator<=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos <= it2.pos; }
|
||||
friend inline bool operator>(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos > it2.pos; }
|
||||
friend inline bool operator>=(const const_reverse_iterator & it1, const const_reverse_iterator & it2) { return it1.pos >= it2.pos; }
|
||||
};
|
||||
|
||||
//! \~english Iterator to the first element.
|
||||
@@ -582,7 +550,7 @@ public:
|
||||
//! \~russian Если массив пустой, возвращаемый итератор будет равен \a end().
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a end(), \a rbegin(), \a rend()
|
||||
inline iterator begin() {return iterator(this, 0);}
|
||||
inline iterator begin() { return iterator(this, 0); }
|
||||
|
||||
//! \~english Iterator to the element following the last element.
|
||||
//! \~russian Итератор на элемент, следующий за последним элементом.
|
||||
@@ -594,10 +562,10 @@ public:
|
||||
//! попытка доступа к нему приведёт к выходу за разрешенную память.
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a begin(), \a rbegin(), \a rend()
|
||||
inline iterator end() {return iterator(this, piv_size);}
|
||||
inline iterator end() { return iterator(this, piv_size); }
|
||||
|
||||
inline const_iterator begin() const {return const_iterator(this, 0);}
|
||||
inline const_iterator end() const {return const_iterator(this, piv_size);}
|
||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||
inline const_iterator end() const { return const_iterator(this, piv_size); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the first element of the reversed array.
|
||||
//! \~russian Обратный итератор на первый элемент.
|
||||
@@ -610,7 +578,7 @@ public:
|
||||
//! Если массив пустой, то совпадает с итератором \a rend().
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a rend(), \a begin(), \a end()
|
||||
inline reverse_iterator rbegin() {return reverse_iterator(this, piv_size - 1);}
|
||||
inline reverse_iterator rbegin() { return reverse_iterator(this, piv_size - 1); }
|
||||
|
||||
//! \~english Returns a reverse iterator to the element
|
||||
//! following the last element of the reversed array.
|
||||
@@ -625,25 +593,25 @@ public:
|
||||
//! попытка доступа к нему приведёт к выходу за разрешенную память.
|
||||
//! \~\return \ref stl_iterators
|
||||
//! \~\sa \a rbegin(), \a begin(), \a end()
|
||||
inline reverse_iterator rend() {return reverse_iterator(this, -1);}
|
||||
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
||||
|
||||
inline const_reverse_iterator rbegin() const {return const_reverse_iterator(this, piv_size - 1);}
|
||||
inline const_reverse_iterator rend() const {return const_reverse_iterator(this, -1);}
|
||||
inline const_reverse_iterator rbegin() const { return const_reverse_iterator(this, piv_size - 1); }
|
||||
inline const_reverse_iterator rend() const { return const_reverse_iterator(this, -1); }
|
||||
|
||||
//! \~english Number of elements in the container.
|
||||
//! \~russian Количество элементов массива.
|
||||
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t size() const {return piv_size;}
|
||||
inline size_t size() const { return piv_size; }
|
||||
|
||||
//! \~english Number of elements in the container as signed value.
|
||||
//! \~russian Количество элементов массива в виде знакового числа.
|
||||
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline ssize_t size_s() const {return piv_size;}
|
||||
inline ssize_t size_s() const { return piv_size; }
|
||||
|
||||
//! \~english Same as \a size().
|
||||
//! \~russian Синоним \a size().
|
||||
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline size_t length() const {return piv_size;}
|
||||
inline size_t length() const { return piv_size; }
|
||||
|
||||
//! \~english Number of elements that the container has currently allocated space for.
|
||||
//! \~russian Количество элементов, для которого сейчас выделена память массивом.
|
||||
@@ -651,7 +619,7 @@ public:
|
||||
//! \~english To find out the actual number of items, use the function \a size().
|
||||
//! \~russian Чтобы узнать фактическое количество элементов используйте функцию \a size().
|
||||
//! \~\sa \a reserve(), \a size(), \a size_s()
|
||||
inline size_t capacity() const {return piv_rsize;}
|
||||
inline size_t capacity() const { return piv_rsize; }
|
||||
|
||||
//! \~english Checks if the container has no elements.
|
||||
//! \~russian Проверяет пуст ли массив.
|
||||
@@ -659,7 +627,7 @@ public:
|
||||
//! \~english **true** if the container is empty, **false** otherwise
|
||||
//! \~russian **true** если массив пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isEmpty() const {return (piv_size == 0);}
|
||||
inline bool isEmpty() const { return (piv_size == 0); }
|
||||
|
||||
//! \~english Checks if the container has elements.
|
||||
//! \~russian Проверяет не пуст ли массив.
|
||||
@@ -667,7 +635,7 @@ public:
|
||||
//! \~english **true** if the container is not empty, **false** otherwise
|
||||
//! \~russian **true** если массив не пуст, **false** иначе.
|
||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||
inline bool isNotEmpty() const {return (piv_size > 0);}
|
||||
inline bool isNotEmpty() const { return (piv_size > 0); }
|
||||
|
||||
//! \~english Tests whether at least one element in the array
|
||||
//! passes the test implemented by the provided function `test`.
|
||||
@@ -735,8 +703,8 @@ public:
|
||||
//! piCout << v; // {1, 2, 5, 9}
|
||||
//! \endcode
|
||||
//! \~\sa \a at()
|
||||
inline T & operator [](size_t index) {return piv_data[index];}
|
||||
inline const T & operator [](size_t index) const {return piv_data[index];}
|
||||
inline T & operator[](size_t index) { return piv_data[index]; }
|
||||
inline const T & operator[](size_t index) const { return piv_data[index]; }
|
||||
|
||||
//! \~english Read only access to element by `index`.
|
||||
//! \~russian Доступ исключительно на чтение к элементу по индексу `index`.
|
||||
@@ -747,7 +715,7 @@ public:
|
||||
//! \~russian Индекс элемента считается от `0`.
|
||||
//! Индекс элемента должен лежать в пределах от `0` до `size()-1`.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline const T & at(size_t index) const {return piv_data[index];}
|
||||
inline const T & at(size_t index) const { return piv_data[index]; }
|
||||
|
||||
|
||||
//! \~english Returns the first element of the array that
|
||||
@@ -758,8 +726,10 @@ public:
|
||||
//! \~\sa \a indexWhere()
|
||||
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
|
||||
ssize_t i = indexWhere(test, start);
|
||||
if (i < 0) return def;
|
||||
else return at(i);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
return at(i);
|
||||
}
|
||||
|
||||
//! \~english Returns the last element of the array that
|
||||
@@ -770,8 +740,10 @@ public:
|
||||
//! \~\sa \a lastIndexWhere()
|
||||
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
|
||||
ssize_t i = lastIndexWhere(test, start);
|
||||
if (i < 0) return def;
|
||||
else return at(i);
|
||||
if (i < 0)
|
||||
return def;
|
||||
else
|
||||
return at(i);
|
||||
}
|
||||
|
||||
//! \~english Last element.
|
||||
@@ -783,8 +755,8 @@ public:
|
||||
//! \~russian Возвращает ссылку на последний элемент в массиве.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline T & back() {return piv_data[piv_size - 1];}
|
||||
inline const T & back() const {return piv_data[piv_size - 1];}
|
||||
inline T & back() { return piv_data[piv_size - 1]; }
|
||||
inline const T & back() const { return piv_data[piv_size - 1]; }
|
||||
|
||||
//! \~english Last element.
|
||||
//! \~russian Первый элемент массива.
|
||||
@@ -795,12 +767,12 @@ public:
|
||||
//! \~russian Возвращает ссылку на пенрвый элемент в массиве.
|
||||
//! Эта функция предполагает, что массив не пустой.
|
||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
inline T & front() {return piv_data[0];}
|
||||
inline const T & front() const {return piv_data[0];}
|
||||
inline T & front() { return piv_data[0]; }
|
||||
inline const T & front() const { return piv_data[0]; }
|
||||
|
||||
//! \~english Compare operator with array `v`.
|
||||
//! \~russian Оператор сравнения с массивом `v`.
|
||||
inline bool operator ==(const PIVector<T> & v) const {
|
||||
inline bool operator==(const PIVector<T> & v) const {
|
||||
if (piv_size != v.piv_size) return false;
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
if (v[i] != piv_data[i]) return false;
|
||||
@@ -810,7 +782,7 @@ public:
|
||||
|
||||
//! \~english Compare operator with array `v`.
|
||||
//! \~russian Оператор сравнения с массивом `v`.
|
||||
inline bool operator !=(const PIVector<T> & v) const {return !(*this == v);}
|
||||
inline bool operator!=(const PIVector<T> & v) const { return !(*this == v); }
|
||||
|
||||
//! \~english Tests if element `e` exists in the array.
|
||||
//! \~russian Проверяет наличие элемента `e` в массиве.
|
||||
@@ -869,7 +841,7 @@ public:
|
||||
start = piv_size + start;
|
||||
if (start < 0) start = 0;
|
||||
}
|
||||
for (const T & e : v) {
|
||||
for (const T & e: v) {
|
||||
bool c = false;
|
||||
for (size_t i = start; i < piv_size; ++i) {
|
||||
if (e == piv_data[i]) {
|
||||
@@ -1122,7 +1094,7 @@ public:
|
||||
//! memcpy(vec.data(1), a, 2 * sizeof(int));
|
||||
//! piCout << v; // {2, 12, 13, 2}
|
||||
//! \endcode
|
||||
inline T * data(size_t index = 0) {return &(piv_data[index]);}
|
||||
inline T * data(size_t index = 0) { return &(piv_data[index]); }
|
||||
|
||||
//! \~english Read only pointer to array
|
||||
//! \~russian Указатель на память массива только для чтения.
|
||||
@@ -1141,7 +1113,7 @@ public:
|
||||
//! memcpy(a, v.data(), a.size() * sizeof(int));
|
||||
//! piCout << a[0] << a[1] << a[2]; // 1 3 5
|
||||
//! \endcode
|
||||
inline const T * data(size_t index = 0) const {return &(piv_data[index]);}
|
||||
inline const T * data(size_t index = 0) const { return &(piv_data[index]); }
|
||||
|
||||
//! \~english Creates sub-array of this array.
|
||||
//! \~russian Создает подмассив, то есть кусок из текущего массива.
|
||||
@@ -1172,17 +1144,13 @@ public:
|
||||
//! \~english Reserved memory will not be released.
|
||||
//! \~russian Зарезервированная память не освободится.
|
||||
//! \~\sa \a resize()
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector<T> & clear() {
|
||||
deleteT(piv_data, piv_size);
|
||||
piv_size = 0;
|
||||
return *this;
|
||||
}
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector<T> & clear() {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, piv_size)
|
||||
piv_size = 0;
|
||||
@@ -1228,21 +1196,17 @@ public:
|
||||
//! \~english Same as \a fill().
|
||||
//! \~russian Тоже самое что и \a fill().
|
||||
//! \~\sa \a fill(), \a resize()
|
||||
inline PIVector<T> & assign(const T & e = T()) {return fill(e);}
|
||||
inline PIVector<T> & assign(const T & e = T()) { return fill(e); }
|
||||
|
||||
//! \~english First does `resize(new_size)` then `fill(e)`.
|
||||
//! \~russian Сначала делает `resize(new_size)`, затем `fill(e)`.
|
||||
//! \~\sa \a fill(), \a resize()
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector<T> & assign(size_t new_size, const T & f) {
|
||||
resize(new_size);
|
||||
return fill(f);
|
||||
}
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector<T> & assign(size_t new_size, const T & f) {
|
||||
_resizeRaw(new_size);
|
||||
return fill(f);
|
||||
@@ -1290,25 +1254,21 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector<T> & _resizeRaw(size_t new_size) {
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
if (new_size > piv_size) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-piv_size));
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - piv_size));
|
||||
}
|
||||
if (new_size < piv_size) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, (piv_size-new_size));
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, (piv_size - new_size));
|
||||
}
|
||||
#endif
|
||||
alloc(new_size);
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline void _copyRaw(T * dst, const T * src, size_t size) {
|
||||
newT(dst, src, size);
|
||||
}
|
||||
inline void _copyRaw(T * dst, const T * src, size_t size) { newT(dst, src, size); }
|
||||
|
||||
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
||||
//! \~russian Резервируется память под как минимум `new_size` элементов.
|
||||
@@ -1347,7 +1307,7 @@ public:
|
||||
alloc(piv_size + 1);
|
||||
if (index < piv_size - 1) {
|
||||
size_t os = piv_size - index - 1;
|
||||
memmove((void*)(piv_data + index + 1), (const void*)(piv_data + index), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index + 1), (const void *)(piv_data + index), os * sizeof(T));
|
||||
}
|
||||
PIINTROSPECTION_CONTAINER_USED(T, 1)
|
||||
elementNew(piv_data + index, e);
|
||||
@@ -1364,7 +1324,7 @@ public:
|
||||
alloc(piv_size + 1);
|
||||
if (index < piv_size - 1) {
|
||||
size_t os = piv_size - index - 1;
|
||||
memmove((void*)(piv_data + index + 1), (const void*)(piv_data + index), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index + 1), (const void *)(piv_data + index), os * sizeof(T));
|
||||
}
|
||||
PIINTROSPECTION_CONTAINER_USED(T, 1)
|
||||
elementNew(piv_data + index, std::move(e));
|
||||
@@ -1388,7 +1348,7 @@ public:
|
||||
ssize_t os = piv_size - index;
|
||||
alloc(piv_size + v.piv_size);
|
||||
if (os > 0) {
|
||||
memmove((void*)(piv_data + index + v.piv_size), (const void*)(piv_data + index), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index + v.piv_size), (const void *)(piv_data + index), os * sizeof(T));
|
||||
}
|
||||
newT(piv_data + index, v.piv_data, v.piv_size);
|
||||
return *this;
|
||||
@@ -1409,7 +1369,7 @@ public:
|
||||
ssize_t os = piv_size - index;
|
||||
alloc(piv_size + init_list.size());
|
||||
if (os > 0) {
|
||||
memmove((void*)(piv_data + index + init_list.size()), (const void*)(piv_data + index), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index + init_list.size()), (const void *)(piv_data + index), os * sizeof(T));
|
||||
}
|
||||
newT(piv_data + index, init_list.begin(), init_list.size());
|
||||
return *this;
|
||||
@@ -1434,7 +1394,7 @@ public:
|
||||
} else {
|
||||
size_t os = piv_size - index - count;
|
||||
deleteT(piv_data + index, count);
|
||||
memmove((void*)(piv_data + index), (const void*)(piv_data + index + count), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index), (const void *)(piv_data + index + count), os * sizeof(T));
|
||||
piv_size -= count;
|
||||
}
|
||||
return *this;
|
||||
@@ -1446,7 +1406,7 @@ public:
|
||||
//! \~english This operation is very fast and never fails.
|
||||
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
|
||||
inline void swap(PIVector<T> & v) {
|
||||
piSwap<T*>(piv_data, v.piv_data);
|
||||
piSwap<T *>(piv_data, v.piv_data);
|
||||
piSwap<size_t>(piv_size, v.piv_size);
|
||||
piSwap<size_t>(piv_rsize, v.piv_rsize);
|
||||
}
|
||||
@@ -1490,23 +1450,18 @@ public:
|
||||
//! Complexity `O(N·log(N))`.
|
||||
//! \~russian Сохранность порядка элементов, имеющих одинаковое значение, не гарантируется.
|
||||
//! Для сравнения элементов используется функция сравнения `comp`.
|
||||
//! Функция сравнения, возвращает `true` если первый аргумент меньше второго.
|
||||
//! Сигнатура функции сравнения должна быть эквивалентна следующей:
|
||||
//! \code
|
||||
//! bool comp(const T &a, const T &b);
|
||||
//! \endcode
|
||||
//! Сигнатура не обязана содержать const &, однако, функция не может изменять переданные объекты.
|
||||
//! Функция обязана возвращать `false` для одинаковых элементов,
|
||||
//! иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||
//! Для сортировки используется функция [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort).
|
||||
//! Сложность сортировки `O(N·log(N))`.
|
||||
//! Функция сравнения, возвращает `true` если первый аргумент меньше
|
||||
//! второго. Сигнатура функции сравнения должна быть эквивалентна следующей: \code bool comp(const T &a, const T &b); \endcode Сигнатура
|
||||
//! не обязана содержать const &, однако, функция не может изменять переданные объекты. Функция обязана возвращать `false` для
|
||||
//! одинаковых элементов, иначе это приведёт к неопределённому поведению программы и ошибкам памяти. Для сортировки используется функция
|
||||
//! [std::sort](https://ru.cppreference.com/w/cpp/algorithm/sort). Сложность сортировки `O(N·log(N))`.
|
||||
//! \~\code
|
||||
//! PIVector<int> v{5, 7, 4, 2, 8, 6, 1, 9, 0, 3};
|
||||
//! v.sort([](const int & a, const int & b){return a > b;});
|
||||
//! piCout << v; // {9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
|
||||
//! \endcode
|
||||
//! \~\sa \a sort()
|
||||
inline PIVector<T> & sort(std::function<bool(const T &a, const T &b)> comp) {
|
||||
inline PIVector<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
|
||||
std::sort(begin(), end(), comp);
|
||||
return *this;
|
||||
}
|
||||
@@ -1528,9 +1483,9 @@ public:
|
||||
//! \endcode
|
||||
//! \~\sa \a reversed()
|
||||
inline PIVector<T> & reverse() {
|
||||
size_t s2 = piv_size/2;
|
||||
size_t s2 = piv_size / 2;
|
||||
for (size_t i = 0; i < s2; ++i) {
|
||||
piSwap<T>(piv_data[i], piv_data[piv_size-i-1]);
|
||||
piSwap<T>(piv_data[i], piv_data[piv_size - i - 1]);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
@@ -1560,8 +1515,10 @@ public:
|
||||
//! \~\sa \a resize()
|
||||
inline PIVector<T> & enlarge(ssize_t add_size, const T & e = T()) {
|
||||
ssize_t ns = size_s() + add_size;
|
||||
if (ns <= 0) clear();
|
||||
else resize(size_t(ns), e);
|
||||
if (ns <= 0)
|
||||
clear();
|
||||
else
|
||||
resize(size_t(ns), e);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -1731,7 +1688,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a prepend(), \a push_front(), \a push_back(), \a insert()
|
||||
inline PIVector<T> & append(const T & e) {return push_back(e);}
|
||||
inline PIVector<T> & append(const T & e) { return push_back(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1739,7 +1696,7 @@ public:
|
||||
//! \~english Overloaded function.
|
||||
//! \~russian Перегруженая функция.
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & append(T && e) {return push_back(std::move(e));}
|
||||
inline PIVector<T> & append(T && e) { return push_back(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given elements to the end of the array.
|
||||
//! \~russian Добавляет элементы в конец массива.
|
||||
@@ -1751,7 +1708,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & append(std::initializer_list<T> init_list) {return push_back(init_list);}
|
||||
inline PIVector<T> & append(std::initializer_list<T> init_list) { return push_back(init_list); }
|
||||
|
||||
//! \~english Appends the given array `v` to the end of the array.
|
||||
//! \~russian Добавляет массив `v` в конец массива.
|
||||
@@ -1764,7 +1721,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & append(const PIVector<T> & v) {return push_back(v);}
|
||||
inline PIVector<T> & append(const PIVector<T> & v) { return push_back(v); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1775,7 +1732,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & operator <<(const T & e) {return push_back(e);}
|
||||
inline PIVector<T> & operator<<(const T & e) { return push_back(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the end of the array.
|
||||
//! \~russian Добавляет элемент `e` в конец массива.
|
||||
@@ -1786,7 +1743,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & operator <<(T && e) {return push_back(std::move(e));}
|
||||
inline PIVector<T> & operator<<(T && e) { return push_back(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given array `v` to the end of the array.
|
||||
//! \~russian Добавляет массив `v` в конец массива.
|
||||
@@ -1797,7 +1754,7 @@ public:
|
||||
//! piCout << v; // {1, 2, 3, 4, 5}
|
||||
//! \endcode
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & operator <<(const PIVector<T> & v) {return push_back(v);}
|
||||
inline PIVector<T> & operator<<(const PIVector<T> & v) { return push_back(v); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1815,9 +1772,7 @@ public:
|
||||
//! piCout << v; // {5, 4, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a push_back(), \a append(), \a prepend(), \a insert()
|
||||
inline PIVector<T> & push_front(const T & e) {
|
||||
return insert(0, e);
|
||||
}
|
||||
inline PIVector<T> & push_front(const T & e) { return insert(0, e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1825,9 +1780,7 @@ public:
|
||||
//! \~english Overloaded function.
|
||||
//! \~russian Перегруженая функция.
|
||||
//! \~\sa \a push_front()
|
||||
inline PIVector<T> & push_front(T && e) {
|
||||
return insert(0, std::move(e));
|
||||
}
|
||||
inline PIVector<T> & push_front(T && e) { return insert(0, std::move(e)); }
|
||||
|
||||
//! \~english Appends the given array `v` to the begin of the array.
|
||||
//! \~russian Добавляет массив `v` в начало массива.
|
||||
@@ -1840,9 +1793,7 @@ public:
|
||||
//! piCout << v; // {4, 5, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a push_front()
|
||||
inline PIVector<T> & push_front(const PIVector<T> & v) {
|
||||
return insert(0, v);
|
||||
}
|
||||
inline PIVector<T> & push_front(const PIVector<T> & v) { return insert(0, v); }
|
||||
|
||||
//! \~english Appends the given elements to the begin of the array.
|
||||
//! \~russian Добавляет элементы в начало массива.
|
||||
@@ -1854,9 +1805,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & push_front(std::initializer_list<T> init_list) {
|
||||
return insert(0, init_list);
|
||||
}
|
||||
inline PIVector<T> & push_front(std::initializer_list<T> init_list) { return insert(0, init_list); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1874,7 +1823,7 @@ public:
|
||||
//! piCout << v; // {5, 4, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a append(), \a push_back(), \a push_front(), \a insert()
|
||||
inline PIVector<T> & prepend(const T & e) {return push_front(e);}
|
||||
inline PIVector<T> & prepend(const T & e) { return push_front(e); }
|
||||
|
||||
//! \~english Appends the given element `e` to the begin of the array.
|
||||
//! \~russian Добавляет элемент `e` в начало массива.
|
||||
@@ -1882,7 +1831,7 @@ public:
|
||||
//! \~english Overloaded function.
|
||||
//! \~russian Перегруженая функция.
|
||||
//! \~\sa \a prepend()
|
||||
inline PIVector<T> & prepend(T && e) {return push_front(std::move(e));}
|
||||
inline PIVector<T> & prepend(T && e) { return push_front(std::move(e)); }
|
||||
|
||||
//! \~english Appends the given array `v` to the begin of the array.
|
||||
//! \~russian Добавляет массив `v` в начало массива.
|
||||
@@ -1895,7 +1844,7 @@ public:
|
||||
//! piCout << v; // {4, 5, 1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a prepend()
|
||||
inline PIVector<T> & prepend(const PIVector<T> & v) {return push_front(v);}
|
||||
inline PIVector<T> & prepend(const PIVector<T> & v) { return push_front(v); }
|
||||
|
||||
//! \~english Appends the given elements to the begin of the array.
|
||||
//! \~russian Добавляет элементы в начало массива.
|
||||
@@ -1907,7 +1856,7 @@ public:
|
||||
//! Добавляет элементы из
|
||||
//! [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list).
|
||||
//! \~\sa \a append()
|
||||
inline PIVector<T> & prepend(std::initializer_list<T> init_list) {return prepend(init_list);}
|
||||
inline PIVector<T> & prepend(std::initializer_list<T> init_list) { return prepend(init_list); }
|
||||
|
||||
//! \~english Remove one element from the end of the array.
|
||||
//! \~russian Удаляет один элемент с конца массива.
|
||||
@@ -1989,7 +1938,7 @@ public:
|
||||
//! piCout << v2; // {1, 2, 3}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> toType() const {
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(piv_size);
|
||||
@@ -2165,9 +2114,10 @@ public:
|
||||
//! piCout << sl; // {"1", "2", "3"}
|
||||
//! \endcode
|
||||
//! \~\sa \a forEach(), \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> map(std::function<ST(const T & e)> f) const {
|
||||
PIVector<ST> ret; ret.reserve(piv_size);
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(piv_size);
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
ret << f(piv_data[i]);
|
||||
}
|
||||
@@ -2182,9 +2132,10 @@ public:
|
||||
//! piCout << sl; // {"0", "1", "2"}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> mapIndexed(std::function<ST(size_t index, const T & e)> f) const {
|
||||
PIVector<ST> ret; ret.reserve(piv_size);
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(piv_size);
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
ret << f(i, piv_data[i]);
|
||||
}
|
||||
@@ -2199,9 +2150,10 @@ public:
|
||||
//! piCout << sl; // {"3", "2", "1"}
|
||||
//! \endcode
|
||||
//! \~\sa \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> mapReverse(std::function<ST(const T & e)> f) const {
|
||||
PIVector<ST> ret; ret.reserve(piv_size);
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(piv_size);
|
||||
for (ssize_t i = piv_size; i >= 0; --i) {
|
||||
ret << f(piv_data[i]);
|
||||
}
|
||||
@@ -2216,9 +2168,10 @@ public:
|
||||
//! piCout << sl; // {"2", "1", "0"}
|
||||
//! \endcode
|
||||
//! \~\sa \a mapReverse()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector<ST> mapReverseIndexed(std::function<ST(size_t index, const T & e)> f) const {
|
||||
PIVector<ST> ret; ret.reserve(piv_size);
|
||||
PIVector<ST> ret;
|
||||
ret.reserve(piv_size);
|
||||
for (ssize_t i = piv_size; i >= 0; --i) {
|
||||
ret << f(i, piv_data[i]);
|
||||
}
|
||||
@@ -2266,7 +2219,7 @@ public:
|
||||
//! piCout << s; // 15
|
||||
//! \endcode
|
||||
//! \~\sa \a forEach(), \a map()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduce(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
@@ -2278,7 +2231,7 @@ public:
|
||||
//! \~english Same as \a reduce() but with `index` parameter in `f`.
|
||||
//! \~russian Аналогично \a reduce() но с параметром индекса `index` в функции `f`.
|
||||
//! \~\sa \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceIndexed(std::function<ST(size_t index, const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (size_t i = 0; i < piv_size; ++i) {
|
||||
@@ -2290,7 +2243,7 @@ public:
|
||||
//! \~english Same as \a reduce() but from end to begin (from right to left).
|
||||
//! \~russian Аналогично \a reduce() но от конца до начала (справа на лево).
|
||||
//! \~\sa \a reduce()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceReverse(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (ssize_t i = piv_size; i >= 0; --i) {
|
||||
@@ -2302,7 +2255,7 @@ public:
|
||||
//! \~english Same as \a reduceReverse() but with `index` parameter in `f`.
|
||||
//! \~russian Аналогично \a reduceReverse() но с параметром индекса `index` в функции `f`.
|
||||
//! \~\sa \a reduceReverse()
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline ST reduceReverseIndexed(std::function<ST(size_t index, const T & e, const ST & acc)> f, const ST & initial = ST()) const {
|
||||
ST ret(initial);
|
||||
for (ssize_t i = piv_size; i >= 0; --i) {
|
||||
@@ -2332,24 +2285,24 @@ public:
|
||||
//! \~\sa \a map(), \a reduce(), \a flatten()
|
||||
inline PIVector<PIVector<T>> reshape(size_t rows, size_t cols, ReshapeOrder order = ReshapeByRow) const {
|
||||
#ifndef NDEBUG
|
||||
if (rows*cols != piv_size) {
|
||||
if (rows * cols != piv_size) {
|
||||
printf("error with PIVector<%s>::reshape\n", __PIP_TYPENAME__(T));
|
||||
}
|
||||
#endif
|
||||
assert(rows*cols == piv_size);
|
||||
assert(rows * cols == piv_size);
|
||||
PIVector<PIVector<T>> ret;
|
||||
if (isEmpty()) return ret;
|
||||
ret.expand(rows);
|
||||
if (order == ReshapeByRow) {
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
ret[r] = PIVector<T>(&(piv_data[r*cols]), cols);
|
||||
ret[r] = PIVector<T>(&(piv_data[r * cols]), cols);
|
||||
}
|
||||
}
|
||||
if (order == ReshapeByColumn) {
|
||||
for (size_t r = 0; r < rows; r++) {
|
||||
ret[r].resize(cols);
|
||||
for (size_t c = 0; c < cols; c++) {
|
||||
ret[r][c] = piv_data[c*rows + r];
|
||||
ret[r][c] = piv_data[c * rows + r];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2370,9 +2323,7 @@ public:
|
||||
//! piCout << xv.flatten<int>(); // {1, 2, 3, 4, 5, 6}
|
||||
//! \endcode
|
||||
//! \~\sa \a map(), \a reduce(), \a reshape()
|
||||
template<typename C, typename std::enable_if<
|
||||
std::is_same<T, PIVector<C>>::value
|
||||
, int>::type = 0>
|
||||
template<typename C, typename std::enable_if<std::is_same<T, PIVector<C>>::value, int>::type = 0>
|
||||
inline PIVector<C> flatten(ReshapeOrder order = ReshapeByRow) const {
|
||||
PIVector<C> ret;
|
||||
if (isEmpty()) return ret;
|
||||
@@ -2413,9 +2364,7 @@ public:
|
||||
//! piCout << xv.reshape<int>(2,3); // {{1, 2, 3}, {4, 5, 6}}
|
||||
//! \endcode
|
||||
//! \~\sa \a map(), \a reduce(), \a reshape()
|
||||
template<typename C, typename std::enable_if<
|
||||
std::is_same<T, PIVector<C>>::value
|
||||
, int>::type = 0>
|
||||
template<typename C, typename std::enable_if<std::is_same<T, PIVector<C>>::value, int>::type = 0>
|
||||
inline PIVector<PIVector<C>> reshape(size_t rows, size_t cols, ReshapeOrder order = ReshapeByRow) const {
|
||||
PIVector<C> fl = flatten<C>();
|
||||
return fl.reshape(rows, cols, order);
|
||||
@@ -2452,9 +2401,9 @@ public:
|
||||
if (isEmpty() || sz == 0) return ret;
|
||||
size_t ch = piv_size / sz;
|
||||
for (size_t i = 0; i < ch; ++i) {
|
||||
ret << PIVector<T>(piv_data + sz*i, sz);
|
||||
ret << PIVector<T>(piv_data + sz * i, sz);
|
||||
}
|
||||
size_t t = ch*sz;
|
||||
size_t t = ch * sz;
|
||||
if (t < piv_size) {
|
||||
ret << PIVector<T>(piv_data + t, piv_size - t);
|
||||
}
|
||||
@@ -2482,10 +2431,10 @@ public:
|
||||
if (index >= piv_size || count == 0) return ret;
|
||||
if (index + count > piv_size) count = piv_size - index;
|
||||
ret.alloc(count);
|
||||
memcpy((void*)ret.piv_data, (const void*)(piv_data + index), count * sizeof(T));
|
||||
memcpy((void *)ret.piv_data, (const void *)(piv_data + index), count * sizeof(T));
|
||||
size_t os = piv_size - index - count;
|
||||
if (os > 0) {
|
||||
memmove((void*)(piv_data + index), (const void*)(piv_data + index + count), os * sizeof(T));
|
||||
memmove((void *)(piv_data + index), (const void *)(piv_data + index + count), os * sizeof(T));
|
||||
piv_size -= count;
|
||||
} else {
|
||||
piv_size = index;
|
||||
@@ -2506,13 +2455,12 @@ private:
|
||||
return piv_rsize * 2;
|
||||
}
|
||||
ssize_t t = _PIContainerConstants<T>::minCountPoT(), s_ = s - 1;
|
||||
while (s_ >> t) ++t;
|
||||
while (s_ >> t)
|
||||
++t;
|
||||
return (1 << t);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void newT(T * dst, const T * src, size_t s) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, s)
|
||||
for (size_t i = 0; i < s; ++i) {
|
||||
@@ -2520,17 +2468,13 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void newT(T * dst, const T * src, size_t s) {
|
||||
PIINTROSPECTION_CONTAINER_USED(T, s)
|
||||
memcpy((void*)(dst), (const void*)(src), s * sizeof(T));
|
||||
memcpy((void *)(dst), (const void *)(src), s * sizeof(T));
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void deleteT(T * d, size_t sz) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, sz)
|
||||
if (d != nullptr) {
|
||||
@@ -2540,56 +2484,42 @@ private:
|
||||
}
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void deleteT(T * d, size_t sz) {
|
||||
PIINTROSPECTION_CONTAINER_UNUSED(T, sz)
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, const T & from) {
|
||||
new(to)T(from);
|
||||
new (to) T(from);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, T && from) {
|
||||
new(to)T(std::move(from));
|
||||
new (to) T(std::move(from));
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T1 * to, const T & from) {
|
||||
(*to) = from;
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementNew(T * to, T && from) {
|
||||
(*to) = std::move(from);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
!std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<!std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementDelete(T & from) {
|
||||
from.~T();
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline void elementDelete(T & from) {}
|
||||
|
||||
inline void dealloc() {
|
||||
if (piv_data != nullptr) {
|
||||
free((void*)piv_data);
|
||||
free((void *)piv_data);
|
||||
piv_data = nullptr;
|
||||
}
|
||||
}
|
||||
@@ -2597,7 +2527,7 @@ private:
|
||||
inline void expand(size_t new_size, const T & e = T()) {
|
||||
size_t os = piv_size;
|
||||
alloc(new_size);
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-os))
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - os))
|
||||
for (size_t i = os; i < new_size; ++i) {
|
||||
elementNew(piv_data + i, e);
|
||||
}
|
||||
@@ -2606,7 +2536,7 @@ private:
|
||||
inline void expand(size_t new_size, std::function<T(size_t i)> f) {
|
||||
size_t os = piv_size;
|
||||
alloc(new_size);
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size-os))
|
||||
PIINTROSPECTION_CONTAINER_USED(T, (new_size - os))
|
||||
for (size_t i = os; i < new_size; ++i) {
|
||||
elementNew(piv_data + i, f(i));
|
||||
}
|
||||
@@ -2620,8 +2550,8 @@ private:
|
||||
piv_size = new_size;
|
||||
size_t as = asize(new_size);
|
||||
if (as == piv_rsize) return;
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as-piv_rsize))
|
||||
T * p_d = (T*)(realloc((void*)(piv_data), as*sizeof(T)));
|
||||
PIINTROSPECTION_CONTAINER_ALLOC(T, (as - piv_rsize))
|
||||
T * p_d = (T *)(realloc((void *)(piv_data), as * sizeof(T)));
|
||||
#ifndef NDEBUG
|
||||
if (!p_d) {
|
||||
printf("error with PIVector<%s>::alloc\n", __PIP_TYPENAME__(T));
|
||||
@@ -2642,7 +2572,7 @@ private:
|
||||
//! \~english Output operator to [std::ostream](https://en.cppreference.com/w/cpp/io/basic_ostream).
|
||||
//! \~russian Оператор вывода в [std::ostream](https://ru.cppreference.com/w/cpp/io/basic_ostream).
|
||||
template<typename T>
|
||||
inline std::ostream & operator <<(std::ostream & s, const PIVector<T> & v) {
|
||||
inline std::ostream & operator<<(std::ostream & s, const PIVector<T> & v) {
|
||||
s << "{";
|
||||
for (size_t i = 0; i < v.size(); ++i) {
|
||||
s << v[i];
|
||||
@@ -2657,7 +2587,7 @@ inline std::ostream & operator <<(std::ostream & s, const PIVector<T> & v) {
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
template<typename T>
|
||||
inline PICout operator <<(PICout s, const PIVector<T> & v) {
|
||||
inline PICout operator<<(PICout s, const PIVector<T> & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "{";
|
||||
@@ -2673,6 +2603,8 @@ inline PICout operator <<(PICout s, const PIVector<T> & v) {
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
inline void piSwap(PIVector<T> & f, PIVector<T> & s) {f.swap(s);}
|
||||
inline void piSwap(PIVector<T> & f, PIVector<T> & s) {
|
||||
f.swap(s);
|
||||
}
|
||||
|
||||
#endif // PIVECTOR_H
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
* \brief 2D wrapper around PIVector
|
||||
*
|
||||
* This file declares PIVector
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
2D wrapper around PIVector
|
||||
@@ -35,154 +35,176 @@
|
||||
* PIVector2D has constructors from PIVector<T> and PIVector<PIVector<T> >
|
||||
*/
|
||||
|
||||
template <typename T>
|
||||
template<typename T>
|
||||
class PIVector2D {
|
||||
public:
|
||||
inline PIVector2D() {rows_ = cols_ = 0;}
|
||||
inline PIVector2D() { rows_ = cols_ = 0; }
|
||||
|
||||
inline PIVector2D(size_t rows, size_t cols, const T & f = T()) {
|
||||
rows_ = rows;
|
||||
cols_ = cols;
|
||||
mat.resize(rows*cols, f);
|
||||
mat.resize(rows * cols, f);
|
||||
}
|
||||
|
||||
inline PIVector2D(size_t rows, size_t cols, const PIVector<T> & v) : rows_(rows), cols_(cols), mat(v) {
|
||||
mat.resize(rows*cols);
|
||||
}
|
||||
inline PIVector2D(size_t rows, size_t cols, const PIVector<T> & v): rows_(rows), cols_(cols), mat(v) { mat.resize(rows * cols); }
|
||||
|
||||
inline PIVector2D(size_t rows, size_t cols, PIVector<T> && v) : rows_(rows), cols_(cols), mat(std::move(v)) {
|
||||
mat.resize(rows*cols);
|
||||
}
|
||||
inline PIVector2D(size_t rows, size_t cols, PIVector<T> && v): rows_(rows), cols_(cols), mat(std::move(v)) { mat.resize(rows * cols); }
|
||||
|
||||
inline PIVector2D(const PIVector<PIVector<T>> & v) {
|
||||
rows_ = v.size();
|
||||
if (rows_) {
|
||||
cols_ = v[0].size();
|
||||
mat.reserve(rows_*cols_);
|
||||
mat.reserve(rows_ * cols_);
|
||||
for (size_t i = 0; i < rows_; i++) {
|
||||
mat.append(v[i]);
|
||||
}
|
||||
mat.resize(rows_*cols_);
|
||||
mat.resize(rows_ * cols_);
|
||||
}
|
||||
if (mat.isEmpty()) rows_ = cols_ = 0;
|
||||
}
|
||||
|
||||
inline size_t rows() const {return rows_;}
|
||||
inline size_t rows() const { return rows_; }
|
||||
|
||||
inline size_t cols() const {return cols_;}
|
||||
inline size_t cols() const { return cols_; }
|
||||
|
||||
inline size_t size() const {return mat.size();}
|
||||
inline size_t size() const { return mat.size(); }
|
||||
|
||||
inline ssize_t size_s() const {return mat.size_s();}
|
||||
inline ssize_t size_s() const { return mat.size_s(); }
|
||||
|
||||
inline size_t length() const {return mat.length();}
|
||||
inline size_t length() const { return mat.length(); }
|
||||
|
||||
inline size_t capacity() const {return mat.capacity();}
|
||||
inline size_t capacity() const { return mat.capacity(); }
|
||||
|
||||
inline bool isEmpty() const {return mat.isEmpty();}
|
||||
inline bool isEmpty() const { return mat.isEmpty(); }
|
||||
|
||||
inline bool isNotEmpty() const {return mat.isNotEmpty();}
|
||||
inline bool isNotEmpty() const { return mat.isNotEmpty(); }
|
||||
|
||||
class Row {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline Row(PIVector2D<T> * p, size_t row) : p_(&(p->mat)) {st_ = p->cols_ * row; sz_ = p->cols_;}
|
||||
inline Row(PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
st_ = p->cols_ * row;
|
||||
sz_ = p->cols_;
|
||||
}
|
||||
PIVector<T> * p_;
|
||||
size_t st_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const {return sz_;}
|
||||
inline T & operator [](size_t index) {return (*p_)[st_ + index];}
|
||||
inline const T & operator [](size_t index) const {return (*p_)[st_ + index];}
|
||||
inline T * data(size_t index = 0) {return p_->data(st_ + index);}
|
||||
inline const T * data(size_t index = 0) const {return p_->data(st_ + index);}
|
||||
inline Row & operator =(const Row & other) {
|
||||
inline size_t size() const { return sz_; }
|
||||
inline T & operator[](size_t index) { return (*p_)[st_ + index]; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[st_ + index]; }
|
||||
inline T * data(size_t index = 0) { return p_->data(st_ + index); }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(st_ + index); }
|
||||
inline Row & operator=(const Row & other) {
|
||||
if (p_ == other.p_ && st_ == other.st_) return *this;
|
||||
size_t sz = piMin<size_t>(sz_, other.sz_);
|
||||
p_->_copyRaw(p_->data(st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
inline Row & operator =(const PIVector<T> & other) {
|
||||
inline Row & operator=(const PIVector<T> & other) {
|
||||
size_t sz = piMin<size_t>(sz, other.size());
|
||||
p_->_copyRaw(p_->data(st_), other.data(), sz);
|
||||
return *this;
|
||||
}
|
||||
inline PIVector<T> toVector() const {return PIVector<T>(p_->data(st_), sz_);}
|
||||
inline PIVector<T> toVector() const { return PIVector<T>(p_->data(st_), sz_); }
|
||||
};
|
||||
|
||||
class Col {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline Col(PIVector2D<T> * p, size_t row) : p_(&(p->mat)) {step_ = p->cols_; row_ = row; sz_ = p->rows_;}
|
||||
inline Col(PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
step_ = p->cols_;
|
||||
row_ = row;
|
||||
sz_ = p->rows_;
|
||||
}
|
||||
PIVector<T> * p_;
|
||||
size_t step_, row_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const {return sz_;}
|
||||
inline T & operator [](size_t index) {return (*p_)[index * step_ + row_];}
|
||||
inline const T & operator [](size_t index) const {return (*p_)[index * step_ + row_];}
|
||||
inline T * data(size_t index = 0) {return p_->data(index * step_ + row_);}
|
||||
inline const T * data(size_t index = 0) const {return p_->data(index * step_ + row_);}
|
||||
inline Col & operator =(const Col & other) {
|
||||
inline size_t size() const { return sz_; }
|
||||
inline T & operator[](size_t index) { return (*p_)[index * step_ + row_]; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[index * step_ + row_]; }
|
||||
inline T * data(size_t index = 0) { return p_->data(index * step_ + row_); }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(index * step_ + row_); }
|
||||
inline Col & operator=(const Col & other) {
|
||||
if (p_ == other.p_ && row_ == other.row_) return *this;
|
||||
size_t sz = piMin<size_t>(sz_, other.sz_);
|
||||
for (int i=0; i<sz; ++i) (*p_)[i * step_ + row_] = other[i];
|
||||
for (int i = 0; i < sz; ++i)
|
||||
(*p_)[i * step_ + row_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
inline Row & operator =(const PIVector<T> & other) {
|
||||
inline Row & operator=(const PIVector<T> & other) {
|
||||
size_t sz = piMin<size_t>(sz_, other.size());
|
||||
for (int i=0; i<sz; ++i) (*p_)[i * step_ + row_] = other[i];
|
||||
for (int i = 0; i < sz; ++i)
|
||||
(*p_)[i * step_ + row_] = other[i];
|
||||
return *this;
|
||||
}
|
||||
inline PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
ret.reserve(sz_);
|
||||
for (size_t i=0; i<sz_; i++) ret << (*p_)[i * step_ + row_];
|
||||
for (size_t i = 0; i < sz_; i++)
|
||||
ret << (*p_)[i * step_ + row_];
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
class RowConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline RowConst(const PIVector2D<T> * p, size_t row) : p_(&(p->mat)) {st_ = p->cols_ * row; sz_ = p->cols_;}
|
||||
inline RowConst(const PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
st_ = p->cols_ * row;
|
||||
sz_ = p->cols_;
|
||||
}
|
||||
const PIVector<T> * p_;
|
||||
size_t st_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const {return sz_;}
|
||||
inline const T & operator [](size_t index) const {return (*p_)[st_ + index];}
|
||||
inline const T * data(size_t index = 0) const {return p_->data(st_ + index);}
|
||||
inline PIVector<T> toVector() const {return PIVector<T>(p_->data(st_), sz_);}
|
||||
inline size_t size() const { return sz_; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[st_ + index]; }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(st_ + index); }
|
||||
inline PIVector<T> toVector() const { return PIVector<T>(p_->data(st_), sz_); }
|
||||
};
|
||||
|
||||
class ColConst {
|
||||
friend class PIVector2D<T>;
|
||||
|
||||
private:
|
||||
inline ColConst(const PIVector2D<T> * p, size_t row) : p_(&(p->mat)) {step_ = p->cols_; row_ = row; sz_ = p->rows_;}
|
||||
inline ColConst(const PIVector2D<T> * p, size_t row): p_(&(p->mat)) {
|
||||
step_ = p->cols_;
|
||||
row_ = row;
|
||||
sz_ = p->rows_;
|
||||
}
|
||||
const PIVector<T> * p_;
|
||||
size_t step_, row_, sz_;
|
||||
|
||||
public:
|
||||
inline size_t size() const {return p_->rows_;}
|
||||
inline const T & operator [](size_t index) const {return (*p_)[index * step_ + row_];}
|
||||
inline const T * data(size_t index = 0) const {return p_->data(index * step_ + row_);}
|
||||
inline size_t size() const { return p_->rows_; }
|
||||
inline const T & operator[](size_t index) const { return (*p_)[index * step_ + row_]; }
|
||||
inline const T * data(size_t index = 0) const { return p_->data(index * step_ + row_); }
|
||||
inline PIVector<T> toVector() const {
|
||||
PIVector<T> ret;
|
||||
ret.reserve(sz_);
|
||||
for (int i=0; i<size(); i++) ret << (*p_)[i * step_ + row_];
|
||||
for (int i = 0; i < size(); i++)
|
||||
ret << (*p_)[i * step_ + row_];
|
||||
return ret;
|
||||
}
|
||||
};
|
||||
|
||||
inline T & element(size_t row, size_t col) {return mat[row * cols_ + col];}
|
||||
inline const T & element(size_t row, size_t col) const {return mat[row * cols_ + col];}
|
||||
inline const T & at(size_t row, size_t col) const {return mat[row * cols_ + col];}
|
||||
inline Row operator[](size_t index) {return Row(this, index);}
|
||||
inline RowConst operator[](size_t index) const {return RowConst(this, index);}
|
||||
inline T * data(size_t index = 0) {return mat.data(index);}
|
||||
inline const T * data(size_t index = 0) const {return mat.data(index);}
|
||||
inline T & element(size_t row, size_t col) { return mat[row * cols_ + col]; }
|
||||
inline const T & element(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
inline const T & at(size_t row, size_t col) const { return mat[row * cols_ + col]; }
|
||||
inline Row operator[](size_t index) { return Row(this, index); }
|
||||
inline RowConst operator[](size_t index) const { return RowConst(this, index); }
|
||||
inline T * data(size_t index = 0) { return mat.data(index); }
|
||||
inline const T * data(size_t index = 0) const { return mat.data(index); }
|
||||
|
||||
inline Row row(size_t index) {return Row(this, index);}
|
||||
inline RowConst row(size_t index) const {return RowConst(this, index);}
|
||||
inline Col col(size_t index) {return Col(this, index);}
|
||||
inline ColConst col(size_t index) const {return ColConst(this, index);}
|
||||
inline Row row(size_t index) { return Row(this, index); }
|
||||
inline RowConst row(size_t index) const { return RowConst(this, index); }
|
||||
inline Col col(size_t index) { return Col(this, index); }
|
||||
inline ColConst col(size_t index) const { return ColConst(this, index); }
|
||||
inline PIVector2D<T> & setRow(size_t row, const Row & other) {
|
||||
size_t sz = piMin<size_t>(cols_, other.sz_);
|
||||
mat._copyRaw(mat.data(cols_ * row), other.data(), sz);
|
||||
@@ -227,20 +249,20 @@ public:
|
||||
}
|
||||
|
||||
inline PIVector2D<T> & resize(size_t rows, size_t cols, const T & f = T()) {
|
||||
mat.resize(rows*cols_, f);
|
||||
mat.resize(rows * cols_, f);
|
||||
rows_ = rows;
|
||||
int cs = (cols - cols_);
|
||||
if (cs < 0) {
|
||||
for (size_t r=0; r<rows; ++r) {
|
||||
mat.remove(r*cols + cols, -cs);
|
||||
for (size_t r = 0; r < rows; ++r) {
|
||||
mat.remove(r * cols + cols, -cs);
|
||||
}
|
||||
}
|
||||
mat.resize(rows*cols, f);
|
||||
mat.resize(rows * cols, f);
|
||||
if (!mat.isEmpty()) {
|
||||
if (cs > 0) {
|
||||
for (size_t r=0; r<rows_; ++r) {
|
||||
for (int i=0; i<cs; ++i)
|
||||
mat.insert(r*cols + cols_, mat.take_back());
|
||||
for (size_t r = 0; r < rows_; ++r) {
|
||||
for (int i = 0; i < cs; ++i)
|
||||
mat.insert(r * cols + cols_, mat.take_back());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -248,26 +270,25 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
inline bool operator ==(const PIVector2D<T> & t) const {
|
||||
if (cols_ != t.cols_ || rows_ != t.rows_)
|
||||
return false;
|
||||
inline bool operator==(const PIVector2D<T> & t) const {
|
||||
if (cols_ != t.cols_ || rows_ != t.rows_) return false;
|
||||
return mat == t.mat;
|
||||
}
|
||||
inline bool operator !=(const PIVector2D<T> & t) const {return !(*this == t);}
|
||||
inline bool operator!=(const PIVector2D<T> & t) const { return !(*this == t); }
|
||||
|
||||
inline PIVector<PIVector<T> > toVectors() const {
|
||||
PIVector<PIVector<T> > ret;
|
||||
inline PIVector<PIVector<T>> toVectors() const {
|
||||
PIVector<PIVector<T>> ret;
|
||||
ret.reserve(rows_);
|
||||
for(size_t i = 0; i < rows_; ++i)
|
||||
ret << PIVector<T>(mat.data(i*cols_), cols_);
|
||||
for (size_t i = 0; i < rows_; ++i)
|
||||
ret << PIVector<T>(mat.data(i * cols_), cols_);
|
||||
return ret;
|
||||
}
|
||||
|
||||
inline PIVector<T> toPlainVector() const {return mat;}
|
||||
inline PIVector<T> toPlainVector() const { return mat; }
|
||||
|
||||
inline PIVector<T> & plainVector() {return mat;}
|
||||
inline PIVector<T> & plainVector() { return mat; }
|
||||
|
||||
inline const PIVector<T> & plainVector() const {return mat;}
|
||||
inline const PIVector<T> & plainVector() const { return mat; }
|
||||
|
||||
inline void swap(PIVector2D<T> & other) {
|
||||
mat.swap(other.mat);
|
||||
@@ -275,13 +296,11 @@ public:
|
||||
piSwap<size_t>(cols_, other.cols_);
|
||||
}
|
||||
|
||||
template<typename T1 = T, typename std::enable_if<
|
||||
std::is_trivially_copyable<T1>::value
|
||||
, int>::type = 0>
|
||||
template<typename T1 = T, typename std::enable_if<std::is_trivially_copyable<T1>::value, int>::type = 0>
|
||||
inline PIVector2D<T> & _resizeRaw(size_t r, size_t c) {
|
||||
rows_ = r;
|
||||
cols_ = c;
|
||||
mat._resizeRaw(r*c);
|
||||
mat._resizeRaw(r * c);
|
||||
return *this;
|
||||
}
|
||||
|
||||
@@ -290,14 +309,12 @@ public:
|
||||
mat.clear();
|
||||
}
|
||||
|
||||
template <typename ST>
|
||||
template<typename ST>
|
||||
inline PIVector2D<ST> map(std::function<ST(const T & e)> f) const {
|
||||
return PIVector2D<ST>(rows_, cols_, mat.map(f));
|
||||
}
|
||||
|
||||
inline void forEach(std::function<void(const T &)> f) const {
|
||||
mat.forEach(f);
|
||||
}
|
||||
inline void forEach(std::function<void(const T &)> f) const { mat.forEach(f); }
|
||||
|
||||
inline PIVector2D<T> & forEach(std::function<void(T &)> f) {
|
||||
mat.forEach(f);
|
||||
@@ -311,7 +328,7 @@ protected:
|
||||
|
||||
|
||||
template<typename T>
|
||||
inline PICout operator <<(PICout s, const PIVector2D<T> & v) {
|
||||
inline PICout operator<<(PICout s, const PIVector2D<T> & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "{";
|
||||
for (size_t i = 0; i < v.rows(); ++i) {
|
||||
@@ -321,7 +338,7 @@ inline PICout operator <<(PICout s, const PIVector2D<T> & v) {
|
||||
if (j < v.cols() - 1) s << ", ";
|
||||
}
|
||||
s << " }";
|
||||
if (i < v.rows() - 1) s << PICoutManipulators::NewLine ;
|
||||
if (i < v.rows() - 1) s << PICoutManipulators::NewLine;
|
||||
}
|
||||
if (v.isEmpty()) s << "{ }";
|
||||
s << "}";
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
* \~russian
|
||||
* Этот файл реализует первый слой после системы и объявляет
|
||||
* несколько базовых полезных методов
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base types and functions
|
||||
@@ -34,10 +34,11 @@
|
||||
#ifndef PIBASE_H
|
||||
#define PIBASE_H
|
||||
|
||||
#include "pip_defs.h"
|
||||
#include "pip_export.h"
|
||||
#include "pip_version.h"
|
||||
#include "piplatform.h"
|
||||
#include "pip_export.h"
|
||||
#include "pip_defs.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
//! \~english
|
||||
@@ -204,18 +205,18 @@
|
||||
//! \~russian Макрос для подавления предупреждения компилятора о неиспользуемой переменной
|
||||
# define NO_UNUSED(x)
|
||||
|
||||
#undef MICRO_PIP
|
||||
#undef FREERTOS
|
||||
#endif //DOXYGEN
|
||||
# undef MICRO_PIP
|
||||
# undef FREERTOS
|
||||
#endif // DOXYGEN
|
||||
|
||||
#ifdef CC_AVR_GCC
|
||||
# include <ArduinoSTL.h>
|
||||
#endif
|
||||
#include <functional>
|
||||
#include <cstddef>
|
||||
#include <cassert>
|
||||
#include <limits>
|
||||
#include <atomic>
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <limits>
|
||||
|
||||
#ifdef WINDOWS
|
||||
# ifdef CC_VC
|
||||
@@ -231,49 +232,49 @@
|
||||
# else
|
||||
# define SHUT_RDWR SD_BOTH
|
||||
# endif
|
||||
typedef int socklen_t;
|
||||
extern long long __pi_perf_freq;
|
||||
typedef int socklen_t;
|
||||
extern long long __pi_perf_freq;
|
||||
#endif
|
||||
|
||||
#ifndef DOXYGEN
|
||||
|
||||
#ifdef ANDROID
|
||||
///# define tcdrain(fd) ioctl(fd, TCSBRK, 1)
|
||||
//inline int wctomb(char * c, wchar_t w) {*c = ((char * )&w)[0]; return 1;}
|
||||
//inline int mbtowc(wchar_t * w, const char * c, size_t) {*w = ((wchar_t * )&c)[0]; return 1;}
|
||||
#endif
|
||||
# ifdef ANDROID
|
||||
/// # define tcdrain(fd) ioctl(fd, TCSBRK, 1)
|
||||
// inline int wctomb(char * c, wchar_t w) {*c = ((char * )&w)[0]; return 1;}
|
||||
// inline int mbtowc(wchar_t * w, const char * c, size_t) {*w = ((wchar_t * )&c)[0]; return 1;}
|
||||
# endif
|
||||
|
||||
#ifdef MAC_OS
|
||||
# ifdef MAC_OS
|
||||
# define environ (*_NSGetEnviron())
|
||||
typedef long time_t;
|
||||
#endif
|
||||
typedef long time_t;
|
||||
# endif
|
||||
|
||||
#ifdef LINUX
|
||||
# ifdef LINUX
|
||||
# define environ __environ
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#ifdef FREE_BSD
|
||||
extern char ** environ;
|
||||
#endif
|
||||
# ifdef FREE_BSD
|
||||
extern char ** environ;
|
||||
# endif
|
||||
|
||||
#ifndef NO_UNUSED
|
||||
# ifndef NO_UNUSED
|
||||
# define NO_UNUSED(x) (void)x
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#ifndef assert
|
||||
# ifndef assert
|
||||
# define assert(x)
|
||||
# define assertm(exp, msg)
|
||||
#else
|
||||
# else
|
||||
# define assertm(exp, msg) assert(((void)msg, exp))
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#ifdef MICRO_PIP
|
||||
# ifdef MICRO_PIP
|
||||
# define __PIP_TYPENAME__(T) "?"
|
||||
#else
|
||||
# else
|
||||
# define __PIP_TYPENAME__(T) typeid(T).name()
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#ifdef CC_GCC
|
||||
# ifdef CC_GCC
|
||||
# undef DEPRECATED
|
||||
# undef DEPRECATEDM
|
||||
# define DEPRECATED __attribute__((deprecated))
|
||||
@@ -293,11 +294,11 @@
|
||||
# pragma GCC diagnostic ignored "-Wextra"
|
||||
# pragma GCC diagnostic ignored "-Wc++11-extensions"
|
||||
# pragma GCC diagnostic ignored "-Wundefined-bool-conversion"
|
||||
//# pragma GCC diagnostic ignored "-Wliteral-suffix"
|
||||
// # pragma GCC diagnostic ignored "-Wliteral-suffix"
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef CC_VC
|
||||
# ifdef CC_VC
|
||||
# undef DEPRECATED
|
||||
# undef DEPRECATEDM
|
||||
# define DEPRECATED __declspec(deprecated)
|
||||
@@ -318,53 +319,63 @@
|
||||
# pragma warning(disable: 4986)
|
||||
# pragma warning(disable: 4996)
|
||||
# ifdef ARCH_BITS_32
|
||||
typedef long ssize_t;
|
||||
typedef long ssize_t;
|
||||
# else
|
||||
typedef long long ssize_t;
|
||||
typedef long long ssize_t;
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef CC_OTHER
|
||||
# ifdef CC_OTHER
|
||||
# undef DEPRECATED
|
||||
# undef DEPRECATEDM
|
||||
# define DEPRECATED
|
||||
# define DEPRECATEDM(msg)
|
||||
#endif
|
||||
# endif
|
||||
|
||||
#endif //DOXYGEN
|
||||
#endif // DOXYGEN
|
||||
// Private data macros
|
||||
#ifndef DOXYGEN
|
||||
|
||||
#define PRIVATE_DECLARATION(e) \
|
||||
# define PRIVATE_DECLARATION(e) \
|
||||
struct __Private__; \
|
||||
friend struct __Private__; \
|
||||
struct e __PrivateInitializer__ { \
|
||||
__PrivateInitializer__(); \
|
||||
__PrivateInitializer__(const __PrivateInitializer__ & o); \
|
||||
~__PrivateInitializer__(); \
|
||||
__PrivateInitializer__ & operator =(const __PrivateInitializer__ & o); \
|
||||
__PrivateInitializer__ & operator=(const __PrivateInitializer__ & o); \
|
||||
__Private__ * p; \
|
||||
}; \
|
||||
__PrivateInitializer__ __privateinitializer__;
|
||||
|
||||
#define PRIVATE_DEFINITION_START(c) \
|
||||
struct c::__Private__ {
|
||||
# define PRIVATE_DEFINITION_START(c) struct c::__Private__ {
|
||||
# define PRIVATE_DEFINITION_END(c) \
|
||||
} \
|
||||
; \
|
||||
c::__PrivateInitializer__::__PrivateInitializer__() { \
|
||||
p = new c::__Private__(); \
|
||||
} \
|
||||
c::__PrivateInitializer__::__PrivateInitializer__(const c::__PrivateInitializer__ &) { /*if (p) delete p;*/ \
|
||||
p = new c::__Private__(); \
|
||||
} \
|
||||
c::__PrivateInitializer__::~__PrivateInitializer__() { \
|
||||
delete p; \
|
||||
p = 0; \
|
||||
} \
|
||||
c::__PrivateInitializer__ & c::__PrivateInitializer__::operator=(const c::__PrivateInitializer__ &) { \
|
||||
if (p) delete p; \
|
||||
p = new c::__Private__(); \
|
||||
return *this; \
|
||||
}
|
||||
|
||||
#define PRIVATE_DEFINITION_END(c) \
|
||||
}; \
|
||||
c::__PrivateInitializer__::__PrivateInitializer__() {p = new c::__Private__();} \
|
||||
c::__PrivateInitializer__::__PrivateInitializer__(const c::__PrivateInitializer__ & ) {/*if (p) delete p;*/ p = new c::__Private__();} \
|
||||
c::__PrivateInitializer__::~__PrivateInitializer__() {delete p; p = 0;} \
|
||||
c::__PrivateInitializer__ & c::__PrivateInitializer__::operator =(const c::__PrivateInitializer__ & ) {if (p) delete p; p = new c::__Private__(); return *this;}
|
||||
# define PRIVATE (__privateinitializer__.p)
|
||||
# define PRIVATEWB __privateinitializer__.p
|
||||
|
||||
#define PRIVATE (__privateinitializer__.p)
|
||||
#define PRIVATEWB __privateinitializer__.p
|
||||
|
||||
#endif //DOXYGEN
|
||||
#endif // DOXYGEN
|
||||
|
||||
#define NO_COPY_CLASS(name) \
|
||||
name(const name&) = delete; \
|
||||
name& operator=(const name&) = delete;
|
||||
name(const name &) = delete; \
|
||||
name & operator=(const name &) = delete;
|
||||
|
||||
|
||||
#define _PIP_ADD_COUNTER_WS(a, cnt, line) a##cnt##_##line
|
||||
@@ -377,11 +388,12 @@
|
||||
class _Initializer_ { \
|
||||
public: \
|
||||
_Initializer_() {
|
||||
|
||||
#define STATIC_INITIALIZER_END \
|
||||
} \
|
||||
} _initializer_; \
|
||||
} _PIP_ADD_COUNTER(_pip_initializer_);
|
||||
} \
|
||||
_initializer_; \
|
||||
} \
|
||||
_PIP_ADD_COUNTER(_pip_initializer_);
|
||||
|
||||
|
||||
//! \~\brief
|
||||
@@ -441,7 +453,12 @@ typedef long double ldouble;
|
||||
//! \~\details
|
||||
//! \~english Example:\n \snippet piincludes.cpp swap
|
||||
//! \~russian Пример:\n \snippet piincludes.cpp swap
|
||||
template<typename T> inline void piSwap(T & f, T & s) {T t(std::move(f)); f = std::move(s); s = std::move(t);}
|
||||
template<typename T>
|
||||
inline void piSwap(T & f, T & s) {
|
||||
T t(std::move(f));
|
||||
f = std::move(s);
|
||||
s = std::move(t);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function for swap two values without "="
|
||||
@@ -449,36 +466,38 @@ template<typename T> inline void piSwap(T & f, T & s) {T t(std::move(f)); f = st
|
||||
//! \~\details
|
||||
//! \~english Example:\n \snippet piincludes.cpp swapBinary
|
||||
//! \~russian Пример:\n \snippet piincludes.cpp swapBinary
|
||||
template<typename T> inline void piSwapBinary(T & f, T & s) {
|
||||
if ((size_t*)&f == (size_t*)&s) return;
|
||||
template<typename T>
|
||||
inline void piSwapBinary(T & f, T & s) {
|
||||
if ((size_t *)&f == (size_t *)&s) return;
|
||||
size_t j = (sizeof(T) / sizeof(size_t)), bs = j * sizeof(size_t), bf = sizeof(T);
|
||||
size_t i = 0;
|
||||
for (i = 0; i < j; ++i) {
|
||||
((size_t*)(&f))[i] ^= ((size_t*)(&s))[i];
|
||||
((size_t*)(&s))[i] ^= ((size_t*)(&f))[i];
|
||||
((size_t*)(&f))[i] ^= ((size_t*)(&s))[i];
|
||||
((size_t *)(&f))[i] ^= ((size_t *)(&s))[i];
|
||||
((size_t *)(&s))[i] ^= ((size_t *)(&f))[i];
|
||||
((size_t *)(&f))[i] ^= ((size_t *)(&s))[i];
|
||||
}
|
||||
for (i = bs; i < bf; ++i) {
|
||||
((uchar*)(&f))[i] ^= ((uchar*)(&s))[i];
|
||||
((uchar*)(&s))[i] ^= ((uchar*)(&f))[i];
|
||||
((uchar*)(&f))[i] ^= ((uchar*)(&s))[i];
|
||||
((uchar *)(&f))[i] ^= ((uchar *)(&s))[i];
|
||||
((uchar *)(&s))[i] ^= ((uchar *)(&f))[i];
|
||||
((uchar *)(&f))[i] ^= ((uchar *)(&s))[i];
|
||||
}
|
||||
}
|
||||
|
||||
template<> inline void piSwapBinary(const void *& f, const void *& s) {
|
||||
if ((size_t*)f == (size_t*)s) return;
|
||||
template<>
|
||||
inline void piSwapBinary(const void *& f, const void *& s) {
|
||||
if ((size_t *)f == (size_t *)s) return;
|
||||
size_t j = (sizeof(void *) / sizeof(size_t)), bs = j * sizeof(size_t), bf = sizeof(void *);
|
||||
size_t i = 0;
|
||||
void * pf = const_cast<void*>(f), * ps = const_cast<void*>(s);
|
||||
void *pf = const_cast<void *>(f), *ps = const_cast<void *>(s);
|
||||
for (i = 0; i < j; ++i) {
|
||||
((size_t*)(&pf))[i] ^= ((size_t*)(&ps))[i];
|
||||
((size_t*)(&ps))[i] ^= ((size_t*)(&pf))[i];
|
||||
((size_t*)(&pf))[i] ^= ((size_t*)(&ps))[i];
|
||||
((size_t *)(&pf))[i] ^= ((size_t *)(&ps))[i];
|
||||
((size_t *)(&ps))[i] ^= ((size_t *)(&pf))[i];
|
||||
((size_t *)(&pf))[i] ^= ((size_t *)(&ps))[i];
|
||||
}
|
||||
for (i = bs; i < bf; ++i) {
|
||||
((uchar*)(&pf))[i] ^= ((uchar*)(&ps))[i];
|
||||
((uchar*)(&ps))[i] ^= ((uchar*)(&pf))[i];
|
||||
((uchar*)(&pf))[i] ^= ((uchar*)(&ps))[i];
|
||||
((uchar *)(&pf))[i] ^= ((uchar *)(&ps))[i];
|
||||
((uchar *)(&ps))[i] ^= ((uchar *)(&pf))[i];
|
||||
((uchar *)(&pf))[i] ^= ((uchar *)(&ps))[i];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -491,8 +510,7 @@ template<> inline void piSwapBinary(const void *& f, const void *& s) {
|
||||
//! \~russian Пример:\n \snippet piincludes.cpp compareBinary
|
||||
inline bool piCompareBinary(const void * f, const void * s, size_t size) {
|
||||
for (size_t i = 0; i < size; ++i)
|
||||
if (((const uchar*)f)[i] != ((const uchar*)s)[i])
|
||||
return false;
|
||||
if (((const uchar *)f)[i] != ((const uchar *)s)[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -516,7 +534,10 @@ inline bool piCompareBinary(const void * f, const void * s, size_t size) {
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp round
|
||||
template<typename T> inline constexpr int piRound(const T & v) {return int(v >= T(0.) ? v + T(0.5) : v - T(0.5));}
|
||||
template<typename T>
|
||||
inline constexpr int piRound(const T & v) {
|
||||
return int(v >= T(0.) ? v + T(0.5) : v - T(0.5));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return floor of float falue
|
||||
@@ -538,7 +559,10 @@ template<typename T> inline constexpr int piRound(const T & v) {return int(v >=
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp floor
|
||||
template<typename T> inline constexpr int piFloor(const T & v) {return v < T(0) ? int(v) - 1 : int(v);}
|
||||
template<typename T>
|
||||
inline constexpr int piFloor(const T & v) {
|
||||
return v < T(0) ? int(v) - 1 : int(v);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return ceil of float falue
|
||||
@@ -560,7 +584,10 @@ template<typename T> inline constexpr int piFloor(const T & v) {return v < T(0)
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp ceil
|
||||
template<typename T> inline constexpr int piCeil(const T & v) {return v < T(0) ? int(v) : int(v) + 1;}
|
||||
template<typename T>
|
||||
inline constexpr int piCeil(const T & v) {
|
||||
return v < T(0) ? int(v) : int(v) + 1;
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return absolute of numeric falue
|
||||
@@ -590,7 +617,10 @@ template<typename T> inline constexpr int piCeil(const T & v) {return v < T(0) ?
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp abs
|
||||
template<typename T> inline constexpr T piAbs(const T & v) {return (v >= T(0) ? v : -v);}
|
||||
template<typename T>
|
||||
inline constexpr T piAbs(const T & v) {
|
||||
return (v >= T(0) ? v : -v);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return minimum of two values
|
||||
@@ -618,7 +648,10 @@ template<typename T> inline constexpr T piAbs(const T & v) {return (v >= T(0) ?
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp min2
|
||||
template<typename T> inline constexpr T piMin(const T & f, const T & s) {return ((f > s) ? s : f);}
|
||||
template<typename T>
|
||||
inline constexpr T piMin(const T & f, const T & s) {
|
||||
return ((f > s) ? s : f);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return minimum of tree values
|
||||
@@ -646,7 +679,10 @@ template<typename T> inline constexpr T piMin(const T & f, const T & s) {return
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp min3
|
||||
template<typename T> inline constexpr T piMin(const T & f, const T & s, const T & t) {return ((f < s && f < t) ? f : ((s < t) ? s : t));}
|
||||
template<typename T>
|
||||
inline constexpr T piMin(const T & f, const T & s, const T & t) {
|
||||
return ((f < s && f < t) ? f : ((s < t) ? s : t));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return maximum of two values
|
||||
@@ -674,7 +710,10 @@ template<typename T> inline constexpr T piMin(const T & f, const T & s, const T
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp max2
|
||||
template<typename T> inline constexpr T piMax(const T & f, const T & s) {return ((f < s) ? s : f);}
|
||||
template<typename T>
|
||||
inline constexpr T piMax(const T & f, const T & s) {
|
||||
return ((f < s) ? s : f);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return maximum of tree values
|
||||
@@ -702,7 +741,10 @@ template<typename T> inline constexpr T piMax(const T & f, const T & s) {return
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp max3
|
||||
template<typename T> inline constexpr T piMax(const T & f, const T & s, const T & t) {return ((f > s && f > t) ? f : ((s > t) ? s : t));}
|
||||
template<typename T>
|
||||
inline constexpr T piMax(const T & f, const T & s, const T & t) {
|
||||
return ((f > s && f > t) ? f : ((s > t) ? s : t));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function return clamped value
|
||||
@@ -732,14 +774,17 @@ template<typename T> inline constexpr T piMax(const T & f, const T & s, const T
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp clamp
|
||||
template<typename T> inline constexpr T piClamp(const T & v, const T & min, const T & max) {return (v > max ? max : (v < min ? min : v));}
|
||||
template<typename T>
|
||||
inline constexpr T piClamp(const T & v, const T & min, const T & max) {
|
||||
return (v > max ? max : (v < min ? min : v));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Function inverse byte order in memory block ([1..N] -> [N..1])
|
||||
//! \~russian Метод для смены порядка байт в блоке памяти ([1..N] -> [N..1])
|
||||
inline void piLetobe(void * data, int size) {
|
||||
for (int i = 0; i < size / 2; i++)
|
||||
piSwap<uchar>(((uchar*)data)[size - i - 1], ((uchar*)data)[i]);
|
||||
piSwap<uchar>(((uchar *)data)[size - i - 1], ((uchar *)data)[i]);
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
@@ -768,7 +813,10 @@ inline bool piCompare(const T & a, const T & b, const T & epsilon = std::numeric
|
||||
//! \~\brief
|
||||
//! \~english Templated function that inverse byte order of value "v"
|
||||
//! \~russian Шаблонный метод, меняющий порядок байт в переменной "v"
|
||||
template<typename T> inline void piLetobe(T * v) {piLetobe(v, sizeof(T));}
|
||||
template<typename T>
|
||||
inline void piLetobe(T * v) {
|
||||
piLetobe(v, sizeof(T));
|
||||
}
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Templated function that returns "v" with inversed byte order
|
||||
@@ -794,14 +842,26 @@ template<typename T> inline void piLetobe(T * v) {piLetobe(v, sizeof(T));}
|
||||
//!
|
||||
//! Пример:
|
||||
//! \snippet piincludes.cpp letobe
|
||||
template<typename T> inline T piLetobe(const T & v) {T tv(v); piLetobe(&tv, sizeof(T)); return tv;}
|
||||
template<typename T>
|
||||
inline T piLetobe(const T & v) {
|
||||
T tv(v);
|
||||
piLetobe(&tv, sizeof(T));
|
||||
return tv;
|
||||
}
|
||||
|
||||
// specialization
|
||||
template<> inline uint16_t piLetobe(const uint16_t & v) {return (v << 8) | (v >> 8);}
|
||||
template<> inline uint32_t piLetobe(const uint32_t & v) {return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | ((v << 24) & 0xFF000000);}
|
||||
template<> inline float piLetobe(const float & v) {
|
||||
template<>
|
||||
inline uint16_t piLetobe(const uint16_t & v) {
|
||||
return (v << 8) | (v >> 8);
|
||||
}
|
||||
template<>
|
||||
inline uint32_t piLetobe(const uint32_t & v) {
|
||||
return (v >> 24) | ((v >> 8) & 0xFF00) | ((v << 8) & 0xFF0000) | ((v << 24) & 0xFF000000);
|
||||
}
|
||||
template<>
|
||||
inline float piLetobe(const float & v) {
|
||||
union _pletobe_f {
|
||||
_pletobe_f(const float &f_) {f = f_;}
|
||||
_pletobe_f(const float & f_) { f = f_; }
|
||||
float f;
|
||||
uint32_t v;
|
||||
};
|
||||
@@ -852,27 +912,63 @@ inline uint piHashData(const uchar * data, uint len, uint seed = 0) {
|
||||
}
|
||||
|
||||
|
||||
template<typename T> inline uint piHash(const T & v) {
|
||||
template<typename T>
|
||||
inline uint piHash(const T & v) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
template<> inline uint piHash(const char & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const uchar & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const short & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const ushort & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const int & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const uint & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const llong & v) {return piHashData((const uchar *)&v, sizeof(v));}
|
||||
template<> inline uint piHash(const ullong & v) {return piHashData((const uchar *)&v, sizeof(v));}
|
||||
template<> inline uint piHash(const float & v) {return (uint)v;}
|
||||
template<> inline uint piHash(const double & v) {return piHashData((const uchar *)&v, sizeof(v));}
|
||||
template<> inline uint piHash(const ldouble & v) {return piHashData((const uchar *)&v, sizeof(v));}
|
||||
template<>
|
||||
inline uint piHash(const char & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const uchar & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const short & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const ushort & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const int & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const uint & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const llong & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const ullong & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const float & v) {
|
||||
return (uint)v;
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const double & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
template<>
|
||||
inline uint piHash(const ldouble & v) {
|
||||
return piHashData((const uchar *)&v, sizeof(v));
|
||||
}
|
||||
|
||||
template<typename T> inline void piDeleteAll(T & container) {
|
||||
template<typename T>
|
||||
inline void piDeleteAll(T & container) {
|
||||
for (auto i: container)
|
||||
delete i;
|
||||
}
|
||||
template<typename T> inline void piDeleteAllAndClear(T & container) {
|
||||
template<typename T>
|
||||
inline void piDeleteAllAndClear(T & container) {
|
||||
piDeleteAll(container);
|
||||
container.clear();
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
#include "picli.h"
|
||||
|
||||
#include "pisysteminfo.h"
|
||||
|
||||
|
||||
@@ -75,8 +76,7 @@ PICLI::PICLI(int argc, char * argv[]) {
|
||||
_count_mand = 0;
|
||||
for (int i = 0; i < argc; ++i)
|
||||
_args_raw << argv[i];
|
||||
if (argc > 0)
|
||||
PISystemInfo::instance()->execCommand = argv[0];
|
||||
if (argc > 0) PISystemInfo::instance()->execCommand = argv[0];
|
||||
}
|
||||
|
||||
|
||||
@@ -89,7 +89,7 @@ void PICLI::parse() {
|
||||
if (cra.left(2) == _prefix_full) {
|
||||
last = 0;
|
||||
full = cra.right(cra.length() - 2);
|
||||
piForeach (Argument & a, _args) {
|
||||
piForeach(Argument & a, _args) {
|
||||
if (a.full_key == full) {
|
||||
a.found = true;
|
||||
last = &a;
|
||||
@@ -101,7 +101,7 @@ void PICLI::parse() {
|
||||
last = 0;
|
||||
for (int j = 1; j < cra.length(); ++j) {
|
||||
bool found = false;
|
||||
piForeach (Argument & a, _args) {
|
||||
piForeach(Argument & a, _args) {
|
||||
if ((a.short_key != '\0') && (a.short_key == cra[j])) {
|
||||
a.found = true;
|
||||
last = &a;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Command-Line parser
|
||||
* \~russian Парсер командной строки
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Command-Line Parser
|
||||
@@ -26,17 +26,15 @@
|
||||
#ifndef PICLI_H
|
||||
#define PICLI_H
|
||||
|
||||
#include "pistringlist.h"
|
||||
#include "piset.h"
|
||||
#include "pistringlist.h"
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Command-Line parser.
|
||||
//! \~russian Парсер командной строки.
|
||||
class PIP_EXPORT PICLI
|
||||
{
|
||||
class PIP_EXPORT PICLI {
|
||||
public:
|
||||
|
||||
//! \~english Constructs %PICLI from "argc" and "argv" from "int main()" method.
|
||||
//! \~russian Создает %PICLI из "argc" и "argv" из метода "int main()".
|
||||
PICLI(int argc, char * argv[]);
|
||||
@@ -44,75 +42,147 @@ public:
|
||||
|
||||
//! \~english Add argument with name "name", short key = name first letter and full key = name.
|
||||
//! \~russian Добавляет аргумент с именем "name", коротким ключом = первой букве имени и полным ключом = имени.
|
||||
void addArgument(const PIString & name, bool value = false) {_args << Argument(name, name[0], name, value); needParse = true;}
|
||||
void addArgument(const PIString & name, bool value = false) {
|
||||
_args << Argument(name, name[0], name, value);
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
//! \~english Add argument with name "name", short key = "shortKey" and full key = name.
|
||||
//! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = имени.
|
||||
void addArgument(const PIString & name, const PIChar & shortKey, bool value = false) {_args << Argument(name, shortKey, name, value); needParse = true;}
|
||||
void addArgument(const PIString & name, const PIChar & shortKey, bool value = false) {
|
||||
_args << Argument(name, shortKey, name, value);
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
//! \~english Add argument with name "name", short key = "shortKey" and full key = name.
|
||||
//! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = имени.
|
||||
void addArgument(const PIString & name, const char * shortKey, bool value = false) {_args << Argument(name, PIChar(shortKey), name, value); needParse = true;}
|
||||
void addArgument(const PIString & name, const char * shortKey, bool value = false) {
|
||||
_args << Argument(name, PIChar(shortKey), name, value);
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
//! \~english Add argument with name "name", short key = "shortKey" and full key = "fullKey".
|
||||
//! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = "fullKey".
|
||||
void addArgument(const PIString & name, const PIChar & shortKey, const PIString & fullKey, bool value = false) {_args << Argument(name, shortKey, fullKey, value); needParse = true;}
|
||||
void addArgument(const PIString & name, const PIChar & shortKey, const PIString & fullKey, bool value = false) {
|
||||
_args << Argument(name, shortKey, fullKey, value);
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
//! \~english Add argument with name "name", short key = "shortKey" and full key = "fullKey".
|
||||
//! \~russian Добавляет аргумент с именем "name", коротким ключом = "shortKey" и полным ключом = "fullKey".
|
||||
void addArgument(const PIString & name, const char * shortKey, const PIString & fullKey, bool value = false) {_args << Argument(name, PIChar(shortKey), fullKey, value); needParse = true;}
|
||||
void addArgument(const PIString & name, const char * shortKey, const PIString & fullKey, bool value = false) {
|
||||
_args << Argument(name, PIChar(shortKey), fullKey, value);
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
|
||||
//! \~english Returns unparsed command-line argument by index "index". Index 0 is program execute command.
|
||||
//! \~russian Возвращает исходный аргумент командной строки по индексу "index". Индекс 0 это команда вызова программы.
|
||||
PIString rawArgument(int index) {parse(); return _args_raw[index];}
|
||||
PIString mandatoryArgument(int index) {parse(); return _args_mand[index];}
|
||||
PIString optionalArgument(int index) {parse(); return _args_opt[index];}
|
||||
PIString rawArgument(int index) {
|
||||
parse();
|
||||
return _args_raw[index];
|
||||
}
|
||||
PIString mandatoryArgument(int index) {
|
||||
parse();
|
||||
return _args_mand[index];
|
||||
}
|
||||
PIString optionalArgument(int index) {
|
||||
parse();
|
||||
return _args_opt[index];
|
||||
}
|
||||
|
||||
//! \~english Returns unparsed command-line arguments.
|
||||
//! \~russian Возвращает исходные аргументы командной строки.
|
||||
const PIStringList & rawArguments() {parse(); return _args_raw;}
|
||||
const PIStringList & mandatoryArguments() {parse(); return _args_mand;}
|
||||
const PIStringList & optionalArguments() {parse(); return _args_opt;}
|
||||
const PIStringList & rawArguments() {
|
||||
parse();
|
||||
return _args_raw;
|
||||
}
|
||||
const PIStringList & mandatoryArguments() {
|
||||
parse();
|
||||
return _args_mand;
|
||||
}
|
||||
const PIStringList & optionalArguments() {
|
||||
parse();
|
||||
return _args_opt;
|
||||
}
|
||||
|
||||
//! \~english Returns program execute command without arguments.
|
||||
//! \~russian Возвращает команду вызова программы без аргументов.
|
||||
PIString programCommand() {parse(); return _args_raw.size() > 0 ? _args_raw.front() : PIString();}
|
||||
PIString programCommand() {
|
||||
parse();
|
||||
return _args_raw.size() > 0 ? _args_raw.front() : PIString();
|
||||
}
|
||||
|
||||
//! \~english Returns if argument "name" found.
|
||||
//! \~russian Возвращает найден ли аргумент "name".
|
||||
bool hasArgument(const PIString & name) {parse(); piForeach (Argument & i, _args) if (i.name == name && i.found) return true; return false;}
|
||||
bool hasArgument(const PIString & name) {
|
||||
parse();
|
||||
piForeach(Argument & i, _args)
|
||||
if (i.name == name && i.found) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Returns argument "name" value, or empty string if this is no value.
|
||||
//! \~russian Возвращает значение аргумента "name" или пустую строку, если значения нет.
|
||||
PIString argumentValue(const PIString & name) {parse(); piForeach (Argument &i, _args) if (i.name == name && i.found) return i.value; return PIString();}
|
||||
PIString argumentValue(const PIString & name) {
|
||||
parse();
|
||||
piForeach(Argument & i, _args)
|
||||
if (i.name == name && i.found) return i.value;
|
||||
return PIString();
|
||||
}
|
||||
|
||||
//! \~english Returns short key of argument "name", or empty string if this is no argument.
|
||||
//! \~russian Возвращает короткий ключ аргумента "name" или пустую строку, если аргумента нет.
|
||||
PIString argumentShortKey(const PIString & name) {piForeach (Argument &i, _args) if (i.name == name) return i.short_key; return PIString();}
|
||||
PIString argumentShortKey(const PIString & name) {
|
||||
piForeach(Argument & i, _args)
|
||||
if (i.name == name) return i.short_key;
|
||||
return PIString();
|
||||
}
|
||||
|
||||
//! \~english Returns full key of argument "name", or empty string if this is no argument.
|
||||
//! \~russian Возвращает полный ключ аргумента "name" или пустую строку, если аргумента нет.
|
||||
PIString argumentFullKey(const PIString & name) {piForeach (Argument &i, _args) if (i.name == name) return i.full_key; return PIString();}
|
||||
PIString argumentFullKey(const PIString & name) {
|
||||
piForeach(Argument & i, _args)
|
||||
if (i.name == name) return i.full_key;
|
||||
return PIString();
|
||||
}
|
||||
|
||||
const PIString & shortKeyPrefix() const {return _prefix_short;}
|
||||
const PIString & fullKeyPrefix() const {return _prefix_full;}
|
||||
int mandatoryArgumentsCount() const {return _count_mand;}
|
||||
int optionalArgumentsCount() const {return _count_opt;}
|
||||
void setShortKeyPrefix(const PIString & prefix) {_prefix_short = prefix; needParse = true;}
|
||||
void setFullKeyPrefix(const PIString & prefix) {_prefix_full = prefix; needParse = true;}
|
||||
void setMandatoryArgumentsCount(const int count) {_count_mand = count; needParse = true;}
|
||||
void setOptionalArgumentsCount(const int count) {_count_opt = count; needParse = true;}
|
||||
const PIString & shortKeyPrefix() const { return _prefix_short; }
|
||||
const PIString & fullKeyPrefix() const { return _prefix_full; }
|
||||
int mandatoryArgumentsCount() const { return _count_mand; }
|
||||
int optionalArgumentsCount() const { return _count_opt; }
|
||||
void setShortKeyPrefix(const PIString & prefix) {
|
||||
_prefix_short = prefix;
|
||||
needParse = true;
|
||||
}
|
||||
void setFullKeyPrefix(const PIString & prefix) {
|
||||
_prefix_full = prefix;
|
||||
needParse = true;
|
||||
}
|
||||
void setMandatoryArgumentsCount(const int count) {
|
||||
_count_mand = count;
|
||||
needParse = true;
|
||||
}
|
||||
void setOptionalArgumentsCount(const int count) {
|
||||
_count_opt = count;
|
||||
needParse = true;
|
||||
}
|
||||
|
||||
bool debug() const {return debug_;}
|
||||
void setDebug(bool debug) {debug_ = debug;}
|
||||
PIConstChars className() const {return "PICLI";}
|
||||
PIString name() const {return PIStringAscii("CLI");}
|
||||
bool debug() const { return debug_; }
|
||||
void setDebug(bool debug) { debug_ = debug; }
|
||||
PIConstChars className() const { return "PICLI"; }
|
||||
PIString name() const { return PIStringAscii("CLI"); }
|
||||
|
||||
private:
|
||||
struct Argument {
|
||||
Argument() {has_value = found = false;}
|
||||
Argument(const PIString & n, const PIChar & s, const PIString & f, bool v) {name = n; short_key = s; full_key = f; has_value = v; found = false;}
|
||||
Argument() { has_value = found = false; }
|
||||
Argument(const PIString & n, const PIChar & s, const PIString & f, bool v) {
|
||||
name = n;
|
||||
short_key = s;
|
||||
full_key = f;
|
||||
has_value = v;
|
||||
found = false;
|
||||
}
|
||||
PIString name;
|
||||
PIChar short_key;
|
||||
PIString full_key;
|
||||
@@ -128,7 +198,6 @@ private:
|
||||
PIVector<Argument> _args;
|
||||
int _count_mand, _count_opt;
|
||||
bool needParse, debug_;
|
||||
|
||||
};
|
||||
|
||||
#endif // PICLI_H
|
||||
|
||||
@@ -40,37 +40,35 @@
|
||||
PIStringList PICollection::groups() {
|
||||
PIStringList sl;
|
||||
PIVector<PICollection::Group> & cg(_groups());
|
||||
piForeachC (Group & g, cg)
|
||||
piForeachC(Group & g, cg)
|
||||
sl << g.name;
|
||||
return sl;
|
||||
}
|
||||
|
||||
|
||||
PIVector<const PIObject * > PICollection::groupElements(const PIString & group) {
|
||||
PIVector<const PIObject *> PICollection::groupElements(const PIString & group) {
|
||||
PIVector<PICollection::Group> & cg(_groups());
|
||||
piForeachC (Group & g, cg)
|
||||
if (g.name == group)
|
||||
return g.elements;
|
||||
return PIVector<const PIObject * >();
|
||||
piForeachC(Group & g, cg)
|
||||
if (g.name == group) return g.elements;
|
||||
return PIVector<const PIObject *>();
|
||||
}
|
||||
|
||||
|
||||
bool PICollection::addToGroup(const PIString & group, const PIObject * element) {
|
||||
//piCout << "add to" << group << element;
|
||||
// piCout << "add to" << group << element;
|
||||
PIString n = PIStringAscii(element->className());
|
||||
PIVector<PICollection::Group> & cg(_groups());
|
||||
piForeach (Group & g, cg)
|
||||
piForeach(Group & g, cg)
|
||||
if (g.name == group) {
|
||||
for (int i = 0; i < g.elements.size_s(); ++i)
|
||||
if (PIString(g.elements[i]->className()) == n)
|
||||
return false;
|
||||
if (PIString(g.elements[i]->className()) == n) return false;
|
||||
g.elements << element;
|
||||
//piCout << "new group" << group << ", ok";
|
||||
// piCout << "new group" << group << ", ok";
|
||||
return true;
|
||||
}
|
||||
_groups() << Group(group);
|
||||
_groups().back().elements << element;
|
||||
//piCout << "new group" << group << ", ok";
|
||||
// piCout << "new group" << group << ", ok";
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -83,9 +81,7 @@ PIVector<PICollection::Group> & PICollection::_groups() {
|
||||
|
||||
PICollection::CollectionAdder::CollectionAdder(const PIString & group, const PIObject * element, const PIString & name, bool own) {
|
||||
if (!element) return;
|
||||
if (name.isNotEmpty())
|
||||
const_cast<PIObject * >(element)->setName(name);
|
||||
if (name.isNotEmpty()) const_cast<PIObject *>(element)->setName(name);
|
||||
bool added = PICollection::addToGroup(group, element);
|
||||
if (!added && own)
|
||||
delete element;
|
||||
if (!added && own) delete element;
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Unique classes collection
|
||||
* \~russian Коллекция уникальных классов
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Peer - named I/O ethernet node, forming self-organized peering network
|
||||
@@ -104,11 +104,11 @@
|
||||
//! \~\brief
|
||||
//! \~english Helper to collect and retrieve classes to groups.
|
||||
//! \~russian Помощник для создания и получения классов в группы.
|
||||
class PIP_EXPORT PICollection
|
||||
{
|
||||
class PIP_EXPORT PICollection {
|
||||
friend class __PICollectionInitializer;
|
||||
|
||||
public:
|
||||
PICollection() {;}
|
||||
PICollection() { ; }
|
||||
|
||||
//! \~english Returns all existing groups by their names
|
||||
//! \~russian Возвращает имена всех групп
|
||||
@@ -116,7 +116,7 @@ public:
|
||||
|
||||
//! \~english Returns all elements of group "group"
|
||||
//! \~russian Возвращает все элементы группы "group"
|
||||
static PIVector<const PIObject * > groupElements(const PIString & group);
|
||||
static PIVector<const PIObject *> groupElements(const PIString & group);
|
||||
|
||||
static bool addToGroup(const PIString & group, const PIObject * element);
|
||||
|
||||
@@ -127,13 +127,12 @@ public:
|
||||
|
||||
protected:
|
||||
struct PIP_EXPORT Group {
|
||||
Group(const PIString & name_ = PIString()) {name = name_;}
|
||||
Group(const PIString & name_ = PIString()) { name = name_; }
|
||||
PIString name;
|
||||
PIVector<const PIObject * > elements;
|
||||
PIVector<const PIObject *> elements;
|
||||
};
|
||||
|
||||
static PIVector<Group> & _groups();
|
||||
|
||||
};
|
||||
|
||||
#endif // PICOLLECTION_H
|
||||
|
||||
@@ -51,12 +51,12 @@
|
||||
#ifndef PICOREMODULE_H
|
||||
#define PICOREMODULE_H
|
||||
|
||||
#include "picollection.h"
|
||||
#include "piobject.h"
|
||||
#include "pitime.h"
|
||||
#include "picli.h"
|
||||
#include "pichunkstream.h"
|
||||
#include "pipropertystorage.h"
|
||||
#include "picli.h"
|
||||
#include "picollection.h"
|
||||
#include "pijson.h"
|
||||
#include "piobject.h"
|
||||
#include "pipropertystorage.h"
|
||||
#include "pitime.h"
|
||||
|
||||
#endif // PICOREMODULE_H
|
||||
|
||||
@@ -16,20 +16,21 @@
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "piincludes_p.h"
|
||||
#include "picout.h"
|
||||
|
||||
#include "pibytearray.h"
|
||||
#include "pistack.h"
|
||||
#include "piincludes_p.h"
|
||||
#include "piobject.h"
|
||||
#include "pistack.h"
|
||||
#include "pistring_std.h"
|
||||
#ifdef HAS_LOCALE
|
||||
# include <locale>
|
||||
# include <codecvt>
|
||||
# include <locale>
|
||||
#endif
|
||||
#ifdef WINDOWS
|
||||
# include <wincon.h>
|
||||
# include <windows.h>
|
||||
# include <wingdi.h>
|
||||
# include <wincon.h>
|
||||
# define COMMON_LVB_UNDERSCORE 0x8000
|
||||
#endif
|
||||
|
||||
@@ -106,13 +107,13 @@
|
||||
|
||||
class NotifierObject: public PIObject {
|
||||
PIOBJECT(NotifierObject)
|
||||
|
||||
public:
|
||||
NotifierObject() {}
|
||||
EVENT2(finished, int, id, PIString*, buffer);
|
||||
EVENT2(finished, int, id, PIString *, buffer);
|
||||
};
|
||||
|
||||
|
||||
|
||||
PICout::Notifier::Notifier() {
|
||||
o = new NotifierObject();
|
||||
}
|
||||
@@ -129,12 +130,16 @@ PIObject * PICout::Notifier::object() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
using namespace PICoutManipulators;
|
||||
|
||||
PIMutex & PICout::__mutex__() {static PIMutex * ret = new PIMutex(); return *ret;}
|
||||
PIString & PICout::__string__() {static PIString * ret = new PIString(); return *ret;}
|
||||
PIMutex & PICout::__mutex__() {
|
||||
static PIMutex * ret = new PIMutex();
|
||||
return *ret;
|
||||
}
|
||||
PIString & PICout::__string__() {
|
||||
static PIString * ret = new PIString();
|
||||
return *ret;
|
||||
}
|
||||
|
||||
PICout::OutputDevices PICout::devs = PICout::StdOut;
|
||||
|
||||
@@ -164,9 +169,16 @@ PICout::PICout(bool active): fo_(true), cc_(false), fc_(false), act_(active), cn
|
||||
}
|
||||
|
||||
|
||||
PICout::PICout(const PICout & other): fo_(other.fo_), cc_(true), fc_(false), act_(other.act_), cnb_(other.cnb_), attr_(other.attr_),
|
||||
id_(other.id_), buffer_(other.buffer_), co_(other.co_) {
|
||||
}
|
||||
PICout::PICout(const PICout & other)
|
||||
: fo_(other.fo_)
|
||||
, cc_(true)
|
||||
, fc_(false)
|
||||
, act_(other.act_)
|
||||
, cnb_(other.cnb_)
|
||||
, attr_(other.attr_)
|
||||
, id_(other.id_)
|
||||
, buffer_(other.buffer_)
|
||||
, co_(other.co_) {}
|
||||
|
||||
|
||||
PICout::~PICout() {
|
||||
@@ -178,12 +190,12 @@ PICout::~PICout() {
|
||||
PICout::__mutex__().unlock();
|
||||
}
|
||||
if (buffer_) {
|
||||
((NotifierObject*)Notifier::object())->finished(id_, buffer_);
|
||||
((NotifierObject *)Notifier::object())->finished(id_, buffer_);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
PICout & PICout::operator <<(PICoutAction v) {
|
||||
PICout & PICout::operator<<(PICoutAction v) {
|
||||
if (!act_) return *this;
|
||||
#ifdef WINDOWS
|
||||
CONSOLE_SCREEN_BUFFER_INFO sbi;
|
||||
@@ -270,7 +282,7 @@ PICout & PICout::operator <<(PICoutAction v) {
|
||||
}
|
||||
|
||||
|
||||
PICout & PICout::operator <<(PICoutManipulators::PICoutFormat v) {
|
||||
PICout & PICout::operator<<(PICoutManipulators::PICoutFormat v) {
|
||||
switch (v) {
|
||||
case PICoutManipulators::Bin: cnb_ = 2; break;
|
||||
case PICoutManipulators::Oct: cnb_ = 8; break;
|
||||
@@ -282,7 +294,7 @@ PICout & PICout::operator <<(PICoutManipulators::PICoutFormat v) {
|
||||
}
|
||||
|
||||
|
||||
PICout & PICout::operator <<(PIFlags<PICoutManipulators::PICoutFormat> v) {
|
||||
PICout & PICout::operator<<(PIFlags<PICoutManipulators::PICoutFormat> v) {
|
||||
if (v[PICoutManipulators::Bin]) cnb_ = 2;
|
||||
if (v[PICoutManipulators::Oct]) cnb_ = 8;
|
||||
if (v[PICoutManipulators::Dec]) cnb_ = 10;
|
||||
@@ -312,32 +324,35 @@ PICout & PICout::operator <<(PIFlags<PICoutManipulators::PICoutFormat> v) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
#define PIINTCOUT(v) { \
|
||||
#define PIINTCOUT(v) \
|
||||
{ \
|
||||
if (!act_) return *this; \
|
||||
space(); \
|
||||
if (cnb_ == 10) {\
|
||||
if (buffer_) {\
|
||||
(*buffer_) += PIString::fromNumber(v);\
|
||||
} else {\
|
||||
if (PICout::isOutputDeviceActive(PICout::StdOut)) std::cout << (v);\
|
||||
if (PICout::isOutputDeviceActive(PICout::Buffer)) PICout::__string__() += PIString::fromNumber(v);\
|
||||
}\
|
||||
} else write(PIString::fromNumber(v, cnb_)); \
|
||||
if (cnb_ == 10) { \
|
||||
if (buffer_) { \
|
||||
(*buffer_) += PIString::fromNumber(v); \
|
||||
} else { \
|
||||
if (PICout::isOutputDeviceActive(PICout::StdOut)) std::cout << (v); \
|
||||
if (PICout::isOutputDeviceActive(PICout::Buffer)) PICout::__string__() += PIString::fromNumber(v); \
|
||||
} \
|
||||
} else \
|
||||
write(PIString::fromNumber(v, cnb_)); \
|
||||
return *this; \
|
||||
}
|
||||
|
||||
#define PIFLOATCOUT(v) { \
|
||||
if (buffer_) {\
|
||||
(*buffer_) += PIString::fromNumber(v, 'g');\
|
||||
} else {\
|
||||
if (PICout::isOutputDeviceActive(PICout::StdOut)) std::cout << (v);\
|
||||
if (PICout::isOutputDeviceActive(PICout::Buffer)) PICout::__string__() += PIString::fromNumber(v, 'g');\
|
||||
}\
|
||||
}\
|
||||
#define PIFLOATCOUT(v) \
|
||||
{ \
|
||||
if (buffer_) { \
|
||||
(*buffer_) += PIString::fromNumber(v, 'g'); \
|
||||
} else { \
|
||||
if (PICout::isOutputDeviceActive(PICout::StdOut)) std::cout << (v); \
|
||||
if (PICout::isOutputDeviceActive(PICout::Buffer)) PICout::__string__() += PIString::fromNumber(v, 'g'); \
|
||||
} \
|
||||
} \
|
||||
return *this;
|
||||
|
||||
|
||||
PICout & PICout::operator <<(const PIString & v) {
|
||||
PICout & PICout::operator<<(const PIString & v) {
|
||||
space();
|
||||
quote();
|
||||
write(v);
|
||||
@@ -345,7 +360,7 @@ PICout & PICout::operator <<(const PIString & v) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(const char * v) {
|
||||
PICout & PICout::operator<<(const char * v) {
|
||||
if (!act_ || !v) return *this;
|
||||
if (v[0] == '\0') return *this;
|
||||
space();
|
||||
@@ -355,56 +370,71 @@ PICout & PICout::operator <<(const char * v) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(bool v) {
|
||||
PICout & PICout::operator<<(bool v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
if (v) write("true");
|
||||
else write("false");
|
||||
if (v)
|
||||
write("true");
|
||||
else
|
||||
write("false");
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(char v) {
|
||||
PICout & PICout::operator<<(char v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
write(v);
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(uchar v) {PIINTCOUT(ushort(v))}
|
||||
PICout & PICout::operator<<(uchar v){PIINTCOUT(ushort(v))}
|
||||
|
||||
PICout & PICout::operator <<(short int v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(short int v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(ushort v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(ushort v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(int v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(int v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(uint v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(uint v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(long v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(long v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(ulong v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(ulong v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(llong v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(llong v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(ullong v) {PIINTCOUT(v)}
|
||||
PICout & PICout::operator<<(ullong v){PIINTCOUT(v)}
|
||||
|
||||
PICout & PICout::operator <<(float v) {if (!act_) return *this; space(); PIFLOATCOUT(v)}
|
||||
PICout & PICout::operator<<(float v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
PIFLOATCOUT(v)
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(double v) {if (!act_) return *this; space(); PIFLOATCOUT(v)}
|
||||
PICout & PICout::operator<<(double v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
PIFLOATCOUT(v)
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(ldouble v) {if (!act_) return *this; space(); PIFLOATCOUT(v)}
|
||||
PICout & PICout::operator<<(ldouble v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
PIFLOATCOUT(v)
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(const void * v) {
|
||||
PICout & PICout::operator<<(const void * v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
write("0x" + PIString::fromNumber(ullong(v), 16));
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(const PIObject * v) {
|
||||
PICout & PICout::operator<<(const PIObject * v) {
|
||||
if (!act_) return *this;
|
||||
space();
|
||||
if (v == 0) write("PIObject*(0x0)");
|
||||
if (v == 0)
|
||||
write("PIObject*(0x0)");
|
||||
else {
|
||||
write(v->className());
|
||||
write("*(0x" + PIString::fromNumber(ullong(v), 16) + ", \"" + v->name() + "\")");
|
||||
@@ -412,7 +442,7 @@ PICout & PICout::operator <<(const PIObject * v) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
PICout & PICout::operator <<(PICoutSpecialChar v) {
|
||||
PICout & PICout::operator<<(PICoutSpecialChar v) {
|
||||
if (!act_) return *this;
|
||||
switch (v) {
|
||||
case Null:
|
||||
@@ -487,7 +517,6 @@ PICout & PICout::restoreControls() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
//! \details
|
||||
//! \~english
|
||||
//! If it is not a first output and control \a AddSpaces is set space character is put
|
||||
@@ -594,9 +623,11 @@ PICout & PICout::write(const PIString & s) {
|
||||
void PICout::stdoutPIString(const PIString & s) {
|
||||
#ifdef HAS_LOCALE
|
||||
std::wstring_convert<std::codecvt_utf8<char16_t>, char16_t> utf8conv;
|
||||
std::cout << utf8conv.to_bytes((char16_t*)&(const_cast<PIString&>(s).front()), (char16_t*)&(const_cast<PIString&>(s).front()) + s.size());
|
||||
std::cout << utf8conv.to_bytes((char16_t *)&(const_cast<PIString &>(s).front()),
|
||||
(char16_t *)&(const_cast<PIString &>(s).front()) + s.size());
|
||||
#else
|
||||
for (PIChar c: s) std::wcout.put(c.toWChar());
|
||||
for (PIChar c: s)
|
||||
std::wcout.put(c.toWChar());
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -626,7 +657,10 @@ void PICout::applyFormat(PICoutFormat f) {
|
||||
static int mask_fore = ~(FOREGROUND_RED | FOREGROUND_GREEN | FOREGROUND_BLUE);
|
||||
static int mask_back = ~(BACKGROUND_RED | BACKGROUND_GREEN | BACKGROUND_BLUE);
|
||||
switch (f) {
|
||||
case Bin: case Oct: case Dec: case Hex: break;
|
||||
case Bin:
|
||||
case Oct:
|
||||
case Dec:
|
||||
case Hex: break;
|
||||
case PICoutManipulators::Bold: attr_ |= FOREGROUND_INTENSITY; break;
|
||||
case PICoutManipulators::Underline: attr_ |= COMMON_LVB_UNDERSCORE; break;
|
||||
case PICoutManipulators::Black: attr_ = (attr_ & mask_fore); break;
|
||||
@@ -651,7 +685,10 @@ void PICout::applyFormat(PICoutFormat f) {
|
||||
SetConsoleTextAttribute(__Private__::hOut, attr_);
|
||||
#else
|
||||
switch (f) {
|
||||
case Bin: case Oct: case Dec: case Hex: break;
|
||||
case Bin:
|
||||
case Oct:
|
||||
case Dec:
|
||||
case Hex: break;
|
||||
case PICoutManipulators::Bold: printf("\e[1m"); break;
|
||||
case PICoutManipulators::Faint: printf("\e[2m"); break;
|
||||
case PICoutManipulators::Italic: printf("\e[3m"); break;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Universal output to console class
|
||||
* \~russian Универсальный вывод в консоль
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Universal output to console class
|
||||
@@ -41,7 +41,9 @@
|
||||
|
||||
#else
|
||||
# define piCout PICout(piDebug)
|
||||
# define piCoutObj PICout(piDebug && debug()) << (PIStringAscii("[") + className() + (name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]")))
|
||||
# define piCoutObj \
|
||||
PICout(piDebug && debug()) << (PIStringAscii("[") + className() + \
|
||||
(name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]")))
|
||||
#endif
|
||||
|
||||
|
||||
@@ -53,19 +55,19 @@ class PIObject;
|
||||
//! \~russian Пространство имен содержит перечисления для контроля PICout
|
||||
namespace PICoutManipulators {
|
||||
|
||||
//! \~english Enum contains special characters
|
||||
//! \~russian Перечисление со спецсимволами
|
||||
enum PICoutSpecialChar {
|
||||
//! \~english Enum contains special characters
|
||||
//! \~russian Перечисление со спецсимволами
|
||||
enum PICoutSpecialChar {
|
||||
Null /*! \~english Null-character, '\\0' \~russian Нулевой символ, '\\0' */,
|
||||
NewLine /*! \~english New line character, '\\n' \~russian Новая строка, '\\n' */,
|
||||
Tab /*! \~english Tab character, '\\t' \~russian Табуляция, '\\t' */,
|
||||
Esc /*! \~english Escape character, '\\e' \~russian Esc-символ, '\\e' */,
|
||||
Quote /*! \~english Quote character, '\"' \~russian Кавычки, '\"' */
|
||||
};
|
||||
};
|
||||
|
||||
//! \~english Enum contains immediate action
|
||||
//! \~russian Перечисление с немедленными действиями
|
||||
enum PICoutAction {
|
||||
//! \~english Enum contains immediate action
|
||||
//! \~russian Перечисление с немедленными действиями
|
||||
enum PICoutAction {
|
||||
Flush /*! \~english Flush the output \~russian Обновить вывод */,
|
||||
Backspace /*! \~english Remove last symbol \~russian Удалить последний символ */,
|
||||
ShowCursor /*! \~english Show cursor \~russian Показать курсор */,
|
||||
@@ -73,12 +75,13 @@ namespace PICoutManipulators {
|
||||
ClearLine /*! \~english Clear current line \~russian Очистить текущую строку */,
|
||||
ClearScreen /*! \~english Clear the screen \~russian Очистить экран */,
|
||||
SaveContol /*! \~english Save control flags, equivalent to \a saveControl() \~russian Сохранить флаги, аналогично \a saveControl() */,
|
||||
RestoreControl /*! \~english Restore control flags, equivalent to \a restoreControl() \~russian Восстановить флаги, аналогично \a restoreControl() */
|
||||
};
|
||||
RestoreControl /*! \~english Restore control flags, equivalent to \a restoreControl() \~russian Восстановить флаги, аналогично \a
|
||||
restoreControl() */
|
||||
};
|
||||
|
||||
//! \~english Enum contains control of PICout
|
||||
//! \~russian Перечисление с управлением PICout
|
||||
enum PICoutControl {
|
||||
//! \~english Enum contains control of PICout
|
||||
//! \~russian Перечисление с управлением PICout
|
||||
enum PICoutControl {
|
||||
AddNone /*! \~english No controls \~russian Без управления */ = 0x0,
|
||||
AddSpaces /*! \~english Spaces will be appear after each output \~russian Пробел после каждого вывода */ = 0x1,
|
||||
AddNewLine /*! \~english New line will be appear after all output \~russian Новая строка после завершения вывода */ = 0x2,
|
||||
@@ -86,11 +89,11 @@ namespace PICoutManipulators {
|
||||
DefaultControls /*! \~english Default controls \~russian Управление по умолчанию */ = AddSpaces | AddNewLine,
|
||||
AddAll /*! \~english All controls \~russian Всё управление */ = 0xFF,
|
||||
NoLock /*! \~english Don`t use mutex for output \~russian Не использовать мьютекс при выводе */ = 0x100,
|
||||
};
|
||||
};
|
||||
|
||||
//! \~english Enum contains output format
|
||||
//! \~russian Перечисление с форматом вывода
|
||||
enum PICoutFormat {
|
||||
//! \~english Enum contains output format
|
||||
//! \~russian Перечисление с форматом вывода
|
||||
enum PICoutFormat {
|
||||
Bin /*! \~english Binary representation of integers \~russian Двоичное представление для целых чисел */ = 0x01,
|
||||
Oct /*! \~english Octal representation of integers \~russian Восьмеричное представление для целых чисел */ = 0x02,
|
||||
Dec /*! \~english Decimal representation of integers \~russian Десятичное представление для целых чисел */ = 0x04,
|
||||
@@ -117,12 +120,10 @@ namespace PICoutManipulators {
|
||||
BackCyan /*! \~english Cyan background \~russian Голубой фон */ = 0x1000000,
|
||||
BackWhite /*! \~english White background \~russian Белый фон */ = 0x2000000,
|
||||
Default /*! \~english Default format \~russian Формат по умолчанию */ = 0x4000000
|
||||
};
|
||||
|
||||
typedef PIFlags<PICoutControl> PICoutControls;
|
||||
}
|
||||
|
||||
};
|
||||
|
||||
typedef PIFlags<PICoutControl> PICoutControls;
|
||||
} // namespace PICoutManipulators
|
||||
|
||||
|
||||
//! \ingroup Core
|
||||
@@ -131,7 +132,6 @@ namespace PICoutManipulators {
|
||||
//! \~russian Универсальный вывод в консоль.
|
||||
class PIP_EXPORT PICout {
|
||||
public:
|
||||
|
||||
//! \~english Default constructor with default features (AddSpaces and AddNewLine)
|
||||
//! \~russian Конструктор по умолчанию (AddSpaces и AddNewLine)
|
||||
PICout(int controls = PICoutManipulators::DefaultControls);
|
||||
@@ -154,6 +154,7 @@ public:
|
||||
//! \~english Object that emit events from %PICout
|
||||
//! \~russian Объект, который посылает события от %PICout
|
||||
static PIObject * object();
|
||||
|
||||
private:
|
||||
Notifier();
|
||||
PIObject * o;
|
||||
@@ -172,103 +173,113 @@ public:
|
||||
|
||||
//! \~english Output operator for strings with <tt>"const char * "</tt> type
|
||||
//! \~russian Оператор вывода для строк <tt>"const char * "</tt>
|
||||
PICout & operator <<(const char * v);
|
||||
PICout & operator<<(const char * v);
|
||||
|
||||
//! \~english Output operator for \a PIString
|
||||
//! \~russian Оператор вывода для \a PIString
|
||||
PICout & operator <<(const PIString & v);
|
||||
PICout & operator<<(const PIString & v);
|
||||
|
||||
//! \~english Output operator for boolean values
|
||||
//! \~russian Оператор вывода для логических значений
|
||||
PICout & operator <<(bool v);
|
||||
PICout & operator<<(bool v);
|
||||
|
||||
//! \~english Output operator for <tt>"char"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"char"</tt> значений
|
||||
PICout & operator <<(char v);
|
||||
PICout & operator<<(char v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned char"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned char"</tt> значений
|
||||
PICout & operator <<(uchar v);
|
||||
PICout & operator<<(uchar v);
|
||||
|
||||
//! \~english Output operator for <tt>"short"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"short"</tt> значений
|
||||
PICout & operator <<(short v);
|
||||
PICout & operator<<(short v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned short"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned short"</tt> значений
|
||||
PICout & operator <<(ushort v);
|
||||
PICout & operator<<(ushort v);
|
||||
|
||||
//! \~english Output operator for <tt>"int"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"int"</tt> значений
|
||||
PICout & operator <<(int v);
|
||||
PICout & operator<<(int v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned int"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned int"</tt> значений
|
||||
PICout & operator <<(uint v);
|
||||
PICout & operator<<(uint v);
|
||||
|
||||
//! \~english Output operator for <tt>"long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"long"</tt> значений
|
||||
PICout & operator <<(long v);
|
||||
PICout & operator<<(long v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned long"</tt> значений
|
||||
PICout & operator <<(ulong v);
|
||||
PICout & operator<<(ulong v);
|
||||
|
||||
//! \~english Output operator for <tt>"long long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"long long"</tt> значений
|
||||
PICout & operator <<(llong v);
|
||||
PICout & operator<<(llong v);
|
||||
|
||||
//! \~english Output operator for <tt>"unsigned long long"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"unsigned long long"</tt> значений
|
||||
PICout & operator <<(ullong v);
|
||||
PICout & operator<<(ullong v);
|
||||
|
||||
//! \~english Output operator for <tt>"float"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"float"</tt> значений
|
||||
PICout & operator <<(float v);
|
||||
PICout & operator<<(float v);
|
||||
|
||||
//! \~english Output operator for <tt>"double"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"double"</tt> значений
|
||||
PICout & operator <<(double v);
|
||||
PICout & operator<<(double v);
|
||||
|
||||
//! \~english Output operator for <tt>"ldouble"</tt> values
|
||||
//! \~russian Оператор вывода для <tt>"ldouble"</tt> значений
|
||||
PICout & operator <<(ldouble v);
|
||||
PICout & operator<<(ldouble v);
|
||||
|
||||
//! \~english Output operator for pointers
|
||||
//! \~russian Оператор вывода для указателей
|
||||
PICout & operator <<(const void * v);
|
||||
PICout & operator<<(const void * v);
|
||||
|
||||
//! \~english Output operator for PIObject and ancestors
|
||||
//! \~russian Оператор вывода для PIObject и наследников
|
||||
PICout & operator <<(const PIObject * v);
|
||||
PICout & operator<<(const PIObject * v);
|
||||
|
||||
//! \~english Output operator for \a PICoutSpecialChar values
|
||||
//! \~russian Оператор вывода для \a PICoutSpecialChar
|
||||
PICout & operator <<(PICoutManipulators::PICoutSpecialChar v);
|
||||
PICout & operator<<(PICoutManipulators::PICoutSpecialChar v);
|
||||
|
||||
//! \~english Output operator for \a PIFlags<PICoutFormat> values
|
||||
//! \~russian Оператор вывода для \a PIFlags<PICoutFormat>
|
||||
PICout & operator <<(PIFlags<PICoutManipulators::PICoutFormat> v);
|
||||
PICout & operator<<(PIFlags<PICoutManipulators::PICoutFormat> v);
|
||||
|
||||
//! \~english Output operator for \a PICoutFormat values
|
||||
//! \~russian Оператор вывода для \a PICoutFormat
|
||||
PICout & operator <<(PICoutManipulators::PICoutFormat v);
|
||||
PICout & operator<<(PICoutManipulators::PICoutFormat v);
|
||||
|
||||
//! \~english Do some action
|
||||
//! \~russian Делает действие
|
||||
PICout & operator <<(PICoutManipulators::PICoutAction v);
|
||||
PICout & operator<<(PICoutManipulators::PICoutAction v);
|
||||
|
||||
//! \~english Set control flag "c" is "on" state
|
||||
//! \~russian Установить флаг "c" в "on" состояние
|
||||
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;
|
||||
}
|
||||
|
||||
//! \~english Set control flags "c"
|
||||
//! \~russian Установить флаги "c"
|
||||
PICout & setControls(PICoutManipulators::PICoutControls c) {co_ = c; return *this;}
|
||||
PICout & setControls(PICoutManipulators::PICoutControls c) {
|
||||
co_ = c;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Exec \a saveControls() and set control flags to "c"
|
||||
//! \~russian Иыполнить \a saveControls() и Установить флаги "c"
|
||||
PICout & saveAndSetControls(PICoutManipulators::PICoutControls c) {saveControls(); co_ = c; return *this;}
|
||||
PICout & saveAndSetControls(PICoutManipulators::PICoutControls c) {
|
||||
saveControls();
|
||||
co_ = c;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Save control flags to internal stack
|
||||
//! \~russian Сохраняет состояние флагов во внутренний стек
|
||||
@@ -331,11 +342,11 @@ public:
|
||||
|
||||
//! \~english Turn on output device "d". Returns if it was enabled
|
||||
//! \~russian Включает устройство вывода "d". Возвращает было ли устройство активно
|
||||
static bool enableOutputDevice(OutputDevice d) {return setOutputDevice(d, true);}
|
||||
static bool enableOutputDevice(OutputDevice d) { return setOutputDevice(d, true); }
|
||||
|
||||
//! \~english Turn off output device "d". Returns if it was enabled
|
||||
//! \~russian Выключает устройство вывода "d". Возвращает было ли устройство активно
|
||||
static bool disableOutputDevice(OutputDevice d) {return setOutputDevice(d, false);}
|
||||
static bool disableOutputDevice(OutputDevice d) { return setOutputDevice(d, false); }
|
||||
|
||||
//! \~english Set output to devices to "d"
|
||||
//! \~russian Устанавливает устройства вывода "d"
|
||||
@@ -343,7 +354,7 @@ public:
|
||||
|
||||
//! \~english Returns current output devices
|
||||
//! \~russian Возвращает текущие устройства вывода
|
||||
static OutputDevices currentOutputDevices() {return devs;}
|
||||
static OutputDevices currentOutputDevices() { return devs; }
|
||||
|
||||
//! \~english Returns if output device "d" is active
|
||||
//! \~russian Возвращает активно ли устройство вывода "d"
|
||||
@@ -352,7 +363,10 @@ public:
|
||||
|
||||
//! \~english Construct with external buffer and ID "id". See \a Notifier for details
|
||||
//! \~russian Конструктор с внешним буфером и ID "id". Подробнее \a Notifier
|
||||
static PICout withExternalBuffer(PIString * buffer, int id = 0, PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces | PICoutManipulators::AddNewLine);
|
||||
static PICout withExternalBuffer(PIString * buffer,
|
||||
int id = 0,
|
||||
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces |
|
||||
PICoutManipulators::AddNewLine);
|
||||
|
||||
static PIMutex & __mutex__();
|
||||
static PIString & __string__();
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
#include "piincludes.h"
|
||||
|
||||
#include "piincludes_p.h"
|
||||
#include "pitime.h"
|
||||
#ifndef QNX
|
||||
@@ -26,10 +27,10 @@
|
||||
# include <locale.h>
|
||||
#endif
|
||||
#ifdef MAC_OS
|
||||
//# include <mach/mach_traps.h>
|
||||
//# include <mach/mach.h>
|
||||
// # include <mach/mach_traps.h>
|
||||
// # include <mach/mach.h>
|
||||
# include <mach/clock.h>
|
||||
//# include <crt_externs.h>
|
||||
// # include <crt_externs.h>
|
||||
#endif
|
||||
#include <errno.h>
|
||||
|
||||
@@ -66,7 +67,13 @@ PIString errorString() {
|
||||
#ifdef WINDOWS
|
||||
char * msg = nullptr;
|
||||
int err = GetLastError();
|
||||
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&msg, 0, NULL);
|
||||
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
NULL,
|
||||
err,
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
(LPSTR)&msg,
|
||||
0,
|
||||
NULL);
|
||||
PIString ret = PIStringAscii("code ") + PIString::fromNumber(err) + PIStringAscii(" - ");
|
||||
if (msg) {
|
||||
ret += PIString::fromSystem(msg).trim();
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Minimal PIP includes
|
||||
* \~russian Минимально-необходимые инклюды PIP
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Minimal PIP includes
|
||||
@@ -28,6 +28,7 @@
|
||||
|
||||
#include "pibase.h"
|
||||
#include "piflags.h"
|
||||
|
||||
#include <sys/types.h>
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
# include <iostream>
|
||||
@@ -38,7 +39,8 @@ class PIMutexLocker;
|
||||
class PIObject;
|
||||
class PIString;
|
||||
class PIByteArray;
|
||||
template <typename P> class PIBinaryStream;
|
||||
template<typename P>
|
||||
class PIBinaryStream;
|
||||
#ifndef MICRO_PIP
|
||||
class PIInit;
|
||||
#endif
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
#define PIINCLUDES_P_H
|
||||
|
||||
|
||||
// clang-format off
|
||||
#include "picout.h"
|
||||
#ifdef WINDOWS
|
||||
# ifdef _WIN32_WINNT
|
||||
@@ -29,20 +30,20 @@
|
||||
# include <stdarg.h>
|
||||
# include <windef.h>
|
||||
# include <winbase.h>
|
||||
typedef LONG(NTAPI*PINtQueryTimerResolution)(PULONG, PULONG, PULONG);
|
||||
typedef LONG(NTAPI*PINtSetTimerResolution)(ULONG, BOOLEAN, PULONG);
|
||||
typedef LONG(NTAPI * PINtQueryTimerResolution)(PULONG, PULONG, PULONG);
|
||||
typedef LONG(NTAPI * PINtSetTimerResolution)(ULONG, BOOLEAN, PULONG);
|
||||
#endif
|
||||
#ifdef CC_GCC
|
||||
# include <unistd.h>
|
||||
#endif
|
||||
#include <string.h>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <stdlib.h>
|
||||
#include <cstdlib>
|
||||
#include <stdio.h>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <iostream>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <string>
|
||||
|
||||
#ifdef FREERTOS
|
||||
# ifdef ESP_PLATFORM
|
||||
@@ -53,6 +54,7 @@ typedef LONG(NTAPI*PINtSetTimerResolution)(ULONG, BOOLEAN, PULONG);
|
||||
# include <STM32FreeRTOS.h>
|
||||
# endif
|
||||
#endif
|
||||
// clang-format on
|
||||
|
||||
|
||||
#endif // PIINCLUDES_P_H
|
||||
|
||||
@@ -17,78 +17,77 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "piincludes_p.h"
|
||||
#include "piinit.h"
|
||||
|
||||
#include "piincludes_p.h"
|
||||
#ifndef MICRO_PIP
|
||||
|
||||
#include "pitime.h"
|
||||
#include "pisignals.h"
|
||||
#include "piobject.h"
|
||||
#include "pisysteminfo.h"
|
||||
#include "piresourcesstorage.h"
|
||||
#include "pidir.h"
|
||||
#include "piprocess.h"
|
||||
#ifdef ESP_PLATFORM
|
||||
# include "pidir.h"
|
||||
# include "piobject.h"
|
||||
# include "piprocess.h"
|
||||
# include "piresourcesstorage.h"
|
||||
# include "pisignals.h"
|
||||
# include "pisysteminfo.h"
|
||||
# include "pitime.h"
|
||||
# ifdef ESP_PLATFORM
|
||||
# include "esp_system.h"
|
||||
#endif
|
||||
#include <codecvt>
|
||||
#ifdef WINDOWS
|
||||
# endif
|
||||
# include <codecvt>
|
||||
# ifdef WINDOWS
|
||||
# include <winsock2.h>
|
||||
extern FILETIME __pi_ftjan1970;
|
||||
extern PINtQueryTimerResolution getTimerResolutionAddr;
|
||||
extern PINtSetTimerResolution setTimerResolutionAddr;
|
||||
void __PISetTimerResolution() {
|
||||
if (setTimerResolutionAddr == NULL || getTimerResolutionAddr == NULL)
|
||||
return;
|
||||
if (setTimerResolutionAddr == NULL || getTimerResolutionAddr == NULL) return;
|
||||
ULONG _max(0), _min(0), _cur(0);
|
||||
//printf("getTimerResolution ...\n");
|
||||
// printf("getTimerResolution ...\n");
|
||||
LONG q = getTimerResolutionAddr(&_max, &_min, &_cur);
|
||||
//printf("getTimerResolution %d %lu %lu %lu\n", q, _min, _max, _cur);
|
||||
if (q == 0)
|
||||
setTimerResolutionAddr(_min, TRUE, &_cur);
|
||||
//printf("setTimerResolution %lu\n", cur);
|
||||
// printf("getTimerResolution %d %lu %lu %lu\n", q, _min, _max, _cur);
|
||||
if (q == 0) setTimerResolutionAddr(_min, TRUE, &_cur);
|
||||
// printf("setTimerResolution %lu\n", cur);
|
||||
}
|
||||
#else
|
||||
# else
|
||||
# include <pthread.h>
|
||||
# include <pwd.h>
|
||||
# include <sys/utsname.h>
|
||||
# include <pthread.h>
|
||||
# ifdef BLACKBERRY
|
||||
# include <signal.h>
|
||||
# else
|
||||
# include <csignal>
|
||||
# endif
|
||||
#endif
|
||||
#ifdef MAC_OS
|
||||
# include <mach/mach_traps.h>
|
||||
# include <mach/mach.h>
|
||||
# endif
|
||||
# ifdef MAC_OS
|
||||
# include <mach/clock.h>
|
||||
# include <mach/mach.h>
|
||||
# include <mach/mach_traps.h>
|
||||
extern clock_serv_t __pi_mac_clock;
|
||||
#endif
|
||||
#ifdef PIP_ICU
|
||||
# endif
|
||||
# ifdef PIP_ICU
|
||||
# define U_NOEXCEPT
|
||||
# include <unicode/uclean.h>
|
||||
# include <unicode/ucnv.h>
|
||||
#endif
|
||||
# endif
|
||||
|
||||
|
||||
#ifdef HAS_LOCALE
|
||||
# ifdef HAS_LOCALE
|
||||
static locale_t currentLocale_t = 0;
|
||||
#endif
|
||||
# endif
|
||||
|
||||
PRIVATE_DEFINITION_START(PIInit)
|
||||
#ifdef WINDOWS
|
||||
HMODULE ntlib;
|
||||
ULONG prev_res;
|
||||
#endif
|
||||
bool delete_locs;
|
||||
# ifdef WINDOWS
|
||||
HMODULE ntlib;
|
||||
ULONG prev_res;
|
||||
# endif
|
||||
bool delete_locs;
|
||||
PRIVATE_DEFINITION_END(PIInit)
|
||||
|
||||
void __sighandler__(PISignals::Signal s) {
|
||||
//piCout << Hex << int(s);
|
||||
if (s == PISignals::StopTTYInput || s == PISignals::StopTTYOutput)
|
||||
piMSleep(10);
|
||||
// piCout << Hex << int(s);
|
||||
if (s == PISignals::StopTTYInput || s == PISignals::StopTTYOutput) piMSleep(10);
|
||||
if (s == PISignals::UserDefined1)
|
||||
dumpApplicationToFile(PIDir::home().path() + PIDir::separator + PIStringAscii("_PIP_DUMP_") + PIString::fromNumber(PIProcess::currentPID()));
|
||||
dumpApplicationToFile(PIDir::home().path() + PIDir::separator + PIStringAscii("_PIP_DUMP_") +
|
||||
PIString::fromNumber(PIProcess::currentPID()));
|
||||
}
|
||||
|
||||
|
||||
@@ -97,7 +96,7 @@ PIInit::PIInit() {
|
||||
PISystemInfo * sinfo = PISystemInfo::instance();
|
||||
sinfo->execDateTime = PIDateTime::current();
|
||||
setFileCharset("UTF-8");
|
||||
#ifndef ANDROID
|
||||
# ifndef ANDROID
|
||||
PISignals::setSlot(__sighandler__);
|
||||
PISignals::grabSignals(PISignals::UserDefined1);
|
||||
# ifndef WINDOWS
|
||||
@@ -109,15 +108,15 @@ PIInit::PIInit() {
|
||||
pthread_sigmask(SIG_BLOCK, &ss, 0);
|
||||
signal(SIGPIPE, SIG_IGN);
|
||||
PIStringList ifpathes;
|
||||
ifpathes << PIStringAscii("/bin/ifconfig") << PIStringAscii("/sbin/ifconfig")
|
||||
<< PIStringAscii("/usr/bin/ifconfig") << PIStringAscii("/usr/sbin/ifconfig");
|
||||
piForeachC (PIString & i, ifpathes) {
|
||||
ifpathes << PIStringAscii("/bin/ifconfig") << PIStringAscii("/sbin/ifconfig") << PIStringAscii("/usr/bin/ifconfig")
|
||||
<< PIStringAscii("/usr/sbin/ifconfig");
|
||||
piForeachC(PIString & i, ifpathes) {
|
||||
if (fileExists(i)) {
|
||||
sinfo->ifconfigPath = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
# else //WINDOWS
|
||||
# else // WINDOWS
|
||||
// OS version
|
||||
DWORD dwVersion = GetVersion();
|
||||
DWORD dwMajorVersion = (DWORD)(LOBYTE(LOWORD(dwVersion)));
|
||||
@@ -143,27 +142,27 @@ PIInit::PIInit() {
|
||||
setTimerResolutionAddr = (PINtSetTimerResolution)GetProcAddress(PRIVATE->ntlib, "NtSetTimerResolution");
|
||||
__PISetTimerResolution();
|
||||
}
|
||||
# endif //WINDOWS
|
||||
# endif // WINDOWS
|
||||
# ifdef HAS_LOCALE
|
||||
//std::cout << "has locale" << std::endl;
|
||||
// std::cout << "has locale" << std::endl;
|
||||
if (currentLocale_t != 0) {
|
||||
freelocale(currentLocale_t);
|
||||
currentLocale_t = 0;
|
||||
}
|
||||
currentLocale_t = newlocale(LC_ALL, setlocale(LC_ALL, "C"), 0);
|
||||
setlocale(LC_CTYPE, "en_US.UTF-8");
|
||||
//std::ios_base::sync_with_stdio(false);
|
||||
//std::locale utf8( std::locale(), new std::codecvt_utf8<wchar_t> );
|
||||
//std::wcout.imbue(utf8);
|
||||
# else //HAS_LOCALE
|
||||
// std::ios_base::sync_with_stdio(false);
|
||||
// std::locale utf8( std::locale(), new std::codecvt_utf8<wchar_t> );
|
||||
// std::wcout.imbue(utf8);
|
||||
# else // HAS_LOCALE
|
||||
setlocale(LC_ALL, "");
|
||||
setlocale(LC_NUMERIC, "C");
|
||||
# endif //HAS_LOCALE
|
||||
#endif //ANDROID
|
||||
# endif // HAS_LOCALE
|
||||
# endif // ANDROID
|
||||
PRIVATE->delete_locs = false;
|
||||
__syslocname__ = __sysoemname__ = 0;
|
||||
__utf8name__ = const_cast<char*>("UTF-8");
|
||||
#ifdef PIP_ICU
|
||||
__utf8name__ = const_cast<char *>("UTF-8");
|
||||
# ifdef PIP_ICU
|
||||
UErrorCode e((UErrorCode)0);
|
||||
u_init(&e);
|
||||
# ifdef WINDOWS
|
||||
@@ -172,8 +171,7 @@ PIInit::PIInit() {
|
||||
int l = 0;
|
||||
GetCPInfoEx(CP_OEMCP, 0, &cpinfo);
|
||||
for (l = 0; l < MAX_PATH; ++l)
|
||||
if (cpinfo.CodePageName[l] == '\0' || cpinfo.CodePageName[l] == ' ')
|
||||
break;
|
||||
if (cpinfo.CodePageName[l] == '\0' || cpinfo.CodePageName[l] == ' ') break;
|
||||
__sysoemname__ = new char[256];
|
||||
memset(__sysoemname__, 0, 256);
|
||||
memcpy(__sysoemname__, "ibm-", 4);
|
||||
@@ -185,24 +183,24 @@ PIInit::PIInit() {
|
||||
PIByteArray enba = en.toByteArray();
|
||||
memcpy(__syslocname__, enba.data(), enba.size_s());*/
|
||||
# endif
|
||||
//piCout << __syslocname__;
|
||||
//piCout << __sysoemname__;
|
||||
#else //PIP_ICU
|
||||
// piCout << __syslocname__;
|
||||
// piCout << __sysoemname__;
|
||||
# else // PIP_ICU
|
||||
# ifdef WINDOWS
|
||||
__syslocname__ = (char *)CP_ACP;
|
||||
__sysoemname__ = (char *)CP_OEMCP;
|
||||
__utf8name__ = (char *)CP_UTF8;
|
||||
# endif
|
||||
#endif //PIP_ICU
|
||||
#ifdef MAC_OS
|
||||
# endif // PIP_ICU
|
||||
# ifdef MAC_OS
|
||||
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &__pi_mac_clock);
|
||||
#endif
|
||||
# endif
|
||||
char cbuff[1024];
|
||||
memset(cbuff, 0, 1024);
|
||||
if (gethostname(cbuff, 1023) == 0) {
|
||||
sinfo->hostname = cbuff;
|
||||
}
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
SYSTEM_INFO sysinfo;
|
||||
GetSystemInfo(&sysinfo);
|
||||
sinfo->processorsCount = sysinfo.dwNumberOfProcessors;
|
||||
@@ -216,14 +214,12 @@ PIInit::PIInit() {
|
||||
}
|
||||
int argc_(0);
|
||||
wchar_t ** argv_ = CommandLineToArgvW(GetCommandLineW(), &argc_);
|
||||
if (argc_ > 0 && argv_ != 0)
|
||||
sinfo->execCommand = argv_[0];
|
||||
if (argc_ > 0 && argv_ != 0) sinfo->execCommand = argv_[0];
|
||||
LocalFree(argv_);
|
||||
memset(cbuff, 0, 1024);
|
||||
ulong unlen = 1023;
|
||||
if (GetUserNameA(cbuff, &unlen) != 0)
|
||||
sinfo->user = cbuff;
|
||||
#else //WINDOWS
|
||||
if (GetUserNameA(cbuff, &unlen) != 0) sinfo->user = cbuff;
|
||||
# else // WINDOWS
|
||||
sinfo->processorsCount = piMaxi(1, int(sysconf(_SC_NPROCESSORS_ONLN)));
|
||||
passwd * ps = getpwuid(getuid());
|
||||
if (ps)
|
||||
@@ -231,42 +227,41 @@ PIInit::PIInit() {
|
||||
else {
|
||||
memset(cbuff, 0, 1024);
|
||||
char * l = getlogin();
|
||||
if (l)
|
||||
sinfo->user = l;
|
||||
if (l) sinfo->user = l;
|
||||
}
|
||||
struct utsname uns;
|
||||
if (uname(&uns) == 0) {
|
||||
sinfo->OS_version = uns.release;
|
||||
sinfo->architecture = uns.machine;
|
||||
}
|
||||
#endif //WINDOWS
|
||||
# endif // WINDOWS
|
||||
|
||||
#ifdef ESP_PLATFORM
|
||||
# ifdef ESP_PLATFORM
|
||||
esp_chip_info_t chip_info;
|
||||
esp_chip_info(&chip_info);
|
||||
sinfo->processorsCount = chip_info.cores;
|
||||
sinfo->architecture = "Xtensa LX6";
|
||||
//printf("silicon revision %d, ", chip_info.revision);
|
||||
// printf("silicon revision %d, ", chip_info.revision);
|
||||
sinfo->OS_version = esp_get_idf_version();
|
||||
#endif
|
||||
# endif
|
||||
sinfo->OS_name =
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
PIStringAscii("Windows");
|
||||
#elif defined(QNX)
|
||||
# elif defined(QNX)
|
||||
PIStringAscii("QNX");
|
||||
#elif defined(MAC_OS)
|
||||
# elif defined(MAC_OS)
|
||||
PIStringAscii("MacOS");
|
||||
#elif defined(ANDROID)
|
||||
# elif defined(ANDROID)
|
||||
PIStringAscii("Android");
|
||||
#elif defined(FREE_BSD)
|
||||
# elif defined(FREE_BSD)
|
||||
PIStringAscii("FreeBSD");
|
||||
#elif defined(FREERTOS)
|
||||
# elif defined(FREERTOS)
|
||||
PIStringAscii("FreeRTOS");
|
||||
#elif defined(MICRO_PIP)
|
||||
# elif defined(MICRO_PIP)
|
||||
PIStringAscii("MicroPIP");
|
||||
#else
|
||||
# else
|
||||
uns.sysname;
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
@@ -274,74 +269,82 @@ PIInit::~PIInit() {
|
||||
if (file_charset) delete[] file_charset;
|
||||
file_charset = 0;
|
||||
PIResourcesStorage::instance()->clear();
|
||||
#ifdef WINDOWS
|
||||
# ifdef WINDOWS
|
||||
WSACleanup();
|
||||
if (PRIVATE->ntlib) FreeLibrary(PRIVATE->ntlib);
|
||||
PRIVATE->ntlib = 0;
|
||||
#endif
|
||||
#ifdef MAC_OS
|
||||
# endif
|
||||
# ifdef MAC_OS
|
||||
mach_port_deallocate(mach_task_self(), __pi_mac_clock);
|
||||
#endif
|
||||
# endif
|
||||
if (PRIVATE->delete_locs) {
|
||||
if (__syslocname__) delete __syslocname__;
|
||||
if (__sysoemname__) delete __sysoemname__;
|
||||
}
|
||||
#ifdef PIP_ICU
|
||||
# ifdef PIP_ICU
|
||||
u_cleanup();
|
||||
#endif
|
||||
# endif
|
||||
}
|
||||
|
||||
|
||||
bool PIInit::isBuildOptionEnabled(PIInit::BuildOption o) {
|
||||
switch (o) {
|
||||
case boICU: return
|
||||
#ifdef PIP_ICU
|
||||
case boICU:
|
||||
return
|
||||
# ifdef PIP_ICU
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boUSB: return
|
||||
#ifdef PIP_USB
|
||||
# endif
|
||||
case boUSB:
|
||||
return
|
||||
# ifdef PIP_USB
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boCrypt: return
|
||||
#ifdef PIP_CRYPT
|
||||
# endif
|
||||
case boCrypt:
|
||||
return
|
||||
# ifdef PIP_CRYPT
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boIntrospection: return
|
||||
#ifdef PIP_INTROSPECTION
|
||||
# endif
|
||||
case boIntrospection:
|
||||
return
|
||||
# ifdef PIP_INTROSPECTION
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boFFTW: return
|
||||
#ifdef PIP_FFTW
|
||||
# endif
|
||||
case boFFTW:
|
||||
return
|
||||
# ifdef PIP_FFTW
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boCompress: return
|
||||
#ifdef PIP_COMPRESS
|
||||
# endif
|
||||
case boCompress:
|
||||
return
|
||||
# ifdef PIP_COMPRESS
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boOpenCL: return
|
||||
#ifdef PIP_OPENCL
|
||||
# endif
|
||||
case boOpenCL:
|
||||
return
|
||||
# ifdef PIP_OPENCL
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
case boCloud: return
|
||||
#ifdef PIP_CLOUD
|
||||
# endif
|
||||
case boCloud:
|
||||
return
|
||||
# ifdef PIP_CLOUD
|
||||
true;
|
||||
#else
|
||||
# else
|
||||
false;
|
||||
#endif
|
||||
# endif
|
||||
default: return false;
|
||||
}
|
||||
return false;
|
||||
@@ -362,7 +365,7 @@ PIStringList PIInit::buildOptions() {
|
||||
}
|
||||
|
||||
|
||||
void PIInit::setFileCharset(const char *charset) {
|
||||
void PIInit::setFileCharset(const char * charset) {
|
||||
if (file_charset) delete file_charset;
|
||||
file_charset = 0;
|
||||
if (charset) {
|
||||
@@ -375,14 +378,12 @@ void PIInit::setFileCharset(const char *charset) {
|
||||
|
||||
bool PIInit::fileExists(const PIString & p) {
|
||||
FILE * f = fopen(p.data(), "r");
|
||||
if (f == 0)
|
||||
return false;
|
||||
if (f == 0) return false;
|
||||
fclose(f);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
|
||||
int __PIInit_Initializer__::count_(0);
|
||||
PIInit * __PIInit_Initializer__::__instance__(0);
|
||||
|
||||
@@ -390,7 +391,7 @@ PIInit * __PIInit_Initializer__::__instance__(0);
|
||||
__PIInit_Initializer__::__PIInit_Initializer__() {
|
||||
count_++;
|
||||
if (count_ > 1) return;
|
||||
//piCout << "create PIInit";
|
||||
// piCout << "create PIInit";
|
||||
__instance__ = new PIInit();
|
||||
}
|
||||
|
||||
@@ -398,7 +399,7 @@ __PIInit_Initializer__::__PIInit_Initializer__() {
|
||||
__PIInit_Initializer__::~__PIInit_Initializer__() {
|
||||
count_--;
|
||||
if (count_ > 0) return;
|
||||
//piCout << "delete PIInit";
|
||||
// piCout << "delete PIInit";
|
||||
if (__instance__ != 0) {
|
||||
delete __instance__;
|
||||
__instance__ = 0;
|
||||
@@ -406,4 +407,3 @@ __PIInit_Initializer__::~__PIInit_Initializer__() {
|
||||
}
|
||||
|
||||
#endif // MICRO_PIP
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Library initialization
|
||||
* \~russian Инициализация библиотеки
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Initialization
|
||||
@@ -30,7 +30,7 @@
|
||||
|
||||
#ifndef MICRO_PIP
|
||||
|
||||
#include "piincludes.h"
|
||||
# include "piincludes.h"
|
||||
|
||||
|
||||
class PIFile;
|
||||
@@ -51,6 +51,7 @@ static __PIInit_Initializer__ __piinit_initializer__;
|
||||
class PIP_EXPORT PIInit {
|
||||
friend class __PIInit_Initializer__;
|
||||
friend class PIFile;
|
||||
|
||||
public:
|
||||
~PIInit();
|
||||
|
||||
@@ -67,7 +68,7 @@ public:
|
||||
boOpenCL /*! \~english OpenCL support \~russian Поддержка OpenCL */ = 0x100,
|
||||
boCloud /*! \~english PICloud transport support \~russian Поддержка облачного транспорта PICloud */ = 0x200,
|
||||
};
|
||||
static PIInit * instance() {return __PIInit_Initializer__::__instance__;}
|
||||
static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~english Returns if build option was enabled
|
||||
@@ -78,9 +79,10 @@ public:
|
||||
//! \~english Returns build options as stringlist
|
||||
//! \~russian Возвращает опции сборки как список строк
|
||||
static PIStringList buildOptions();
|
||||
|
||||
private:
|
||||
explicit PIInit();
|
||||
void setFileCharset(const char *charset);
|
||||
void setFileCharset(const char * charset);
|
||||
bool fileExists(const PIString & p);
|
||||
PRIVATE_DECLARATION(PIP_EXPORT)
|
||||
char * file_charset;
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Base types and functions
|
||||
* \~russian Базовые типы и методы
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Base types and functions
|
||||
@@ -34,40 +34,53 @@
|
||||
//! \~russian Вспомогательная структура для сохранения/извлечения произвольного блока данных в/из PIBinaryStream
|
||||
struct PIMemoryBlock {
|
||||
public:
|
||||
//! \~english Constructs data block
|
||||
//! \~russian Создает блок данных
|
||||
PIMemoryBlock(void * data_ = 0, int size_ = 0) {
|
||||
d = data_;
|
||||
s = size_;
|
||||
}
|
||||
|
||||
//! \~english Constructs data block
|
||||
//! \~russian Создает блок данных
|
||||
PIMemoryBlock(void * data_ = 0, int size_ = 0) {d = data_; s = size_;}
|
||||
PIMemoryBlock(const void * data_, const int size_) {
|
||||
d = const_cast<void *>(data_);
|
||||
s = size_;
|
||||
}
|
||||
|
||||
//! \~english Constructs data block
|
||||
//! \~russian Создает блок данных
|
||||
PIMemoryBlock(const void * data_, const int size_) {d = const_cast<void * >(data_); s = size_;}
|
||||
PIMemoryBlock(const PIMemoryBlock & o) {
|
||||
d = o.d;
|
||||
s = o.s;
|
||||
}
|
||||
|
||||
PIMemoryBlock(const PIMemoryBlock & o) {d = o.d; s = o.s;}
|
||||
|
||||
PIMemoryBlock & operator =(const PIMemoryBlock & o) {d = o.d; s = o.s; return *this;}
|
||||
PIMemoryBlock & operator=(const PIMemoryBlock & o) {
|
||||
d = o.d;
|
||||
s = o.s;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Pointer to data
|
||||
//! \~russian Указатель на данные
|
||||
void * data() {return d;}
|
||||
void * data() { return d; }
|
||||
|
||||
//! \~english Pointer to data
|
||||
//! \~russian Указатель на данные
|
||||
const void * data() const {return d;}
|
||||
const void * data() const { return d; }
|
||||
|
||||
//! \~english Size of data in bytes
|
||||
//! \~russian Размер данных в байтах
|
||||
int size() const {return s;}
|
||||
int size() const { return s; }
|
||||
|
||||
private:
|
||||
void * d;
|
||||
int s;
|
||||
|
||||
};
|
||||
|
||||
//! \~english Returns PIMemoryBlock from pointer to variable "ptr" with type "T"
|
||||
//! \~russian Возвращает PIMemoryBlock из указателя "ptr" типа "T"
|
||||
template<typename T>
|
||||
PIMemoryBlock createMemoryBlock(const T * ptr) {return PIMemoryBlock(ptr, sizeof(T));}
|
||||
PIMemoryBlock createMemoryBlock(const T * ptr) {
|
||||
return PIMemoryBlock(ptr, sizeof(T));
|
||||
}
|
||||
|
||||
#endif // PIMEMORYBLOCK_H
|
||||
|
||||
@@ -18,12 +18,13 @@
|
||||
*/
|
||||
|
||||
#include "piobject.h"
|
||||
#include "pithread.h"
|
||||
|
||||
#include "piconditionvar.h"
|
||||
#include "pithread.h"
|
||||
#ifndef MICRO_PIP
|
||||
# include "pisysteminfo.h"
|
||||
# include "pifile.h"
|
||||
# include "piiostream.h"
|
||||
# include "pisysteminfo.h"
|
||||
#endif
|
||||
|
||||
|
||||
@@ -111,8 +112,7 @@ PIObject::__MetaFunc::__MetaFunc() {
|
||||
|
||||
int PIObject::__MetaFunc::argumentsCount() const {
|
||||
for (int i = 0; i < __PIOBJECT_MAX_ARGS__; ++i)
|
||||
if (!types[i])
|
||||
return i;
|
||||
if (!types[i]) return i;
|
||||
return __PIOBJECT_MAX_ARGS__;
|
||||
}
|
||||
|
||||
@@ -129,9 +129,7 @@ PIString PIObject::__MetaFunc::arguments() const {
|
||||
|
||||
|
||||
PIString PIObject::__MetaFunc::fullFormat() const {
|
||||
PIString ret = PIStringAscii(type_ret) + " " +
|
||||
PIStringAscii(scope) + "::" +
|
||||
PIStringAscii(func_name) +"(";
|
||||
PIString ret = PIStringAscii(type_ret) + " " + PIStringAscii(scope) + "::" + PIStringAscii(func_name) + "(";
|
||||
for (int i = 0; i < __PIOBJECT_MAX_ARGS__; ++i) {
|
||||
if (!types[i]) break;
|
||||
if (i > 0) ret += ", ";
|
||||
@@ -156,22 +154,20 @@ void PIObject::__MetaFunc::__addArgument(const char * t, const char * n) {
|
||||
types_id[i] = PIObject::simplifyType(t, false).hash();
|
||||
break;
|
||||
}
|
||||
//PICout(PICoutManipulators::DefaultControls | PICoutManipulators::AddQuotes)
|
||||
// PICout(PICoutManipulators::DefaultControls | PICoutManipulators::AddQuotes)
|
||||
// << "__addArgument" << t << n << PIObject::simplifyType(t) << types_id.back();
|
||||
}
|
||||
|
||||
|
||||
bool PIObject::__MetaFunc::canConnectTo(const __MetaFunc & dst, int & args_count) const {
|
||||
for (int i = 0; i < __PIOBJECT_MAX_ARGS__; ++i) {
|
||||
//piCout << "canConnectTo" << i << types[i] << dst.types[i];
|
||||
// piCout << "canConnectTo" << i << types[i] << dst.types[i];
|
||||
args_count = i;
|
||||
if (!dst.types[i]) break;
|
||||
if (!types[i]) return false;
|
||||
if (types_id[i] != dst.types_id[i])
|
||||
return false;
|
||||
if (types_id[i] != dst.types_id[i]) return false;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -182,13 +178,13 @@ PIObject::PIObject(const PIString & name): _signature_(__PIOBJECT_SIGNATURE__),
|
||||
mutexObjects().lock();
|
||||
objects() << this;
|
||||
mutexObjects().unlock();
|
||||
//piCout << "new" << this;
|
||||
// piCout << "new" << this;
|
||||
}
|
||||
|
||||
|
||||
PIObject::~PIObject() {
|
||||
in_event_cnt = 0;
|
||||
//piCout << "delete" << this;
|
||||
// piCout << "delete" << this;
|
||||
mutexObjects().lock();
|
||||
objects().removeAll(this);
|
||||
mutexObjects().unlock();
|
||||
@@ -198,19 +194,16 @@ PIObject::~PIObject() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
bool PIObject::execute(const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
||||
if (method.isEmpty()) return false;
|
||||
if (!isPIObject()) {
|
||||
piCout << "Error: \"execute(" << method << ")\":" << (void*)this << "is not PIObject!";
|
||||
piCout << "Error: \"execute(" << method << ")\":" << (void *)this << "is not PIObject!";
|
||||
return false;
|
||||
}
|
||||
int ac = 0;
|
||||
__MetaFunc func;
|
||||
bool ok = findSuitableMethodV(method, vl.size_s(), ac, func);
|
||||
if (!ok)
|
||||
return false;
|
||||
if (!ok) return false;
|
||||
callAddrV(func.addrV, toThis(), ac, vl);
|
||||
return true;
|
||||
}
|
||||
@@ -218,18 +211,17 @@ bool PIObject::execute(const PIString & method, const PIVector<PIVariantSimple>
|
||||
|
||||
bool PIObject::executeQueued(PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
||||
if (!isPIObject()) {
|
||||
piCout << "Error: \"executeQueued(" << method << ")\": this(" << (void*)this << ") is not PIObject!";
|
||||
piCout << "Error: \"executeQueued(" << method << ")\": this(" << (void *)this << ") is not PIObject!";
|
||||
return false;
|
||||
}
|
||||
if (!performer->isPIObject()) {
|
||||
piCout << "Error: \"executeQueued(" << method << ")\": performer(" << (void*)performer << ") is not PIObject!";
|
||||
piCout << "Error: \"executeQueued(" << method << ")\": performer(" << (void *)performer << ") is not PIObject!";
|
||||
return false;
|
||||
}
|
||||
int ac = 0;
|
||||
__MetaFunc func;
|
||||
bool ok = findSuitableMethodV(method, vl.size_s(), ac, func);
|
||||
if (!ok)
|
||||
return false;
|
||||
if (!ok) return false;
|
||||
performer->postQueuedEvent(__QueuedEvent(func.addrV, toThis(), this, performer, vl));
|
||||
performer->proc_event_queue = true;
|
||||
return true;
|
||||
@@ -262,8 +254,7 @@ bool PIObject::isMethodEHContains(const PIString & name) const {
|
||||
PIMutexLocker ml(__meta_mutex());
|
||||
const __MetaData & ehd(__meta_data()[classNameID()]);
|
||||
for (auto eh = ehd.eh_func.begin(); eh != ehd.eh_func.end(); eh++) {
|
||||
if (eh.value().func_name_id == search_id)
|
||||
return true;
|
||||
if (eh.value().func_name_id == search_id) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
@@ -274,8 +265,7 @@ PIString PIObject::methodEHArguments(const PIString & name) const {
|
||||
PIMutexLocker ml(__meta_mutex());
|
||||
const __MetaData & ehd(__meta_data()[classNameID()]);
|
||||
for (auto eh = ehd.eh_func.begin(); eh != ehd.eh_func.end(); eh++) {
|
||||
if (eh.value().func_name_id == search_id)
|
||||
return eh.value().arguments();
|
||||
if (eh.value().func_name_id == search_id) return eh.value().arguments();
|
||||
}
|
||||
return PIString();
|
||||
}
|
||||
@@ -286,8 +276,7 @@ PIString PIObject::methodEHFullFormat(const PIString & name) const {
|
||||
PIMutexLocker ml(__meta_mutex());
|
||||
const __MetaData & ehd(__meta_data()[classNameID()]);
|
||||
for (auto eh = ehd.eh_func.begin(); eh != ehd.eh_func.end(); eh++) {
|
||||
if (eh.value().func_name_id == search_id)
|
||||
return eh.value().fullFormat();
|
||||
if (eh.value().func_name_id == search_id) return eh.value().fullFormat();
|
||||
}
|
||||
return PIString();
|
||||
}
|
||||
@@ -303,8 +292,7 @@ PIVector<PIObject::__MetaFunc> PIObject::findEH(const PIString & name) const {
|
||||
PIVector<__MetaFunc> ret;
|
||||
const __MetaData & ehd(__meta_data()[classNameID()]);
|
||||
for (auto eh = ehd.eh_func.begin(); eh != ehd.eh_func.end(); eh++) {
|
||||
if (eh.value().func_name_id == search_id)
|
||||
ret << eh.value();
|
||||
if (eh.value().func_name_id == search_id) ret << eh.value();
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -316,25 +304,38 @@ PIObject::__MetaFunc PIObject::methodEH(const void * addr) const {
|
||||
}
|
||||
|
||||
|
||||
PIObject::Connection PIObject::piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc) {
|
||||
//piCout << "piConnect ...";
|
||||
//piCout << "piConnect" << src << (void*)(dest) << sig;
|
||||
//piCout << "piConnect" << src->className() << "->" << ((PIObject*)dest)->className();
|
||||
PIObject::Connection PIObject::piConnect(PIObject * src,
|
||||
const PIString & sig,
|
||||
PIObject * dest_o,
|
||||
void * dest,
|
||||
void * ev_h,
|
||||
void * e_h,
|
||||
int args,
|
||||
const char * loc) {
|
||||
// piCout << "piConnect ...";
|
||||
// piCout << "piConnect" << src << (void*)(dest) << sig;
|
||||
// piCout << "piConnect" << src->className() << "->" << ((PIObject*)dest)->className();
|
||||
PIMutexLocker _ml(src->mutex_connect);
|
||||
PIMutexLocker _mld(dest_o->mutex_connect, src != dest_o);
|
||||
|
||||
Connection conn(ev_h, e_h, sig, src, dest_o, dest, args);
|
||||
src->connections << conn;
|
||||
//piCout << "piConnect" << ((PIObject*)dest) << sig << ((PIObject*)dest)->connectors.size_s() << "...";
|
||||
//piCout << "addConnector" << dest_o << src;
|
||||
// piCout << "piConnect" << ((PIObject*)dest) << sig << ((PIObject*)dest)->connectors.size_s() << "...";
|
||||
// piCout << "addConnector" << dest_o << src;
|
||||
dest_o->connectors << src;
|
||||
//piCout << "piConnect" << ((PIObject*)dest) << sig << ((PIObject*)dest)->connectors.size_s();
|
||||
//piCout << "piConnect ok";
|
||||
// piCout << "piConnect" << ((PIObject*)dest) << sig << ((PIObject*)dest)->connectors.size_s();
|
||||
// piCout << "piConnect ok";
|
||||
return conn;
|
||||
}
|
||||
|
||||
|
||||
PIObject::Connection PIObject::piConnectU(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, const PIString & hname, const char * loc, PIObject * performer) {
|
||||
PIObject::Connection PIObject::piConnectU(PIObject * src,
|
||||
const PIString & sig,
|
||||
PIObject * dest_o,
|
||||
void * dest,
|
||||
const PIString & hname,
|
||||
const char * loc,
|
||||
PIObject * performer) {
|
||||
if (src == 0 || dest_o == 0 || dest == 0) return Connection();
|
||||
if (!src->isPIObject()) {
|
||||
piCout << "[piConnectU] \"" << sig << "\" -> \"" << hname << "\" error: source object is not PIObject! (" << loc << ")";
|
||||
@@ -356,12 +357,12 @@ PIObject::Connection PIObject::piConnectU(PIObject * src, const PIString & sig,
|
||||
piCout << "[piConnectU] Error: can`t find handler \"" << hname << "\" in class \"" << dest_o->className() << "\"! (" << loc << ")";
|
||||
return Connection();
|
||||
}
|
||||
void * addr_src(0), * addr_dest(0);
|
||||
void *addr_src(0), *addr_dest(0);
|
||||
int args(0);
|
||||
bool que = (performer != 0);
|
||||
piForeachC (__MetaFunc & fs, m_src) {
|
||||
piForeachC(__MetaFunc & fs, m_src) {
|
||||
if (addr_src != 0) break;
|
||||
piForeachC (__MetaFunc & fd, m_dest) {
|
||||
piForeachC(__MetaFunc & fd, m_dest) {
|
||||
if (addr_src != 0) break;
|
||||
if (fs.canConnectTo(fd, args)) {
|
||||
addr_src = fs.addr;
|
||||
@@ -378,7 +379,7 @@ PIObject::Connection PIObject::piConnectU(PIObject * src, const PIString & sig,
|
||||
src->connections << conn;
|
||||
if (que) performer->proc_event_queue = true;
|
||||
dest_o->connectors << src;
|
||||
//piCout << cc << cq << _ol.size();//"connect" << src << "->" << dest_o << ", dest.connectors.size() =" << dest_o->connectors.size();
|
||||
// piCout << cc << cq << _ol.size();//"connect" << src << "->" << dest_o << ", dest.connectors.size() =" << dest_o->connectors.size();
|
||||
return conn;
|
||||
}
|
||||
|
||||
@@ -395,7 +396,7 @@ PIObject::Connection PIObject::piConnectLS(PIObject * src, const PIString & sig,
|
||||
}
|
||||
PIMutexLocker ml(__meta_mutex());
|
||||
PIMutexLocker mls(src->mutex_connect);
|
||||
//piCout << "locked";
|
||||
// piCout << "locked";
|
||||
PIVector<__MetaFunc> m_src = src->findEH(sig);
|
||||
if (m_src.isEmpty()) {
|
||||
piCout << "[piConnectLS] Error: can`t find event \"" << sig << "\" in class \"" << src->className() << "\"! (" << loc << ")";
|
||||
@@ -403,15 +404,16 @@ PIObject::Connection PIObject::piConnectLS(PIObject * src, const PIString & sig,
|
||||
return Connection();
|
||||
}
|
||||
if (m_src.size() != 1) {
|
||||
piCout << "[piConnectLS] Error: can`t connect overloaded event \"" << sig << "\" in class \"" << src->className() << "\"! (" << loc << ")";
|
||||
piCout << "[piConnectLS] Error: can`t connect overloaded event \"" << sig << "\" in class \"" << src->className() << "\"! (" << loc
|
||||
<< ")";
|
||||
delete f;
|
||||
return Connection();
|
||||
}
|
||||
PIObject::Connection conn(0, m_src[0].addr, sig, src);
|
||||
//piCout << "found";
|
||||
// piCout << "found";
|
||||
conn.functor = f;
|
||||
src->connections << conn;
|
||||
//piCout << "finished";
|
||||
// piCout << "finished";
|
||||
return conn;
|
||||
}
|
||||
|
||||
@@ -468,10 +470,10 @@ void PIObject::piDisconnect(PIObject * src, const PIString & sig) {
|
||||
|
||||
void PIObject::piDisconnectAll() {
|
||||
PIMutexLocker _ml(mutex_connect);
|
||||
PIVector<PIObject * > cv = connectors.toVector();
|
||||
// piCout << "disconnect connectors =" << connectors.size();
|
||||
piForeach (PIObject * o, cv) {
|
||||
// piCout << "disconnect"<< src << o;
|
||||
PIVector<PIObject *> cv = connectors.toVector();
|
||||
// piCout << "disconnect connectors =" << connectors.size();
|
||||
piForeach(PIObject * o, cv) {
|
||||
// piCout << "disconnect"<< src << o;
|
||||
if (!o || (o == this)) continue;
|
||||
if (!o->isPIObject()) continue;
|
||||
#if !defined(ANDROID) && !defined(MAC_OS) && !defined(MICRO_PIP)
|
||||
@@ -480,7 +482,7 @@ void PIObject::piDisconnectAll() {
|
||||
PIVector<Connection> & oc(o->connections);
|
||||
for (int i = 0; i < oc.size_s(); ++i) {
|
||||
if (oc[i].functor) continue;
|
||||
//piCout << " check" << (void*)(oc[i].dest_o) << "==" << (void*)(src);
|
||||
// piCout << " check" << (void*)(oc[i].dest_o) << "==" << (void*)(src);
|
||||
if (oc[i].dest_o == this) {
|
||||
oc[i].destroy();
|
||||
oc.remove(i);
|
||||
@@ -488,8 +490,8 @@ void PIObject::piDisconnectAll() {
|
||||
}
|
||||
}
|
||||
}
|
||||
// piCout << "disconnect connections =" << connections.size();
|
||||
piForeachC (PIObject::Connection & c, connections) {
|
||||
// piCout << "disconnect connections =" << connections.size();
|
||||
piForeachC(PIObject::Connection & c, connections) {
|
||||
if (c.functor) continue;
|
||||
if (!c.dest_o) continue;
|
||||
if (!c.dest_o->isPIObject()) continue;
|
||||
@@ -502,15 +504,14 @@ void PIObject::piDisconnectAll() {
|
||||
|
||||
|
||||
void PIObject::updateConnectors() {
|
||||
//piCout << "*** updateConnectors" << this;
|
||||
// piCout << "*** updateConnectors" << this;
|
||||
connectors.clear();
|
||||
PIMutexLocker _ml(mutexObjects());
|
||||
piForeach (PIObject * o, objects()) {
|
||||
piForeach(PIObject * o, objects()) {
|
||||
if (o == this) continue;
|
||||
PIVector<Connection> & oc(o->connections);
|
||||
piForeach (Connection & c, oc)
|
||||
if (c.dest == this)
|
||||
connectors << o;
|
||||
piForeach(Connection & c, oc)
|
||||
if (c.dest == this) connectors << o;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -523,8 +524,8 @@ void PIObject::postQueuedEvent(const PIObject::__QueuedEvent & e) {
|
||||
|
||||
|
||||
void * PIObject::toThis() const {
|
||||
//piCout << ptrOffset() << (void*)this << (void*)((char*)this - ptrOffset());
|
||||
return (void*)((char*)this - ptrOffset());
|
||||
// piCout << ptrOffset() << (void*)this << (void*)((char*)this - ptrOffset());
|
||||
return (void *)((char *)this - ptrOffset());
|
||||
}
|
||||
|
||||
|
||||
@@ -545,7 +546,7 @@ void PIObject::callQueuedEvents() {
|
||||
PIVector<__QueuedEvent> qe = events_queue;
|
||||
events_queue.clear();
|
||||
mutex_queue.unlock();
|
||||
piForeachC (__QueuedEvent & e, qe) {
|
||||
piForeachC(__QueuedEvent & e, qe) {
|
||||
if (e.dest_o->thread_safe_) e.dest_o->mutex_.lock();
|
||||
e.dest_o->emitter_ = e.src;
|
||||
callAddrV(e.slot, e.dest, e.values.size_s(), e.values);
|
||||
@@ -594,8 +595,8 @@ bool PIObject::findSuitableMethodV(const PIString & method, int args, int & ret_
|
||||
}
|
||||
|
||||
|
||||
PIVector<PIObject * > & PIObject::objects() {
|
||||
static PIVector<PIObject * > * ret = new PIVector<PIObject * >();
|
||||
PIVector<PIObject *> & PIObject::objects() {
|
||||
static PIVector<PIObject *> * ret = new PIVector<PIObject *>();
|
||||
return *ret;
|
||||
}
|
||||
|
||||
@@ -609,11 +610,16 @@ PIMutex & PIObject::mutexObjects() {
|
||||
void PIObject::callAddrV(void * slot, void * obj, int args, const PIVector<PIVariantSimple> & vl) {
|
||||
args = piMini(args, vl.size_s());
|
||||
switch (args) {
|
||||
case 0: ((void(*)(void *))slot)(obj); break;
|
||||
case 1: ((void(*)(void * , const PIVariantSimple & ))slot)(obj, vl[0]); break;
|
||||
case 2: ((void(*)(void * , const PIVariantSimple & , const PIVariantSimple & ))slot)(obj, vl[0], vl[1]); break;
|
||||
case 3: ((void(*)(void * , const PIVariantSimple & , const PIVariantSimple & , const PIVariantSimple & ))slot)(obj, vl[0], vl[1], vl[2]); break;
|
||||
case 4: ((void(*)(void * , const PIVariantSimple & , const PIVariantSimple & , const PIVariantSimple & , const PIVariantSimple & ))slot)(obj, vl[0], vl[1], vl[2], vl[3]); break;
|
||||
case 0: ((void (*)(void *))slot)(obj); break;
|
||||
case 1: ((void (*)(void *, const PIVariantSimple &))slot)(obj, vl[0]); break;
|
||||
case 2: ((void (*)(void *, const PIVariantSimple &, const PIVariantSimple &))slot)(obj, vl[0], vl[1]); break;
|
||||
case 3:
|
||||
((void (*)(void *, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &))slot)(obj, vl[0], vl[1], vl[2]);
|
||||
break;
|
||||
case 4:
|
||||
((void (*)(void *, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &))
|
||||
slot)(obj, vl[0], vl[1], vl[2], vl[3]);
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
@@ -625,7 +631,7 @@ PIString PIObject::simplifyType(const char * a, bool readable) {
|
||||
int white = -1;
|
||||
for (int i = 0; i < ret.size_s(); ++i) {
|
||||
bool iw = ret[i] == ' ' || ret[i] == '\t' || ret[i] == '\r' || ret[i] == '\n';
|
||||
//piCout << i << iw << white;
|
||||
// piCout << i << iw << white;
|
||||
if (white < 0) {
|
||||
if (iw) {
|
||||
white = i;
|
||||
@@ -636,7 +642,7 @@ PIString PIObject::simplifyType(const char * a, bool readable) {
|
||||
ret.replace(white, i - white, " ");
|
||||
i = white;
|
||||
white = -1;
|
||||
//piCout << i;
|
||||
// piCout << i;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -652,11 +658,9 @@ PIString PIObject::simplifyType(const char * a, bool readable) {
|
||||
ret.replaceAll("> ", '>');
|
||||
ret.replaceAll("& ", '&');
|
||||
ret.replaceAll("* ", '*');
|
||||
if (ret.startsWith("const ") && ret.endsWith("&"))
|
||||
ret.cutLeft(6).cutRight(1).trim();
|
||||
if (ret.startsWith("const ") && ret.endsWith("&")) ret.cutLeft(6).cutRight(1).trim();
|
||||
} else {
|
||||
if (ret.startsWith("const ") && ret.endsWith("&"))
|
||||
ret.cutLeft(6).cutRight(1).trim();
|
||||
if (ret.startsWith("const ") && ret.endsWith("&")) ret.cutLeft(6).cutRight(1).trim();
|
||||
ret.removeAll(' ').removeAll('\t').removeAll('\r').removeAll('\n');
|
||||
}
|
||||
return ret;
|
||||
@@ -670,49 +674,53 @@ bool PIObject::isPIObject(const PIObject * o) {
|
||||
|
||||
|
||||
void PIObject::dump(const PIString & line_prefix) const {
|
||||
//printf("dump %s \"%s\"\n", className(), name().data());
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << "class " << className() << " (" << (const void*)this << ", \"" << name() << "\") {";
|
||||
// printf("dump %s \"%s\"\n", className(), name().data());
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << "class " << className() << " (" << (const void *)this << ", \"" << name()
|
||||
<< "\") {";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " scope: " << scopeList().join(" -> ");
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " properties {";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " count: " << properties_.size_s();
|
||||
//printf("dump %d properties\n", properties_.size());
|
||||
// printf("dump %d properties\n", properties_.size());
|
||||
const char * o_name = "name";
|
||||
auto it = properties_.makeIterator();
|
||||
while (it.next()) {
|
||||
if (it.key() != piHashData((const uchar *)o_name, strlen(o_name)))
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << it.key() << ": " << it.value();
|
||||
}
|
||||
//printf("dump %d properties ok\n", properties_.size());
|
||||
// printf("dump %d properties ok\n", properties_.size());
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " }";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " methods {";
|
||||
const __MetaData & ehd(__meta_data()[classNameID()]);
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " count: " << ehd.eh_func.size_s();
|
||||
//printf("dump %d methods\n", ehd.eh_func.size());
|
||||
// printf("dump %d methods\n", ehd.eh_func.size());
|
||||
for (auto eh = ehd.eh_func.begin(); eh != ehd.eh_func.end(); eh++) {
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << eh.value().fullFormat();
|
||||
}
|
||||
//printf("dump %d methods ok\n", ehd.eh_func.size());
|
||||
// printf("dump %d methods ok\n", ehd.eh_func.size());
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " }";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " connections {";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " count: " << connections.size_s();
|
||||
//printf("dump %d connections\n",connections.size());
|
||||
for (const Connection & c : connections) {
|
||||
// printf("dump %d connections\n",connections.size());
|
||||
for (const Connection & c: connections) {
|
||||
PIObject * dst = c.dest_o;
|
||||
__MetaFunc ef = methodEH(c.signal);
|
||||
PIString src(c.event);
|
||||
if (ef.func_name)
|
||||
src = PIStringAscii(ef.func_name) + "(" + ef.arguments() + ")";
|
||||
if (ef.func_name) src = PIStringAscii(ef.func_name) + "(" + ef.arguments() + ")";
|
||||
if (dst) {
|
||||
__MetaFunc hf = dst->methodEH(c.slot);
|
||||
PIString hf_fn;
|
||||
if (!hf.func_name) hf_fn = "[BROKEN]";
|
||||
else hf_fn = PIStringAscii(hf.func_name) + "(" + hf.arguments() + ")";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << src << " -> " << dst->className() << " (" << c.dest << ", \"" << dst->name() << "\")::" << hf_fn;
|
||||
if (!hf.func_name)
|
||||
hf_fn = "[BROKEN]";
|
||||
else
|
||||
hf_fn = PIStringAscii(hf.func_name) + "(" + hf.arguments() + ")";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << src << " -> " << dst->className() << " (" << c.dest
|
||||
<< ", \"" << dst->name() << "\")::" << hf_fn;
|
||||
} else {
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << src << " -> " << "[lambda]";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " " << src << " -> "
|
||||
<< "[lambda]";
|
||||
}
|
||||
}
|
||||
//printf("dump %d connections ok\n",connections.size());
|
||||
// printf("dump %d connections ok\n",connections.size());
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << " }";
|
||||
PICout(PICoutManipulators::AddNewLine) << line_prefix << "}";
|
||||
}
|
||||
@@ -721,7 +729,7 @@ void PIObject::dump(const PIString & line_prefix) const {
|
||||
#ifndef MICRO_PIP
|
||||
void dumpApplication(bool with_objects) {
|
||||
PIMutexLocker _ml(PIObject::mutexObjects());
|
||||
//printf("dump application ...\n");
|
||||
// printf("dump application ...\n");
|
||||
PIDateTime cd = PIDateTime::current();
|
||||
PISystemInfo * pi = PISystemInfo::instance();
|
||||
PICout(PICoutManipulators::AddNewLine) << "application {";
|
||||
@@ -734,7 +742,8 @@ void dumpApplication(bool with_objects) {
|
||||
PICout(PICoutManipulators::AddNewLine) << " username: \"" << pi->user << "\"";
|
||||
PICout(PICoutManipulators::AddNewLine) << " exec command: \"" << pi->execCommand << "\"";
|
||||
PICout(PICoutManipulators::AddNewLine) << " started: " << pi->execDateTime.toString();
|
||||
PICout(PICoutManipulators::AddNewLine) << " uptime: " << PITime::fromSystemTime(cd.toSystemTime() - pi->execDateTime.toSystemTime()).toString();
|
||||
PICout(PICoutManipulators::AddNewLine) << " uptime: "
|
||||
<< PITime::fromSystemTime(cd.toSystemTime() - pi->execDateTime.toSystemTime()).toString();
|
||||
PICout(PICoutManipulators::AddNewLine) << " PIObjects {";
|
||||
PICout(PICoutManipulators::AddNewLine) << " count: " << PIObject::objects().size_s();
|
||||
if (with_objects) {
|
||||
@@ -743,7 +752,7 @@ void dumpApplication(bool with_objects) {
|
||||
}
|
||||
PICout(PICoutManipulators::AddNewLine) << " }";
|
||||
PICout(PICoutManipulators::AddNewLine) << "}";
|
||||
//printf("dump application done\n");
|
||||
// printf("dump application done\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -774,8 +783,6 @@ void PIObject::__MetaData::addScope(const char * s, uint shash) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
void PIObject::Connection::destroy() {
|
||||
if (functor) delete functor;
|
||||
functor = nullptr;
|
||||
@@ -804,11 +811,9 @@ bool PIObject::Connection::disconnect() {
|
||||
Connection & cc(src_o->connections[i]);
|
||||
if (cc.eventID == eventID) {
|
||||
if (dest_o && (cc.dest_o == dest_o)) {
|
||||
if (cc.slot == slot)
|
||||
found = true;
|
||||
if (cc.slot == slot) found = true;
|
||||
}
|
||||
if (functor && (cc.functor == functor))
|
||||
found = true;
|
||||
if (functor && (cc.functor == functor)) found = true;
|
||||
}
|
||||
if (found) {
|
||||
src_o->connections[i].destroy();
|
||||
@@ -818,44 +823,43 @@ bool PIObject::Connection::disconnect() {
|
||||
}
|
||||
}
|
||||
if (dest_o) {
|
||||
if (dest_o->isPIObject())
|
||||
dest_o->updateConnectors();
|
||||
if (dest_o->isPIObject()) dest_o->updateConnectors();
|
||||
}
|
||||
if (ndm) dest_o->mutex_connect.unlock();
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
PRIVATE_DEFINITION_START(PIObject::Deleter)
|
||||
PIThread thread;
|
||||
PIConditionVariable cond_var;
|
||||
PIVector<PIObject*> obj_queue;
|
||||
PIVector<PIObject *> obj_queue;
|
||||
PRIVATE_DEFINITION_END(PIObject::Deleter)
|
||||
|
||||
|
||||
PIObject::Deleter::Deleter() {
|
||||
//piCout << "Deleter start ...";
|
||||
PRIVATE->thread.setSlot([this](){
|
||||
PIVector<PIObject*> oq;
|
||||
// piCout << "Deleter start ...";
|
||||
PRIVATE->thread.setSlot([this]() {
|
||||
PIVector<PIObject *> oq;
|
||||
PRIVATE->thread.lock();
|
||||
if (PRIVATE->obj_queue.isEmpty()) PRIVATE->cond_var.wait(PRIVATE->thread.mutex());
|
||||
oq.swap(PRIVATE->obj_queue);
|
||||
PRIVATE->thread.unlock();
|
||||
for (PIObject * o : oq) deleteObject(o);
|
||||
for (PIObject * o: oq)
|
||||
deleteObject(o);
|
||||
});
|
||||
PRIVATE->thread.start();
|
||||
}
|
||||
|
||||
|
||||
PIObject::Deleter::~Deleter() {
|
||||
//piCout << "~Deleter ...";
|
||||
// piCout << "~Deleter ...";
|
||||
PRIVATE->thread.stop();
|
||||
PRIVATE->cond_var.notifyAll();
|
||||
PRIVATE->thread.waitForFinish();
|
||||
for (PIObject * o : PRIVATE->obj_queue) deleteObject(o);
|
||||
//piCout << "~Deleter ok";
|
||||
for (PIObject * o: PRIVATE->obj_queue)
|
||||
deleteObject(o);
|
||||
// piCout << "~Deleter ok";
|
||||
}
|
||||
|
||||
|
||||
@@ -867,24 +871,25 @@ PIObject::Deleter * PIObject::Deleter::instance() {
|
||||
|
||||
void PIObject::Deleter::post(PIObject * o) {
|
||||
if (!o->isPIObject()) return;
|
||||
//piCout << "[Deleter] post" << o << "...";
|
||||
// piCout << "[Deleter] post" << o << "...";
|
||||
PRIVATE->thread.lock();
|
||||
if (!PRIVATE->obj_queue.contains(o)) {
|
||||
PRIVATE->obj_queue << o;
|
||||
PRIVATE->cond_var.notifyAll();
|
||||
}
|
||||
PRIVATE->thread.unlock();
|
||||
//piCout << "[Deleter] post" << o << "done";
|
||||
// piCout << "[Deleter] post" << o << "done";
|
||||
}
|
||||
|
||||
|
||||
void PIObject::Deleter::deleteObject(PIObject * o) {
|
||||
//piCout << "[Deleter] delete" << (uintptr_t)o << "...";
|
||||
// piCout << "[Deleter] delete" << (uintptr_t)o << "...";
|
||||
if (o->isPIObject()) {
|
||||
//piCout << "[Deleter] delete" << (uintptr_t)o << "wait atomic ...";
|
||||
while (o->isInEvent()) piMinSleep();
|
||||
//piCout << "[Deleter] delete" << (uintptr_t)o << "wait atomic done";
|
||||
// piCout << "[Deleter] delete" << (uintptr_t)o << "wait atomic ...";
|
||||
while (o->isInEvent())
|
||||
piMinSleep();
|
||||
// piCout << "[Deleter] delete" << (uintptr_t)o << "wait atomic done";
|
||||
delete o;
|
||||
}
|
||||
//piCout << "[Deleter] delete" << (uintptr_t)o << "done";
|
||||
// piCout << "[Deleter] delete" << (uintptr_t)o << "done";
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english Base object
|
||||
* \~russian Базовый класс
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Object, base class of some PIP classes, provide EVENT -> EVENT_HANDLER mechanism
|
||||
@@ -27,12 +27,12 @@
|
||||
#define PIOBJECT_H
|
||||
|
||||
#include "piinit.h"
|
||||
#include "pimutex.h"
|
||||
#include "piobject_macros.h"
|
||||
#include "piqueue.h"
|
||||
#include "piset.h"
|
||||
#include "pivariant.h"
|
||||
#include "pivariantsimple.h"
|
||||
#include "pimutex.h"
|
||||
#include "piset.h"
|
||||
#include "piqueue.h"
|
||||
#include "piobject_macros.h"
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\brief
|
||||
@@ -46,6 +46,7 @@ class PIP_EXPORT PIObject {
|
||||
#endif
|
||||
typedef PIObject __PIObject__;
|
||||
typedef void __Parent__;
|
||||
|
||||
public:
|
||||
NO_COPY_CLASS(PIObject);
|
||||
|
||||
@@ -61,9 +62,14 @@ public:
|
||||
//! \~russian Вспомогательный класс для получения информации об успешности соединения и возможности его разрыва.
|
||||
class PIP_EXPORT Connection {
|
||||
friend class PIObject;
|
||||
Connection(void * sl, void * si, const PIString & e = PIString(),
|
||||
PIObject * s_o = nullptr, PIObject * d_o = nullptr,
|
||||
void * d = nullptr, int ac = 0, PIObject * p = nullptr) {
|
||||
Connection(void * sl,
|
||||
void * si,
|
||||
const PIString & e = PIString(),
|
||||
PIObject * s_o = nullptr,
|
||||
PIObject * d_o = nullptr,
|
||||
void * d = nullptr,
|
||||
int ac = 0,
|
||||
PIObject * p = nullptr) {
|
||||
slot = sl;
|
||||
signal = si;
|
||||
event = e;
|
||||
@@ -81,31 +87,31 @@ public:
|
||||
std::function<void()> * functor;
|
||||
PIString event;
|
||||
uint eventID;
|
||||
PIObject * src_o, * dest_o;
|
||||
PIObject *src_o, *dest_o;
|
||||
PIObject * performer;
|
||||
void * dest;
|
||||
int args_count;
|
||||
public:
|
||||
|
||||
public:
|
||||
//! \~english Contructs invalid %Connection
|
||||
//! \~russian Создает недействительный %Connection
|
||||
Connection();
|
||||
|
||||
//! \~english Returns if %Connection is valid
|
||||
//! \~russian Возвращает успешен ли %Connection
|
||||
bool isValid() const {return signal;}
|
||||
bool isValid() const { return signal; }
|
||||
|
||||
//! \~english Returns source object
|
||||
//! \~russian Возвращает объект-источник
|
||||
PIObject * sourceObject() const {return src_o;}
|
||||
PIObject * sourceObject() const { return src_o; }
|
||||
|
||||
//! \~english Returns destination object or "nullptr" if this is lambda connection
|
||||
//! \~russian Возвращает объект-приемник или "nullptr" если это соединение на лямбда-функцию
|
||||
PIObject * destinationObject() const {return dest_o;}
|
||||
PIObject * destinationObject() const { return dest_o; }
|
||||
|
||||
//! \~english Returns performer object or "nullptr" if this is non-queued connection
|
||||
//! \~russian Возвращает объект-исполнитель или "nullptr" если это соединение не отложенное
|
||||
PIObject * performerObject() const {return performer;}
|
||||
PIObject * performerObject() const { return performer; }
|
||||
|
||||
//! \~english Disconnect this %Connection, returns if operation successful
|
||||
//! \~russian Разрывает этот %Connection, возвращает успешен ли разрыв
|
||||
@@ -116,80 +122,155 @@ private:
|
||||
uint _signature_;
|
||||
|
||||
public:
|
||||
|
||||
//! \~english Returns object name
|
||||
//! \~russian Возвращает имя объекта
|
||||
PIString name() const {return property("name").toString();}
|
||||
PIString name() const { return property("name").toString(); }
|
||||
|
||||
//! \~english Returns object class name
|
||||
//! \~russian Возвращает имя класса объекта
|
||||
virtual const char * className() const {return "PIObject";}
|
||||
virtual const char * className() const { return "PIObject"; }
|
||||
|
||||
virtual uint classNameID() const {static uint ret = PIStringAscii("PIObject").hash(); return ret;}
|
||||
virtual uint classNameID() const {
|
||||
static uint ret = PIStringAscii("PIObject").hash();
|
||||
return ret;
|
||||
}
|
||||
|
||||
static const char * __classNameCC() {return "PIObject";}
|
||||
static uint __classNameIDS() {static uint ret = PIStringAscii("PIObject").hash(); return ret;}
|
||||
static const char * __classNameCC() { return "PIObject"; }
|
||||
static uint __classNameIDS() {
|
||||
static uint ret = PIStringAscii("PIObject").hash();
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns parent class name
|
||||
//! \~russian Возвращает имя родительского класса
|
||||
virtual const char * parentClassName() const {return "";}
|
||||
virtual const char * parentClassName() const { return ""; }
|
||||
|
||||
|
||||
//! \~english Return if \a piCoutObj of this object is active
|
||||
//! \~russian Возвращает включен ли вывод \a piCoutObj для этого объекта
|
||||
bool debug() const {return property("debug").toBool();}
|
||||
bool debug() const { return property("debug").toBool(); }
|
||||
|
||||
|
||||
//! \~english Set object name
|
||||
//! \~russian Устанавливает имя объекта
|
||||
void setName(const PIString & name) {setProperty("name", name);}
|
||||
void setName(const PIString & name) { setProperty("name", name); }
|
||||
|
||||
//! \~english Set object \a piCoutObj active
|
||||
//! \~russian Включает или отключает вывод \a piCoutObj для этого объекта
|
||||
void setDebug(bool debug) {setProperty("debug", debug);}
|
||||
void setDebug(bool debug) { setProperty("debug", debug); }
|
||||
|
||||
//! \~english Returns property with name "name"
|
||||
//! \~russian Возвращает свойство объекта по имени "name"
|
||||
PIVariant property(const char * name) const {return properties_.value(piHashData((const uchar *)name, strlen(name)));}
|
||||
PIVariant property(const char * name) const { return properties_.value(piHashData((const uchar *)name, strlen(name))); }
|
||||
|
||||
//! \~english Set property with name "name" to "value". If there is no such property in object it will be added
|
||||
//! \~russian Устанавливает у объекта свойство по имени "name" в "value". Если такого свойства нет, оно добавляется
|
||||
void setProperty(const char * name, const PIVariant & value) {properties_[piHashData((const uchar *)name, strlen(name))] = value; propertyChanged(name);}
|
||||
void setProperty(const char * name, const PIVariant & value) {
|
||||
properties_[piHashData((const uchar *)name, strlen(name))] = value;
|
||||
propertyChanged(name);
|
||||
}
|
||||
|
||||
//! \~english Returns if property with name "name" exists
|
||||
//! \~russian Возвращает присутствует ли свойство по имени "name"
|
||||
bool isPropertyExists(const char * name) const {return properties_.contains(piHashData((const uchar *)name, strlen(name)));}
|
||||
bool isPropertyExists(const char * name) const { return properties_.contains(piHashData((const uchar *)name, strlen(name))); }
|
||||
|
||||
void setThreadSafe(bool yes) {thread_safe_ = yes;}
|
||||
bool isThreadSafe() const {return thread_safe_;}
|
||||
void setThreadSafe(bool yes) { thread_safe_ = yes; }
|
||||
bool isThreadSafe() const { return thread_safe_; }
|
||||
|
||||
bool execute(const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||
bool execute(const PIString & method) {return execute(method, PIVector<PIVariantSimple>());}
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0) {return execute(method, PIVector<PIVariantSimple>() << v0);}
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {return execute(method, PIVector<PIVariantSimple>() << v0 << v1);}
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2);}
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) {return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);}
|
||||
bool execute(const PIString & method) { return execute(method, PIVector<PIVariantSimple>()); }
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0) { return execute(method, PIVector<PIVariantSimple>() << v0); }
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
bool execute(const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2,
|
||||
const PIVariantSimple & v3) {
|
||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||
bool executeQueued(PIObject * performer, const PIString & method) {return executeQueued(performer, method, PIVector<PIVariantSimple>());}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0) {return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0);}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1);}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) {return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);}
|
||||
bool executeQueued(PIObject * performer, const PIString & method) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>());
|
||||
}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
bool executeQueued(PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
bool executeQueued(PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2,
|
||||
const PIVariantSimple & v3) {
|
||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVector<PIVariantSimple> & vl) {return o->execute(method, vl);}
|
||||
static bool execute(PIObject * o, const PIString & method) {return execute(o, method, PIVector<PIVariantSimple>());}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0) {return execute(o, method, PIVector<PIVariantSimple>() << v0);}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1);}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) {return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVector<PIVariantSimple> & vl) { return o->execute(method, vl); }
|
||||
static bool execute(PIObject * o, const PIString & method) { return execute(o, method, PIVector<PIVariantSimple>()); }
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
static bool
|
||||
execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
static bool execute(PIObject * o,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2,
|
||||
const PIVariantSimple & v3) {
|
||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {return o->executeQueued(performer, method, vl);}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method) {return executeQueued(o, performer, method, PIVector<PIVariantSimple>());}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0) {return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0);}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1);}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) {return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
||||
return o->executeQueued(performer, method, vl);
|
||||
}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>());
|
||||
}
|
||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0);
|
||||
}
|
||||
static bool
|
||||
executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||
}
|
||||
static bool executeQueued(PIObject * o,
|
||||
PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||
}
|
||||
static bool executeQueued(PIObject * o,
|
||||
PIObject * performer,
|
||||
const PIString & method,
|
||||
const PIVariantSimple & v0,
|
||||
const PIVariantSimple & v1,
|
||||
const PIVariantSimple & v2,
|
||||
const PIVariantSimple & v3) {
|
||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||
}
|
||||
|
||||
void dump(const PIString & line_prefix = PIString()) const;
|
||||
|
||||
@@ -205,29 +286,37 @@ public:
|
||||
PIString methodEHFromAddr(const void * addr) const;
|
||||
|
||||
// / Direct connect
|
||||
static PIObject::Connection piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc);
|
||||
static PIObject::Connection piConnectU(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, const PIString & hname, const char * loc, PIObject * performer = 0);
|
||||
static PIObject::Connection
|
||||
piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc);
|
||||
static PIObject::Connection piConnectU(PIObject * src,
|
||||
const PIString & sig,
|
||||
PIObject * dest_o,
|
||||
void * dest,
|
||||
const PIString & hname,
|
||||
const char * loc,
|
||||
PIObject * performer = 0);
|
||||
static PIObject::Connection piConnectLS(PIObject * src, const PIString & sig, std::function<void()> * f, const char * loc);
|
||||
template <typename PIINPUT, typename... PITYPES>
|
||||
static std::function<void()> * __newFunctor(void(*stat_handler)(void*,PITYPES...), PIINPUT functor) {
|
||||
return (std::function<void()>*)(new std::function<void(PITYPES...)>(functor));
|
||||
template<typename PIINPUT, typename... PITYPES>
|
||||
static std::function<void()> * __newFunctor(void (*stat_handler)(void *, PITYPES...), PIINPUT functor) {
|
||||
return (std::function<void()> *)(new std::function<void(PITYPES...)>(functor));
|
||||
}
|
||||
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest" and handler "ev_h"
|
||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest" и обработчику "ev_h"
|
||||
void piDisconnect(const PIString & sig, PIObject * dest, void * ev_h) {piDisconnect(this, sig, dest, ev_h);}
|
||||
void piDisconnect(const PIString & sig, PIObject * dest, void * ev_h) { piDisconnect(this, sig, dest, ev_h); }
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest"
|
||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest"
|
||||
void piDisconnect(const PIString & sig, PIObject * dest) {piDisconnect(this, sig, dest);}
|
||||
void piDisconnect(const PIString & sig, PIObject * dest) { piDisconnect(this, sig, dest); }
|
||||
|
||||
//! \~english Disconnect object from all connections with event name "sig"
|
||||
//! \~russian Разрывает все соединения от события "sig"
|
||||
void piDisconnect(const PIString & sig) {piDisconnect(this, sig);}
|
||||
void piDisconnect(const PIString & sig) { piDisconnect(this, sig); }
|
||||
|
||||
|
||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest" and handler "ev_h"
|
||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest" and handler
|
||||
//! "ev_h"
|
||||
//! \~russian Разрывает все соединения от события "sig" объекта "src" к объекту "dest" и обработчику "ev_h"
|
||||
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest, void * ev_h);
|
||||
|
||||
@@ -255,7 +344,7 @@ public:
|
||||
i.dest_o->eventBegin();
|
||||
sender->eventBegin();
|
||||
i.dest_o->emitter_ = sender;
|
||||
((void( *)(void * ))i.slot)(i.dest);
|
||||
((void (*)(void *))i.slot)(i.dest);
|
||||
sender->eventEnd();
|
||||
if (i.dest_o->isPIObject()) {
|
||||
i.dest_o->emitter_ = 0;
|
||||
@@ -268,13 +357,13 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T0>
|
||||
template<typename T0>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
Connection i(sender->connections[j]);
|
||||
if (i.eventID != eventID) continue;
|
||||
if (i.functor) {
|
||||
(*((std::function<void(T0)>*)i.functor))(v0);
|
||||
(*((std::function<void(T0)> *)i.functor))(v0);
|
||||
} else {
|
||||
if (i.performer) {
|
||||
PIVector<PIVariantSimple> vl;
|
||||
@@ -286,8 +375,10 @@ public:
|
||||
i.dest_o->eventBegin();
|
||||
sender->eventBegin();
|
||||
i.dest_o->emitter_ = sender;
|
||||
if (i.args_count == 0) ((void(*)(void *))i.slot)(i.dest);
|
||||
else ((void(*)(void * , T0))i.slot)(i.dest, v0);
|
||||
if (i.args_count == 0)
|
||||
((void (*)(void *))i.slot)(i.dest);
|
||||
else
|
||||
((void (*)(void *, T0))i.slot)(i.dest, v0);
|
||||
sender->eventEnd();
|
||||
if (i.dest_o->isPIObject()) {
|
||||
i.dest_o->emitter_ = 0;
|
||||
@@ -299,13 +390,13 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
template <typename T0, typename T1>
|
||||
template<typename T0, typename T1>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
Connection i(sender->connections[j]);
|
||||
if (i.eventID != eventID) continue;
|
||||
if (i.functor) {
|
||||
(*((std::function<void(T0, T1)>*)i.functor))(v0, v1);
|
||||
(*((std::function<void(T0, T1)> *)i.functor))(v0, v1);
|
||||
} else {
|
||||
if (i.performer) {
|
||||
PIVector<PIVariantSimple> vl;
|
||||
@@ -319,9 +410,9 @@ public:
|
||||
sender->eventBegin();
|
||||
i.dest_o->emitter_ = sender;
|
||||
switch (i.args_count) {
|
||||
case 0: ((void(*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void(*)(void * , T0))i.slot)(i.dest, v0); break;
|
||||
default: ((void(*)(void * , T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
case 0: ((void (*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void (*)(void *, T0))i.slot)(i.dest, v0); break;
|
||||
default: ((void (*)(void *, T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
}
|
||||
sender->eventEnd();
|
||||
if (i.dest_o->isPIObject()) {
|
||||
@@ -334,13 +425,13 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
template <typename T0, typename T1, typename T2>
|
||||
template<typename T0, typename T1, typename T2>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1(), const T2 & v2 = T2()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
Connection i(sender->connections[j]);
|
||||
if (i.eventID != eventID) continue;
|
||||
if (i.functor) {
|
||||
(*((std::function<void(T0, T1, T2)>*)i.functor))(v0, v1, v2);
|
||||
(*((std::function<void(T0, T1, T2)> *)i.functor))(v0, v1, v2);
|
||||
} else {
|
||||
if (i.performer) {
|
||||
PIVector<PIVariantSimple> vl;
|
||||
@@ -355,10 +446,10 @@ public:
|
||||
sender->eventBegin();
|
||||
i.dest_o->emitter_ = sender;
|
||||
switch (i.args_count) {
|
||||
case 0: ((void(*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void(*)(void * , T0))i.slot)(i.dest, v0); break;
|
||||
case 2: ((void(*)(void * , T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
default: ((void(*)(void * , T0, T1, T2))i.slot)(i.dest, v0, v1, v2); break;
|
||||
case 0: ((void (*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void (*)(void *, T0))i.slot)(i.dest, v0); break;
|
||||
case 2: ((void (*)(void *, T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
default: ((void (*)(void *, T0, T1, T2))i.slot)(i.dest, v0, v1, v2); break;
|
||||
}
|
||||
sender->eventEnd();
|
||||
if (i.dest_o->isPIObject()) {
|
||||
@@ -371,13 +462,18 @@ public:
|
||||
if (!sender->isPIObject()) break;
|
||||
}
|
||||
}
|
||||
template <typename T0, typename T1, typename T2, typename T3>
|
||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1(), const T2 & v2 = T2(), const T3 & v3 = T3()) {
|
||||
template<typename T0, typename T1, typename T2, typename T3>
|
||||
static void raiseEvent(PIObject * sender,
|
||||
const uint eventID,
|
||||
const T0 & v0 = T0(),
|
||||
const T1 & v1 = T1(),
|
||||
const T2 & v2 = T2(),
|
||||
const T3 & v3 = T3()) {
|
||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||
Connection i(sender->connections[j]);
|
||||
if (i.eventID != eventID) continue;
|
||||
if (i.functor) {
|
||||
(*((std::function<void(T0, T1, T2, T3)>*)i.functor))(v0, v1, v2, v3);
|
||||
(*((std::function<void(T0, T1, T2, T3)> *)i.functor))(v0, v1, v2, v3);
|
||||
} else {
|
||||
if (i.performer) {
|
||||
PIVector<PIVariantSimple> vl;
|
||||
@@ -393,11 +489,11 @@ public:
|
||||
sender->eventBegin();
|
||||
i.dest_o->emitter_ = sender;
|
||||
switch (i.args_count) {
|
||||
case 0: ((void(*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void(*)(void * , T0))i.slot)(i.dest, v0); break;
|
||||
case 2: ((void(*)(void * , T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
case 3: ((void(*)(void * , T0, T1, T2))i.slot)(i.dest, v0, v1, v2); break;
|
||||
default: ((void(*)(void * , T0, T1, T2, T3))i.slot)(i.dest, v0, v1, v2, v3); break;
|
||||
case 0: ((void (*)(void *))i.slot)(i.dest); break;
|
||||
case 1: ((void (*)(void *, T0))i.slot)(i.dest, v0); break;
|
||||
case 2: ((void (*)(void *, T0, T1))i.slot)(i.dest, v0, v1); break;
|
||||
case 3: ((void (*)(void *, T0, T1, T2))i.slot)(i.dest, v0, v1, v2); break;
|
||||
default: ((void (*)(void *, T0, T1, T2, T3))i.slot)(i.dest, v0, v1, v2, v3); break;
|
||||
}
|
||||
sender->eventEnd();
|
||||
if (i.dest_o->isPIObject()) {
|
||||
@@ -414,7 +510,7 @@ public:
|
||||
//! Returns PIObject* with name "name" or 0, if there is no object found
|
||||
static PIObject * findByName(const PIString & name) {
|
||||
PIMutexLocker _ml(mutexObjects());
|
||||
piForeach (PIObject * i, PIObject::objects()) {
|
||||
piForeach(PIObject * i, PIObject::objects()) {
|
||||
if (i->name() != name) continue;
|
||||
return i;
|
||||
}
|
||||
@@ -423,7 +519,7 @@ public:
|
||||
|
||||
//! \~english Returns if this is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли это %PIObject (проверяет подпись)
|
||||
bool isPIObject() const {return isPIObject(this);}
|
||||
bool isPIObject() const { return isPIObject(this); }
|
||||
|
||||
//! \~english Returns if this is valid %PIObject subclass "T" (check signature and classname)
|
||||
//! \~russian Возвращает действительный ли это наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
||||
@@ -435,29 +531,34 @@ public:
|
||||
}
|
||||
|
||||
//! \~english Returns cast to T if this is valid subclass "T" (check by \a isTypeOf()) or "nullptr"
|
||||
//! \~russian Возвращает преобразование к типу T если это действительный наследник типа "T" (проверяет через \a isTypeOf()), или "nullptr"
|
||||
//! \~russian Возвращает преобразование к типу T если это действительный наследник типа "T" (проверяет через \a isTypeOf()), или
|
||||
//! "nullptr"
|
||||
template<typename T>
|
||||
T * cast() const {
|
||||
if (!isTypeOf<T>()) return (T*)nullptr;
|
||||
return (T*)this;
|
||||
if (!isTypeOf<T>()) return (T *)nullptr;
|
||||
return (T *)this;
|
||||
}
|
||||
|
||||
//! \~english Returns if "o" is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли "o" %PIObject (проверяет подпись)
|
||||
static bool isPIObject(const PIObject * o);
|
||||
static bool isPIObject(const void * o) {return isPIObject((PIObject*)o);}
|
||||
static bool isPIObject(const void * o) { return isPIObject((PIObject *)o); }
|
||||
|
||||
//! \~english Returns if "o" is valid %PIObject subclass "T" (check signature and classname)
|
||||
//! \~russian Возвращает действительный ли "o" наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
||||
template<typename T>
|
||||
static bool isTypeOf(const PIObject * o) {return o->isTypeOf<T>();}
|
||||
static bool isTypeOf(const PIObject * o) {
|
||||
return o->isTypeOf<T>();
|
||||
}
|
||||
template<typename T>
|
||||
static bool isTypeOf(const void * o) {return isTypeOf<T>((PIObject*)o);}
|
||||
static bool isTypeOf(const void * o) {
|
||||
return isTypeOf<T>((PIObject *)o);
|
||||
}
|
||||
static PIString simplifyType(const char * a, bool readable = true);
|
||||
|
||||
struct PIP_EXPORT __MetaFunc {
|
||||
__MetaFunc();
|
||||
bool isNull() const {return addr == nullptr;}
|
||||
bool isNull() const { return addr == nullptr; }
|
||||
int argumentsCount() const;
|
||||
PIString arguments() const;
|
||||
PIString fullFormat() const;
|
||||
@@ -476,14 +577,17 @@ public:
|
||||
};
|
||||
|
||||
struct PIP_EXPORT __MetaData {
|
||||
__MetaData() {scope_list << "PIObject"; scope_id << PIStringAscii("PIObject").hash();}
|
||||
__MetaData() {
|
||||
scope_list << "PIObject";
|
||||
scope_id << PIStringAscii("PIObject").hash();
|
||||
}
|
||||
void addScope(const char * s, uint shash);
|
||||
PIVector<const char *> scope_list;
|
||||
PISet<uint> scope_id;
|
||||
PISet<const void * > eh_set;
|
||||
PIMap<const void * , __MetaFunc> eh_func;
|
||||
PISet<const void *> eh_set;
|
||||
PIMap<const void *, __MetaFunc> eh_func;
|
||||
};
|
||||
typedef PIPair<const void * , __MetaFunc> __EHPair;
|
||||
typedef PIPair<const void *, __MetaFunc> __EHPair;
|
||||
|
||||
//! \~english Execute all posted events from CONNECTU_QUEUED connections
|
||||
//! \~russian Выполнить все отложенные события от CONNECTU_QUEUED соединений
|
||||
@@ -497,7 +601,10 @@ public:
|
||||
//! \brief Если было хотя бы одно CONNECTU_QUEUED соединение с исполнителем this, то выполнить события
|
||||
//! \details Этот метод более оптимален, чем \a callQueuedEvents(), для объектов, которые не были в роли
|
||||
//! \"performer\" в макросе CONNECTU_QUEUED
|
||||
bool maybeCallQueuedEvents() {if (proc_event_queue) callQueuedEvents(); return proc_event_queue;}
|
||||
bool maybeCallQueuedEvents() {
|
||||
if (proc_event_queue) callQueuedEvents();
|
||||
return proc_event_queue;
|
||||
}
|
||||
|
||||
//! \~english Mark object to delete
|
||||
//! \~russian Пометить объект на удаление
|
||||
@@ -507,10 +614,9 @@ public:
|
||||
static PIMap<uint, __MetaData> & __meta_data(); // [hash(classname)]=__MetaData
|
||||
|
||||
protected:
|
||||
|
||||
//! \~english Returns %PIObject* which has raised an event. This value is correct only in definition of some event handler
|
||||
//! \~russian Возвращает %PIObject* который вызвал это событие. Значение допустимо только из методов обработчиков событий
|
||||
PIObject * emitter() const {return emitter_;}
|
||||
PIObject * emitter() const { return emitter_; }
|
||||
|
||||
//! \~english Virtual function executes after property with name "name" has been changed
|
||||
//! \~russian Виртуальная функция, вызывается после изменения любого свойства.
|
||||
@@ -518,8 +624,8 @@ protected:
|
||||
|
||||
EVENT1(deleted, PIObject *, o);
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void deleted(PIObject * o)
|
||||
//! \brief
|
||||
@@ -533,12 +639,15 @@ protected:
|
||||
//! Это событие вызывается из деструктора, поэтому используйте
|
||||
//! только численное значение "o", не надо кастовать его в другие типы!
|
||||
|
||||
//! \}
|
||||
//! \}
|
||||
|
||||
private:
|
||||
|
||||
struct __QueuedEvent {
|
||||
__QueuedEvent(void * sl = 0, void * d = 0, PIObject * d_o = 0, PIObject * s = 0, const PIVector<PIVariantSimple> & v = PIVector<PIVariantSimple>()) {
|
||||
__QueuedEvent(void * sl = 0,
|
||||
void * d = 0,
|
||||
PIObject * d_o = 0,
|
||||
PIObject * s = 0,
|
||||
const PIVector<PIVariantSimple> & v = PIVector<PIVariantSimple>()) {
|
||||
slot = sl;
|
||||
dest = d;
|
||||
dest_o = d_o;
|
||||
@@ -558,6 +667,7 @@ private:
|
||||
~Deleter();
|
||||
static Deleter * instance();
|
||||
void post(PIObject * o);
|
||||
|
||||
private:
|
||||
void deleteObject(PIObject * o);
|
||||
PRIVATE_DECLARATION(PIP_EXPORT)
|
||||
@@ -570,26 +680,25 @@ private:
|
||||
void piDisconnectAll();
|
||||
|
||||
void postQueuedEvent(const __QueuedEvent & e);
|
||||
void eventBegin() {in_event_cnt++;}
|
||||
void eventEnd () {in_event_cnt--;}
|
||||
bool isInEvent() const {return in_event_cnt > 0;}
|
||||
void eventBegin() { in_event_cnt++; }
|
||||
void eventEnd() { in_event_cnt--; }
|
||||
bool isInEvent() const { return in_event_cnt > 0; }
|
||||
void * toThis() const;
|
||||
virtual int ptrOffset() const {return 0;}
|
||||
virtual int ptrOffset() const { return 0; }
|
||||
|
||||
static PIVector<PIObject * > & objects();
|
||||
static PIVector<PIObject *> & objects();
|
||||
static PIMutex & mutexObjects();
|
||||
static void callAddrV(void * slot, void * obj, int args, const PIVector<PIVariantSimple> & vl);
|
||||
|
||||
|
||||
PIVector<Connection> connections;
|
||||
PIMap<uint, PIVariant> properties_;
|
||||
PISet<PIObject * > connectors;
|
||||
PISet<PIObject *> connectors;
|
||||
PIVector<__QueuedEvent> events_queue;
|
||||
PIMutex mutex_, mutex_connect, mutex_queue;
|
||||
PIObject * emitter_;
|
||||
bool thread_safe_, proc_event_queue;
|
||||
std::atomic_int in_event_cnt;
|
||||
|
||||
};
|
||||
|
||||
#ifndef MICRO_PIP
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english PIObject macros
|
||||
* \~russian Макросы PIObject
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Macros for PIObject
|
||||
@@ -33,133 +33,141 @@
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER and correct piCoutObj output
|
||||
//! \~russian Необходимо использовать этот макрос после объявления класса для использования событийной системы и корректного вывода piCoutObj
|
||||
#define PIOBJECT(name)
|
||||
//! \~russian Необходимо использовать этот макрос после объявления класса для использования событийной системы и корректного вывода
|
||||
//! piCoutObj
|
||||
# define PIOBJECT(name)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER of parent class, and \a scopeList()
|
||||
//! \~russian
|
||||
#define PIOBJECT_SUBCLASS(name, parent)
|
||||
# define PIOBJECT_SUBCLASS(name, parent)
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name()
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name()
|
||||
#define EVENT_HANDLER0(ret, name) ret name()
|
||||
# define EVENT_HANDLER0(ret, name) ret name()
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0)
|
||||
#define EVENT_HANDLER1(ret, name, type0, var0) ret name(type0 var0)
|
||||
# define EVENT_HANDLER1(ret, name, type0, var0) ret name(type0 var0)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1)
|
||||
#define EVENT_HANDLER2(ret, name, type0, var0, type1, var1) ret name(type0 var0, type1 var1)
|
||||
# define EVENT_HANDLER2(ret, name, type0, var0, type1, var1) ret name(type0 var0, type1 var1)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
||||
#define EVENT_HANDLER3(ret, name, type0, var0, type1, var1, type2, var2) ret name(type0 var0, type1 var1, type2 var2)
|
||||
# define EVENT_HANDLER3(ret, name, type0, var0, type1, var1, type2, var2) ret name(type0 var0, type1 var1, type2 var2)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
#define EVENT_HANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2,
|
||||
//! type3 var3)
|
||||
# define EVENT_HANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||
ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Synonym of EVENT_HANDLER0
|
||||
//! \~russian Аналог EVENT_HANDLER0
|
||||
#define EVENT_HANDLER EVENT_HANDLER0
|
||||
# define EVENT_HANDLER EVENT_HANDLER0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name()
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name()
|
||||
#define EVENT_VHANDLER0(ret, name) virtual ret name()
|
||||
# define EVENT_VHANDLER0(ret, name) virtual ret name()
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0)
|
||||
#define EVENT_VHANDLER1(ret, name, type0, var0) virtual ret name(type0 var0)
|
||||
# define EVENT_VHANDLER1(ret, name, type0, var0) virtual ret name(type0 var0)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1 var1)
|
||||
#define EVENT_VHANDLER2(ret, name, type0, var0, type1, var1) virtual ret name(type0 var0, type1 var1)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1)
|
||||
# define EVENT_VHANDLER2(ret, name, type0, var0, type1, var1) virtual ret name(type0 var0, type1 var1)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
#define EVENT_VHANDLER3(ret, name, type0, var0, type1, var1, type2, var2) virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1, type2 var2)
|
||||
# define EVENT_VHANDLER3(ret, name, type0, var0, type1, var1, type2, var2) virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
#define EVENT_VHANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2,
|
||||
//! type3 var3)
|
||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
||||
//! var1, type2 var2, type3 var3)
|
||||
# define EVENT_VHANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||
virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Synonym of EVENT_VHANDLER0
|
||||
//! \~russian Аналог EVENT_VHANDLER0
|
||||
#define EVENT_VHANDLER EVENT_VHANDLER0
|
||||
# define EVENT_VHANDLER EVENT_VHANDLER0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name();
|
||||
//! \~russian Объявляет событие с именем \"name\", void name();
|
||||
#define EVENT0(name) void name();
|
||||
# define EVENT0(name) void name();
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0);
|
||||
#define EVENT1(name, type0, var0) void name(type0 var0);
|
||||
# define EVENT1(name, type0, var0) void name(type0 var0);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1);
|
||||
#define EVENT2(name, type0, var0, type1, var1) void name(type0 var0, type1 var1);
|
||||
# define EVENT2(name, type0, var0, type1, var1) void name(type0 var0, type1 var1);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2);
|
||||
#define EVENT3(name, type0, var0, type1, var1, type2, var2) void name(type0 var0, type1 var1, type2 var2);
|
||||
# define EVENT3(name, type0, var0, type1, var1, type2, var2) void name(type0 var0, type1 var1, type2 var2);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
#define EVENT4(name, type0, var0, type1, var1, type2, var2, type3, var3) void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
# define EVENT4(name, type0, var0, type1, var1, type2, var2, type3, var3) void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Synonym of EVENT0
|
||||
//! \~russian Аналог EVENT0
|
||||
#define EVENT EVENT0
|
||||
# define EVENT EVENT0
|
||||
|
||||
|
||||
#define RAISE_EVENT0(src, event)
|
||||
#define RAISE_EVENT1(src, event, v0)
|
||||
#define RAISE_EVENT2(src, event, v0, v1)
|
||||
#define RAISE_EVENT3(src, event, v0, v1, v2)
|
||||
#define RAISE_EVENT4(src, event, v0, v1, v2, v3)
|
||||
#define RAISE_EVENT RAISE_EVENT0
|
||||
# define RAISE_EVENT0(src, event)
|
||||
# define RAISE_EVENT1(src, event, v0)
|
||||
# define RAISE_EVENT2(src, event, v0, v1)
|
||||
# define RAISE_EVENT3(src, event, v0, v1, v2)
|
||||
# define RAISE_EVENT4(src, event, v0, v1, v2, v3)
|
||||
# define RAISE_EVENT RAISE_EVENT0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -173,7 +181,7 @@
|
||||
//! \~russian
|
||||
//! \"handler\" может принимать не все аргументы от \"event\".
|
||||
//! Возвращает \a PIObject::Connection
|
||||
#define CONNECTU(src, event, dest, handler)
|
||||
# define CONNECTU(src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
@@ -192,7 +200,7 @@
|
||||
//! Все типы аргументов должны быть зарегистрированы с помощью макроса \a REGISTER_VARIANT(),
|
||||
//! однако многие стандартные и PIP типы уже там.
|
||||
//! Возвращает \a PIObject::Connection
|
||||
#define CONNECTU_QUEUED(src, event, dest, handler, performer)
|
||||
# define CONNECTU_QUEUED(src, event, dest, handler, performer)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
@@ -207,62 +215,72 @@
|
||||
//! \"event\" и \"functor\" должны иметь одинаковые аргументы.
|
||||
//! В случае сложной лямбда-функции оберните её ().
|
||||
//! Возвращает \a PIObject::Connection
|
||||
#define CONNECTL(src, event, functor)
|
||||
# define CONNECTL(src, event, functor)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
#define CONNECT0(ret, src, event, dest, handler)
|
||||
# define CONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
#define CONNECT1(ret, type0, src, event, dest, handler)
|
||||
# define CONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
#define CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
# define CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
#define CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
# define CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with check of event and handler exists.
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
||||
//! check of event and handler exists.
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" с проверкой наличия события и обработчика.
|
||||
//! \~\details
|
||||
//! Returns PIObject::Connection
|
||||
#define CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
# define CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
@@ -271,7 +289,7 @@
|
||||
//! \~\brief
|
||||
//! \~english Synonym of \a CONNECT0
|
||||
//! \~russian Аналог \a CONNECT0
|
||||
#define CONNECT CONNECT0
|
||||
# define CONNECT CONNECT0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
@@ -279,45 +297,55 @@
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" без проверки наличия события и обработчика.
|
||||
#define WEAK_CONNECT0(ret, src, event, dest, handler)
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
# define WEAK_CONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" без проверки наличия события и обработчика.
|
||||
#define WEAK_CONNECT1(ret, type0, src, event, dest, handler)
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
# define WEAK_CONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" без проверки наличия события и обработчика.
|
||||
#define WEAK_CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
# define WEAK_CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" без проверки наличия события и обработчика.
|
||||
#define WEAK_CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
# define WEAK_CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
//! \~english Use \a CONNECTU() instead
|
||||
//! \~russian Используйте \a CONNECTU()
|
||||
//! \~\brief
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта \"dest\" без проверки наличия события и обработчика.
|
||||
#define WEAK_CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
||||
//! check of event exists
|
||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\" без проверки наличия события и обработчика.
|
||||
# define WEAK_CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \deprecated
|
||||
@@ -326,78 +354,99 @@
|
||||
//! \~\brief
|
||||
//! \~english Synonym of \a WEAK_CONNECT0
|
||||
//! \~russian Аналог \a WEAK_CONNECT0
|
||||
#define WEAK_CONNECT WEAK_CONNECT0
|
||||
# define WEAK_CONNECT WEAK_CONNECT0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта \"dest\"
|
||||
#define DISCONNECT0(ret, src, event, dest, handler)
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
# define DISCONNECT0(ret, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта \"dest\"
|
||||
#define DISCONNECT1(ret, type0, src, event, dest, handler)
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
# define DISCONNECT1(ret, type0, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта \"dest\"
|
||||
#define DISCONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
# define DISCONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта \"dest\"
|
||||
#define DISCONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
# define DISCONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта \"dest\"
|
||||
#define DISCONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
||||
//! \"dest\"
|
||||
# define DISCONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Synonym of \a DISCONNECT0
|
||||
//! \~russian Аналог \a DISCONNECT0
|
||||
#define DISCONNECT DISCONNECT0
|
||||
# define DISCONNECT DISCONNECT0
|
||||
|
||||
|
||||
//! \relatesalso PIObject
|
||||
//! \~\brief
|
||||
//! \~english Returns pointer to events handler \"handler\"
|
||||
//! \~russian Возвращает указатель на обработчик события \"handler\"
|
||||
#define HANDLER(handler)
|
||||
# define HANDLER(handler)
|
||||
|
||||
|
||||
#else
|
||||
|
||||
|
||||
#define _PI_STR(x) #x
|
||||
#define _PI_SSTR(x) _PI_STR(x)
|
||||
#define LOCATION __FILE__ ":" _PI_SSTR(__LINE__)
|
||||
#ifdef CC_GCC
|
||||
# define _PI_STR(x) #x
|
||||
# define _PI_SSTR(x) _PI_STR(x)
|
||||
# define LOCATION __FILE__ ":" _PI_SSTR(__LINE__)
|
||||
# ifdef CC_GCC
|
||||
# define __PTYPE(t) typename __PIVariantTypeInfo__<t>::PureType
|
||||
#else
|
||||
# else
|
||||
# define __PTYPE(t) __PIVariantTypeInfo__<t>::PureType
|
||||
#endif
|
||||
#define __VVALUE(t, v) v.value< __PTYPE(t) >()
|
||||
#define __PIOBJECT_MAX_ARGS__ 4
|
||||
# endif
|
||||
# define __VVALUE(t, v) v.value<__PTYPE(t)>()
|
||||
# define __PIOBJECT_MAX_ARGS__ 4
|
||||
|
||||
|
||||
#define PIOBJECT(name) \
|
||||
# define PIOBJECT(name) \
|
||||
\
|
||||
protected: \
|
||||
typedef name __PIObject__; \
|
||||
\
|
||||
public: \
|
||||
static const char * __classNameCC() {return #name;} \
|
||||
static uint __classNameIDS() {static uint ret = PIStringAscii(#name).hash(); return ret;} \
|
||||
const char * className() const override {return #name;} \
|
||||
uint classNameID() const override {static uint ret = PIStringAscii(#name).hash(); return ret;} \
|
||||
static const char * __classNameCC() { \
|
||||
return #name; \
|
||||
} \
|
||||
static uint __classNameIDS() { \
|
||||
static uint ret = PIStringAscii(#name).hash(); \
|
||||
return ret; \
|
||||
} \
|
||||
const char * className() const override { \
|
||||
return #name; \
|
||||
} \
|
||||
uint classNameID() const override { \
|
||||
static uint ret = PIStringAscii(#name).hash(); \
|
||||
return ret; \
|
||||
} \
|
||||
\
|
||||
private: \
|
||||
int ptrOffset() const override {name * o = (name*)100; return int(llong((PIObject*)o) - llong(o));} \
|
||||
int ptrOffset() const override { \
|
||||
name * o = (name *)100; \
|
||||
return int(llong((PIObject *)o) - llong(o)); \
|
||||
} \
|
||||
class __BaseInitializer__ { \
|
||||
public: \
|
||||
__BaseInitializer__() { \
|
||||
@@ -417,7 +466,7 @@
|
||||
}; \
|
||||
__BaseInitializer__ __base_init__;
|
||||
|
||||
#define PIOBJECT_PARENT(name) \
|
||||
# define PIOBJECT_PARENT(name) \
|
||||
class __ParentInitializer__ { \
|
||||
public: \
|
||||
__ParentInitializer__() { \
|
||||
@@ -436,15 +485,19 @@
|
||||
} \
|
||||
}; \
|
||||
__ParentInitializer__ __parent_init__; \
|
||||
\
|
||||
public: \
|
||||
const char * parentClassName() const override {return #name;} \
|
||||
const char * parentClassName() const override { \
|
||||
return #name; \
|
||||
} \
|
||||
typedef name __Parent__; \
|
||||
\
|
||||
private:
|
||||
|
||||
#define PIOBJECT_SUBCLASS(name, parent) PIOBJECT(name) PIOBJECT_PARENT(parent)
|
||||
# define PIOBJECT_SUBCLASS(name, parent) PIOBJECT(name) PIOBJECT_PARENT(parent)
|
||||
|
||||
|
||||
#define __EH_INIT_BASE__(ret, name) \
|
||||
# define __EH_INIT_BASE__(ret, name) \
|
||||
PIMutexLocker ml(__meta_mutex()); \
|
||||
__MetaData & eh(__meta_data()[__classNameIDS()]); \
|
||||
if (eh.eh_set[fp]) return; \
|
||||
@@ -456,44 +509,47 @@
|
||||
f.addrV = fpV; \
|
||||
f.type_ret = #ret;
|
||||
|
||||
#define EH_INIT0(ret, name) \
|
||||
# define EH_INIT0(ret, name) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
void * fp = (void*)(ret(*)(void*))__stat_eh_##name##__; \
|
||||
void * fp = (void *)(ret(*)(void *))__stat_eh_##name##__; \
|
||||
void * fpV = fp; \
|
||||
__EH_INIT_BASE__(ret, name) \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
#define EH_INIT1(ret, name, a0, n0) \
|
||||
# define EH_INIT1(ret, name, a0, n0) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
void * fp = (void*)(ret(*)(void*, a0))__stat_eh_##name##__; \
|
||||
void * fpV = (void*)(ret(*)(void*, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
void * fp = (void *)(ret(*)(void *, a0))__stat_eh_##name##__; \
|
||||
void * fpV = (void *)(ret(*)(void *, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
__EH_INIT_BASE__(ret, name) \
|
||||
f.__addArgument(#a0, #n0); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
#define EH_INIT2(ret, name, a0, n0, a1, n1) \
|
||||
# define EH_INIT2(ret, name, a0, n0, a1, n1) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
void * fp = (void*)(ret(*)(void*, a0, a1))__stat_eh_##name##__; \
|
||||
void * fpV = (void*)(ret(*)(void*, const PIVariantSimple &, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
void * fp = (void *)(ret(*)(void *, a0, a1))__stat_eh_##name##__; \
|
||||
void * fpV = (void *)(ret(*)(void *, const PIVariantSimple &, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
__EH_INIT_BASE__(ret, name) \
|
||||
f.__addArgument(#a0, #n0); \
|
||||
f.__addArgument(#a1, #n1); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
#define EH_INIT3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
# define EH_INIT3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
void * fp = (void*)(ret(*)(void*, a0, a1, a2))__stat_eh_##name##__; \
|
||||
void * fpV = (void*)(ret(*)(void*, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
void * fp = (void *)(ret(*)(void *, a0, a1, a2))__stat_eh_##name##__; \
|
||||
void * fpV = \
|
||||
(void *)(ret(*)(void *, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
__EH_INIT_BASE__(ret, name) \
|
||||
f.__addArgument(#a0, #n0); \
|
||||
f.__addArgument(#a1, #n1); \
|
||||
f.__addArgument(#a2, #n2); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
#define EH_INIT4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
# define EH_INIT4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
void * fp = (void*)(ret(*)(void*, a0, a1, a2, a3))__stat_eh_##name##__; \
|
||||
void * fpV = (void*)(ret(*)(void*, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &))__stat_eh_v_##name##__; \
|
||||
void * fp = (void *)(ret(*)(void *, a0, a1, a2, a3))__stat_eh_##name##__; \
|
||||
void * fpV = \
|
||||
(void *)(ret(*)(void *, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &, const PIVariantSimple &)) \
|
||||
__stat_eh_v_##name##__; \
|
||||
__EH_INIT_BASE__(ret, name) \
|
||||
f.__addArgument(#a0, #n0); \
|
||||
f.__addArgument(#a1, #n1); \
|
||||
@@ -502,191 +558,308 @@
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
|
||||
#define EVENT_HANDLER0(ret, name) \
|
||||
# define EVENT_HANDLER0(ret, name) \
|
||||
EH_INIT0(ret, name) \
|
||||
static ret __stat_eh_##name##__(void * __o__) {return ((__PIObject__*)__o__)->name();} \
|
||||
static ret __stat_eh_##name##__(void * __o__) { \
|
||||
return ((__PIObject__ *)__o__)->name(); \
|
||||
} \
|
||||
ret name()
|
||||
|
||||
#define EVENT_HANDLER1(ret, name, a0, n0) \
|
||||
# define EVENT_HANDLER1(ret, name, a0, n0) \
|
||||
EH_INIT1(ret, name, a0, n0) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0) {return ((__PIObject__*)__o__)->name(n0);} \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0) { \
|
||||
return ((__PIObject__ *)__o__)->name(n0); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0) { \
|
||||
__PTYPE(a0) tv0 = __VVALUE(a0, v0); \
|
||||
return ((__PIObject__*)__o__)->name(tv0);} \
|
||||
return ((__PIObject__ *)__o__)->name(tv0); \
|
||||
} \
|
||||
ret name(a0 n0)
|
||||
|
||||
#define EVENT_HANDLER2(ret, name, a0, n0, a1, n1) \
|
||||
# define EVENT_HANDLER2(ret, name, a0, n0, a1, n1) \
|
||||
EH_INIT2(ret, name, a0, n0, a1, n1) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1) {return ((__PIObject__*)__o__)->name(n0, n1);} \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1) { \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1) { \
|
||||
__PTYPE(a0) tv0 = __VVALUE(a0, v0); \
|
||||
__PTYPE(a1) tv1 = __VVALUE(a1, v1); \
|
||||
return ((__PIObject__*)__o__)->name(tv0, tv1);} \
|
||||
return ((__PIObject__ *)__o__)->name(tv0, tv1); \
|
||||
} \
|
||||
ret name(a0 n0, a1 n1)
|
||||
|
||||
#define EVENT_HANDLER3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
# define EVENT_HANDLER3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
EH_INIT3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2) {return ((__PIObject__*)__o__)->name(n0, n1, n2);} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) { \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2) { \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1, n2); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, \
|
||||
const PIVariantSimple & v0, \
|
||||
const PIVariantSimple & v1, \
|
||||
const PIVariantSimple & v2) { \
|
||||
__PTYPE(a0) tv0 = __VVALUE(a0, v0); \
|
||||
__PTYPE(a1) tv1 = __VVALUE(a1, v1); \
|
||||
__PTYPE(a2) tv2 = __VVALUE(a2, v2); \
|
||||
return ((__PIObject__*)__o__)->name(tv0, tv1, tv2);} \
|
||||
return ((__PIObject__ *)__o__)->name(tv0, tv1, tv2); \
|
||||
} \
|
||||
ret name(a0 n0, a1 n1, a2 n2)
|
||||
|
||||
#define EVENT_HANDLER4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
# define EVENT_HANDLER4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
EH_INIT4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2, a3 n3) {return ((__PIObject__*)__o__)->name(n0, n1, n2, n3);} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) { \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2, a3 n3) { \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1, n2, n3); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, \
|
||||
const PIVariantSimple & v0, \
|
||||
const PIVariantSimple & v1, \
|
||||
const PIVariantSimple & v2, \
|
||||
const PIVariantSimple & v3) { \
|
||||
__PTYPE(a0) tv0 = __VVALUE(a0, v0); \
|
||||
__PTYPE(a1) tv1 = __VVALUE(a1, v1); \
|
||||
__PTYPE(a2) tv2 = __VVALUE(a2, v2); \
|
||||
__PTYPE(a3) tv3 = __VVALUE(a3, v3); \
|
||||
return ((__PIObject__*)__o__)->name(tv0, tv1, tv2, tv3);} \
|
||||
return ((__PIObject__ *)__o__)->name(tv0, tv1, tv2, tv3); \
|
||||
} \
|
||||
ret name(a0 n0, a1 n1, a2 n2, a3 n3)
|
||||
|
||||
#define EVENT_HANDLER EVENT_HANDLER0
|
||||
# define EVENT_HANDLER EVENT_HANDLER0
|
||||
|
||||
|
||||
#define EVENT_VHANDLER0(ret, name) \
|
||||
# define EVENT_VHANDLER0(ret, name) \
|
||||
EH_INIT0(ret, name) \
|
||||
static ret __stat_eh_##name##__(void * __o__) { \
|
||||
return ((__PIObject__*)__o__)->name();} \
|
||||
return ((__PIObject__ *)__o__)->name(); \
|
||||
} \
|
||||
virtual ret name()
|
||||
|
||||
#define EVENT_VHANDLER1(ret, name, a0, n0) \
|
||||
# define EVENT_VHANDLER1(ret, name, a0, n0) \
|
||||
EH_INIT1(ret, name, a0, n0) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0) { \
|
||||
return ((__PIObject__*)__o__)->name(n0);} \
|
||||
return ((__PIObject__ *)__o__)->name(n0); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0) { \
|
||||
return ((__PIObject__*)__o__)->name(__VVALUE(a0, v0));} \
|
||||
return ((__PIObject__ *)__o__)->name(__VVALUE(a0, v0)); \
|
||||
} \
|
||||
virtual ret name(a0 n0)
|
||||
|
||||
#define EVENT_VHANDLER2(ret, name, a0, n0, a1, n1) \
|
||||
# define EVENT_VHANDLER2(ret, name, a0, n0, a1, n1) \
|
||||
EH_INIT2(ret, name, a0, n0, a1, n1) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1) { \
|
||||
return ((__PIObject__*)__o__)->name(n0, n1);} \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1) { \
|
||||
return ((__PIObject__*)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1));} \
|
||||
return ((__PIObject__ *)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1)); \
|
||||
} \
|
||||
virtual ret name(a0 n0, a1 n1)
|
||||
|
||||
#define EVENT_VHANDLER3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
# define EVENT_VHANDLER3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
EH_INIT3(ret, name, a0, n0, a1, n1, a2, n2) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2) { \
|
||||
return ((__PIObject__*)__o__)->name(n0, n1, n2);} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) { \
|
||||
return ((__PIObject__*)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1), __VVALUE(a2, v2));} \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1, n2); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, \
|
||||
const PIVariantSimple & v0, \
|
||||
const PIVariantSimple & v1, \
|
||||
const PIVariantSimple & v2) { \
|
||||
return ((__PIObject__ *)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1), __VVALUE(a2, v2)); \
|
||||
} \
|
||||
virtual ret name(a0 n0, a1 n1, a2 n2)
|
||||
|
||||
#define EVENT_VHANDLER4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
# define EVENT_VHANDLER4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
EH_INIT4(ret, name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
static ret __stat_eh_##name##__(void * __o__, a0 n0, a1 n1, a2 n2, a3 n3) { \
|
||||
return ((__PIObject__*)__o__)->name(n0, n1, n2, n3);} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2, const PIVariantSimple & v3) { \
|
||||
return ((__PIObject__*)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1), __VVALUE(a2, v2), __VVALUE(a3, v3));} \
|
||||
return ((__PIObject__ *)__o__)->name(n0, n1, n2, n3); \
|
||||
} \
|
||||
static ret __stat_eh_v_##name##__(void * __o__, \
|
||||
const PIVariantSimple & v0, \
|
||||
const PIVariantSimple & v1, \
|
||||
const PIVariantSimple & v2, \
|
||||
const PIVariantSimple & v3) { \
|
||||
return ((__PIObject__ *)__o__)->name(__VVALUE(a0, v0), __VVALUE(a1, v1), __VVALUE(a2, v2), __VVALUE(a3, v3)); \
|
||||
} \
|
||||
virtual ret name(a0 n0, a1 n1, a2 n2, a3 n3)
|
||||
|
||||
#define EVENT_VHANDLER EVENT_VHANDLER0
|
||||
# define EVENT_VHANDLER EVENT_VHANDLER0
|
||||
|
||||
|
||||
#define EVENT0(name) EVENT_HANDLER0(void, name) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); PIObject::raiseEvent(this, eid);}
|
||||
# define EVENT0(name) \
|
||||
EVENT_HANDLER0(void, name) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); \
|
||||
PIObject::raiseEvent(this, eid); \
|
||||
}
|
||||
|
||||
#define EVENT1(name, a0, n0) EVENT_HANDLER1(void, name, a0, n0) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); PIObject::raiseEvent(this, eid, n0);}
|
||||
# define EVENT1(name, a0, n0) \
|
||||
EVENT_HANDLER1(void, name, a0, n0) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); \
|
||||
PIObject::raiseEvent(this, eid, n0); \
|
||||
}
|
||||
|
||||
#define EVENT2(name, a0, n0, a1, n1) EVENT_HANDLER2(void, name, a0, n0, a1, n1) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); PIObject::raiseEvent(this, eid, n0, n1);}
|
||||
# define EVENT2(name, a0, n0, a1, n1) \
|
||||
EVENT_HANDLER2(void, name, a0, n0, a1, n1) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); \
|
||||
PIObject::raiseEvent(this, eid, n0, n1); \
|
||||
}
|
||||
|
||||
#define EVENT3(name, a0, n0, a1, n1, a2, n2) EVENT_HANDLER3(void, name, a0, n0, a1, n1, a2, n2) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); PIObject::raiseEvent(this, eid, n0, n1, n2);}
|
||||
# define EVENT3(name, a0, n0, a1, n1, a2, n2) \
|
||||
EVENT_HANDLER3(void, name, a0, n0, a1, n1, a2, n2) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); \
|
||||
PIObject::raiseEvent(this, eid, n0, n1, n2); \
|
||||
}
|
||||
|
||||
#define EVENT4(name, a0, n0, a1, n1, a2, n2, a3, n3) EVENT_HANDLER4(void, name, a0, n0, a1, n1, a2, n2, a3, n3) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); PIObject::raiseEvent(this, eid, n0, n1, n2, n3);}
|
||||
# define EVENT4(name, a0, n0, a1, n1, a2, n2, a3, n3) \
|
||||
EVENT_HANDLER4(void, name, a0, n0, a1, n1, a2, n2, a3, n3) { \
|
||||
static uint eid = PIStringAscii(#name).hash(); \
|
||||
PIObject::raiseEvent(this, eid, n0, n1, n2, n3); \
|
||||
}
|
||||
|
||||
#define EVENT EVENT0
|
||||
# define EVENT EVENT0
|
||||
|
||||
|
||||
#define RAISE_EVENT0(src, event) (src)->event();
|
||||
#define RAISE_EVENT1(src, event, v0) (src)->event(v0);
|
||||
#define RAISE_EVENT2(src, event, v0, v1) (src)->event(v0, v1);
|
||||
#define RAISE_EVENT3(src, event, v0, v1, v2) (src)->event(v0, v1, v2);
|
||||
#define RAISE_EVENT4(src, event, v0, v1, v2, v3) (src)->event(v0, v1, v2, v3);
|
||||
#define RAISE_EVENT RAISE_EVENT0
|
||||
# define RAISE_EVENT0(src, event) (src)->event();
|
||||
# define RAISE_EVENT1(src, event, v0) (src)->event(v0);
|
||||
# define RAISE_EVENT2(src, event, v0, v1) (src)->event(v0, v1);
|
||||
# define RAISE_EVENT3(src, event, v0, v1, v2) (src)->event(v0, v1, v2);
|
||||
# define RAISE_EVENT4(src, event, v0, v1, v2, v3) (src)->event(v0, v1, v2, v3);
|
||||
# define RAISE_EVENT RAISE_EVENT0
|
||||
|
||||
|
||||
#define CONNECTU(src, event, dest, handler) \
|
||||
# define CONNECTU(src, event, dest, handler) \
|
||||
PIObject::piConnectU(src, PIStringAscii(#event), dest, dest, PIStringAscii(#handler), LOCATION);
|
||||
|
||||
#define CONNECTU_QUEUED(src, event, dest, handler, performer) \
|
||||
# define CONNECTU_QUEUED(src, event, dest, handler, performer) \
|
||||
PIObject::piConnectU(src, PIStringAscii(#event), dest, dest, PIStringAscii(#handler), LOCATION, performer);
|
||||
|
||||
#define CONNECTL(src, event, functor) \
|
||||
# define CONNECTL(src, event, functor) \
|
||||
PIObject::piConnectLS(src, PIStringAscii(#event), PIObject::__newFunctor(&(src)->__stat_eh_##event##__, functor), LOCATION);
|
||||
|
||||
|
||||
#define CONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void*)(void(*)(void*))(&(src)->__stat_eh_##event##__), 0, LOCATION);
|
||||
# define CONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void *)(void (*)(void *))(&(src)->__stat_eh_##event##__), \
|
||||
0, \
|
||||
LOCATION);
|
||||
|
||||
#define CONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void*)(void(*)(void*, a0))(&(src)->__stat_eh_##event##__), 1, LOCATION);
|
||||
# define CONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void *)(void (*)(void *, a0))(&(src)->__stat_eh_##event##__), \
|
||||
1, \
|
||||
LOCATION);
|
||||
|
||||
#define CONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void*)(void(*)(void*, a0, a1))(&(src)->__stat_eh_##event##__), 2, LOCATION);
|
||||
# define CONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void *)(void (*)(void *, a0, a1))(&(src)->__stat_eh_##event##__), \
|
||||
2, \
|
||||
LOCATION);
|
||||
|
||||
#define CONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1, a2))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void*)(void(*)(void*, a0, a1, a2))(&(src)->__stat_eh_##event##__), 3, LOCATION);
|
||||
# define CONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1, a2))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void *)(void (*)(void *, a0, a1, a2))(&(src)->__stat_eh_##event##__), \
|
||||
3, \
|
||||
LOCATION);
|
||||
|
||||
#define CONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void*)(void(*)(void*, a0, a1, a2, a3))(&(src)->__stat_eh_##event##__), 4, LOCATION);
|
||||
# define CONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__), \
|
||||
(void *)(void (*)(void *, a0, a1, a2, a3))(&(src)->__stat_eh_##event##__), \
|
||||
4, \
|
||||
LOCATION);
|
||||
|
||||
#define CONNECT CONNECT0
|
||||
# define CONNECT CONNECT0
|
||||
|
||||
|
||||
#define WEAK_CONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*))(&(dest)->__stat_eh_##handler##__), 0, 0, LOCATION);
|
||||
# define WEAK_CONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *))(&(dest)->__stat_eh_##handler##__), \
|
||||
0, \
|
||||
0, \
|
||||
LOCATION);
|
||||
|
||||
#define WEAK_CONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0))(&(dest)->__stat_eh_##handler##__), 0, 1, LOCATION);
|
||||
# define WEAK_CONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0))(&(dest)->__stat_eh_##handler##__), \
|
||||
0, \
|
||||
1, \
|
||||
LOCATION);
|
||||
|
||||
#define WEAK_CONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1))(&(dest)->__stat_eh_##handler##__), 0, 2, LOCATION);
|
||||
# define WEAK_CONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1))(&(dest)->__stat_eh_##handler##__), \
|
||||
0, \
|
||||
2, \
|
||||
LOCATION);
|
||||
|
||||
#define WEAK_CONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1, a2))(&(dest)->__stat_eh_##handler##__), 0, 3, LOCATION);
|
||||
# define WEAK_CONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1, a2))(&(dest)->__stat_eh_##handler##__), \
|
||||
0, \
|
||||
3, \
|
||||
LOCATION);
|
||||
|
||||
#define WEAK_CONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, PIStringAscii(#event), dest, dest, (void*)(ret(*)(void*, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__), 0, 4, LOCATION);
|
||||
# define WEAK_CONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piConnect(src, \
|
||||
PIStringAscii(#event), \
|
||||
dest, \
|
||||
dest, \
|
||||
(void *)(ret(*)(void *, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__), \
|
||||
0, \
|
||||
4, \
|
||||
LOCATION);
|
||||
|
||||
#define WEAK_CONNECT WEAK_CONNECT0
|
||||
# define WEAK_CONNECT WEAK_CONNECT0
|
||||
|
||||
|
||||
#define DISCONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void*)(ret(*)(void*))(&(dest)->__stat_eh_##handler##__));
|
||||
# define DISCONNECT0(ret, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void *)(ret(*)(void *))(&(dest)->__stat_eh_##handler##__));
|
||||
|
||||
#define DISCONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void*)(ret(*)(void*, a0))(&(dest)->__stat_eh_##handler##__));
|
||||
# define DISCONNECT1(ret, a0, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void *)(ret(*)(void *, a0))(&(dest)->__stat_eh_##handler##__));
|
||||
|
||||
#define DISCONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void*)(ret(*)(void*, a0, a1))(&(dest)->__stat_eh_##handler##__));
|
||||
# define DISCONNECT2(ret, a0, a1, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void *)(ret(*)(void *, a0, a1))(&(dest)->__stat_eh_##handler##__));
|
||||
|
||||
#define DISCONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void*)(ret(*)(void*, a0, a1, a2))(&(dest)->__stat_eh_##handler##__));
|
||||
# define DISCONNECT3(ret, a0, a1, a2, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void *)(ret(*)(void *, a0, a1, a2))(&(dest)->__stat_eh_##handler##__));
|
||||
|
||||
#define DISCONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void*)(ret(*)(void*, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__));
|
||||
# define DISCONNECT4(ret, a0, a1, a2, a3, src, event, dest, handler) \
|
||||
PIObject::piDisconnect(src, PIStringAscii(#event), dest, (void *)(ret(*)(void *, a0, a1, a2, a3))(&(dest)->__stat_eh_##handler##__));
|
||||
|
||||
#define DISCONNECT DISCONNECT0
|
||||
# define DISCONNECT DISCONNECT0
|
||||
|
||||
|
||||
#define HANDLER(handler) __stat_eh_##handler##__
|
||||
# define HANDLER(handler) __stat_eh_##handler##__
|
||||
|
||||
#define __PIOBJECT_SIGNATURE__ 0xabcdbadc
|
||||
# define __PIOBJECT_SIGNATURE__ 0xabcdbadc
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -19,15 +19,15 @@
|
||||
|
||||
#include "piwaitevent_p.h"
|
||||
#ifdef WINDOWS
|
||||
//# ifdef _WIN32_WINNT
|
||||
//# undef _WIN32_WINNT
|
||||
//# define _WIN32_WINNT 0x0600
|
||||
//# endif
|
||||
// # ifdef _WIN32_WINNT
|
||||
// # undef _WIN32_WINNT
|
||||
// # define _WIN32_WINNT 0x0600
|
||||
// # endif
|
||||
# include <synchapi.h>
|
||||
#else
|
||||
# include <errno.h>
|
||||
# include <fcntl.h>
|
||||
# include <sys/ioctl.h>
|
||||
# include <errno.h>
|
||||
#endif
|
||||
#include "pistring.h"
|
||||
|
||||
@@ -45,7 +45,8 @@ void PIWaitEvent::create() {
|
||||
piCout << "Error with CreateEventA:" << errorString();
|
||||
}
|
||||
#else
|
||||
for (int i = 0; i < 3; ++i) memset(&(fds[i]), 0, sizeof(fds[i]));
|
||||
for (int i = 0; i < 3; ++i)
|
||||
memset(&(fds[i]), 0, sizeof(fds[i]));
|
||||
if (::pipe(pipe_fd) < 0) {
|
||||
piCout << "Error with pipe:" << errorString();
|
||||
} else {
|
||||
@@ -82,14 +83,16 @@ bool PIWaitEvent::wait(int fd, CheckRole role) {
|
||||
if (fd == -1) return false;
|
||||
int nfds = piMaxi(pipe_fd[ReadEnd], fd) + 1;
|
||||
int fd_index = role;
|
||||
for (int i = 0; i < 3; ++i) FD_ZERO(&(fds[i]));
|
||||
for (int i = 0; i < 3; ++i)
|
||||
FD_ZERO(&(fds[i]));
|
||||
FD_SET(pipe_fd[ReadEnd], &(fds[CheckRead]));
|
||||
FD_SET(fd, &(fds[CheckExeption]));
|
||||
if (fd_index != CheckExeption) FD_SET(fd, &(fds[fd_index]));
|
||||
int sr = ::select(nfds, &(fds[CheckRead]), &(fds[CheckWrite]), &(fds[CheckExeption]), nullptr);
|
||||
int buf = 0;
|
||||
while (::read(pipe_fd[ReadEnd], &buf, sizeof(buf)) > 0);
|
||||
//piCout << "wait result" << sr << FD_ISSET(fd, &(fds[CheckExeption])) << FD_ISSET(fd, &(fds[fd_index]));
|
||||
while (::read(pipe_fd[ReadEnd], &buf, sizeof(buf)) > 0)
|
||||
;
|
||||
// piCout << "wait result" << sr << FD_ISSET(fd, &(fds[CheckExeption])) << FD_ISSET(fd, &(fds[fd_index]));
|
||||
if (sr == EBADF || sr == EINTR) return false;
|
||||
if (FD_ISSET(fd, &(fds[CheckExeption]))) return true;
|
||||
return FD_ISSET(fd, &(fds[fd_index]));
|
||||
@@ -113,7 +116,8 @@ bool PIWaitEvent::sleep(int us) {
|
||||
timeout.tv_usec = us % 1000000;
|
||||
int ret = ::select(nfds, &(fds[CheckRead]), nullptr, nullptr, &timeout);
|
||||
int buf = 0;
|
||||
while (::read(pipe_fd[ReadEnd], &buf, sizeof(buf)) > 0);
|
||||
while (::read(pipe_fd[ReadEnd], &buf, sizeof(buf)) > 0)
|
||||
;
|
||||
return ret == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -21,14 +21,16 @@
|
||||
#define PIWAITEVENT_P_H
|
||||
|
||||
#include "pibase.h"
|
||||
// clang-format off
|
||||
#ifdef WINDOWS
|
||||
# include <stdarg.h>
|
||||
# include <windef.h>
|
||||
# include <winbase.h>
|
||||
#else
|
||||
# include <unistd.h>
|
||||
# include <sys/select.h>
|
||||
# include <unistd.h>
|
||||
#endif
|
||||
// clang-format on
|
||||
|
||||
|
||||
class PIP_EXPORT PIWaitEvent {
|
||||
@@ -60,7 +62,6 @@ private:
|
||||
WriteEnd = 1
|
||||
};
|
||||
#endif
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -26,34 +26,41 @@
|
||||
#ifndef PIAUTH_H
|
||||
#define PIAUTH_H
|
||||
|
||||
#include "pip_crypt_export.h"
|
||||
#include "piobject.h"
|
||||
#include "picrypt.h"
|
||||
#include "piobject.h"
|
||||
#include "pip_crypt_export.h"
|
||||
|
||||
|
||||
class PIP_CRYPT_EXPORT PIAuth : public PIObject
|
||||
{
|
||||
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
|
||||
PIOBJECT(PIAuth)
|
||||
|
||||
public:
|
||||
enum State {NotConnected, AuthProbe, PassRequest, AuthReply, KeyExchange, Connected};
|
||||
enum State {
|
||||
NotConnected,
|
||||
AuthProbe,
|
||||
PassRequest,
|
||||
AuthReply,
|
||||
KeyExchange,
|
||||
Connected
|
||||
};
|
||||
|
||||
//! Create PIAuth with your digital sign
|
||||
PIAuth(const PIByteArray & sign);
|
||||
|
||||
//! Set server info data for client authorize event
|
||||
void setInfoData(const PIByteArray & info) {custom_info = info;}
|
||||
void setInfoData(const PIByteArray & info) { custom_info = info; }
|
||||
|
||||
//! Set server password for check
|
||||
void setServerPassword(const PIString & ps);
|
||||
|
||||
//! Set list of trusted clients/servers public digital sign keys
|
||||
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) {auth_pkeys = pkeys;}
|
||||
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
|
||||
|
||||
//! Get list of trusted clients/servers public digital sign keys
|
||||
PIVector<PIByteArray> getAuthorizedPublicKeys() {return auth_pkeys;}
|
||||
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
|
||||
|
||||
//! Get your digital sign public key
|
||||
PIByteArray getSignPublicKey() {return sign_pk;}
|
||||
PIByteArray getSignPublicKey() { return sign_pk; }
|
||||
|
||||
|
||||
//! Stop authorization
|
||||
@@ -91,7 +98,10 @@ public:
|
||||
EVENT1(passwordCheck, bool, result);
|
||||
|
||||
private:
|
||||
enum Role {Client, Server};
|
||||
enum Role {
|
||||
Client,
|
||||
Server
|
||||
};
|
||||
|
||||
State disconnect(PIByteArray & ba, const PIString & error = PIString());
|
||||
bool isAuthorizedKey(const PIByteArray & pkey);
|
||||
|
||||
@@ -41,7 +41,7 @@ public:
|
||||
PIByteArray setKey(const PIString & secret);
|
||||
|
||||
//! Returns current key
|
||||
PIByteArray key() {return key_;}
|
||||
PIByteArray key() { return key_; }
|
||||
|
||||
//! Encrypt given data "data", result size will be increased by \a sizeCrypt()
|
||||
PIByteArray crypt(const PIByteArray & data);
|
||||
@@ -104,7 +104,7 @@ public:
|
||||
static void generateKeypair(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
||||
|
||||
//! Encrypt given data "data"
|
||||
PIByteArray crypt(const PIByteArray &data, const PIByteArray & public_key, const PIByteArray & secret_key);
|
||||
PIByteArray crypt(const PIByteArray & data, const PIByteArray & public_key, const PIByteArray & secret_key);
|
||||
|
||||
//! Decrypt given data "crypt_data"
|
||||
PIByteArray decrypt(const PIByteArray & crypt_data, const PIByteArray & public_key, const PIByteArray & secret_key, bool * ok = 0);
|
||||
@@ -120,7 +120,6 @@ private:
|
||||
static bool init();
|
||||
|
||||
PIByteArray nonce_, key_;
|
||||
|
||||
};
|
||||
|
||||
#endif // PICRYPT_H
|
||||
|
||||
@@ -51,7 +51,7 @@
|
||||
#ifndef PICRYPTMODULE_H
|
||||
#define PICRYPTMODULE_H
|
||||
|
||||
#include "picrypt.h"
|
||||
#include "piauth.h"
|
||||
#include "picrypt.h"
|
||||
|
||||
#endif // PICRYPTMODULE_H
|
||||
|
||||
@@ -58,9 +58,8 @@ PIEllipsoidModel PIEllipsoidModel::GPSEllipsoid() {
|
||||
PIEllipsoidModel PIEllipsoidModel::KrasovskiyEllipsoid() {
|
||||
PIEllipsoidModel v;
|
||||
v.a = 6378245.0;
|
||||
v.flattening = 1.0/298.3;
|
||||
v.eccentricity = sqrt(v.a*v.a - 6356863.0*6356863.0)/v.a;
|
||||
v.flattening = 1.0 / 298.3;
|
||||
v.eccentricity = sqrt(v.a * v.a - 6356863.0 * 6356863.0) / v.a;
|
||||
v.angVelocity = 7.292115e-5;
|
||||
return v;
|
||||
}
|
||||
|
||||
|
||||
@@ -32,8 +32,8 @@
|
||||
class PIP_EXPORT PIEllipsoidModel {
|
||||
public:
|
||||
PIEllipsoidModel();
|
||||
double eccSquared() const {return eccentricity * eccentricity;} // eccentricity squared
|
||||
double b() const {return a * sqrt(1 - eccSquared());}
|
||||
double eccSquared() const { return eccentricity * eccentricity; } // eccentricity squared
|
||||
double b() const { return a * sqrt(1 - eccSquared()); }
|
||||
|
||||
static PIEllipsoidModel WGS84Ellipsoid();
|
||||
static PIEllipsoidModel PZ90Ellipsoid();
|
||||
@@ -47,5 +47,4 @@ public:
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif // PIELLIPSOIDMODEL_H
|
||||
|
||||
@@ -44,15 +44,15 @@ PIGeoPosition::PIGeoPosition(PIMathVectorT3d v, PIGeoPosition::CoordinateSystem
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
if(sys == Unknown || sys == s) return *this;
|
||||
PIGeoPosition & PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
if (sys == Unknown || sys == s) return *this;
|
||||
PIGeoPosition tmp(*this);
|
||||
switch(s) {
|
||||
case Unknown:
|
||||
return *this;
|
||||
switch (s) {
|
||||
case Unknown: return *this;
|
||||
case Geodetic:
|
||||
switch(sys) {
|
||||
case Unknown: case Geodetic: return *this;
|
||||
switch (sys) {
|
||||
case Unknown:
|
||||
case Geodetic: return *this;
|
||||
case Geocentric:
|
||||
convertGeodeticToGeocentric(*this, tmp, el);
|
||||
tmp.s = Geocentric;
|
||||
@@ -69,8 +69,9 @@ PIGeoPosition &PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
}
|
||||
break;
|
||||
case Geocentric:
|
||||
switch(sys) {
|
||||
case Unknown: case Geocentric: return *this;
|
||||
switch (sys) {
|
||||
case Unknown:
|
||||
case Geocentric: return *this;
|
||||
case Geodetic:
|
||||
convertGeocentricToGeodetic(*this, tmp, el);
|
||||
tmp.s = Geodetic;
|
||||
@@ -86,8 +87,9 @@ PIGeoPosition &PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
}
|
||||
break;
|
||||
case Cartesian:
|
||||
switch(sys) {
|
||||
case Unknown: case Cartesian: return *this;
|
||||
switch (sys) {
|
||||
case Unknown:
|
||||
case Cartesian: return *this;
|
||||
case Geodetic:
|
||||
convertCartesianToGeodetic(*this, tmp, el);
|
||||
tmp.s = Geodetic;
|
||||
@@ -103,8 +105,9 @@ PIGeoPosition &PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
}
|
||||
break;
|
||||
case Spherical:
|
||||
switch(sys) {
|
||||
case Unknown: case Spherical: return *this;
|
||||
switch (sys) {
|
||||
case Unknown:
|
||||
case Spherical: return *this;
|
||||
case Geodetic:
|
||||
(*this)[0] = 90 - (*this)[0]; // sph -> geocen
|
||||
convertGeocentricToGeodetic(*this, tmp, el);
|
||||
@@ -126,7 +129,7 @@ PIGeoPosition &PIGeoPosition::transformTo(PIGeoPosition::CoordinateSystem sys) {
|
||||
}
|
||||
|
||||
double PIGeoPosition::x() const {
|
||||
if(s == Cartesian) return (*this)[0];
|
||||
if (s == Cartesian) return (*this)[0];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Cartesian);
|
||||
return t[0];
|
||||
@@ -134,7 +137,7 @@ double PIGeoPosition::x() const {
|
||||
|
||||
|
||||
double PIGeoPosition::y() const {
|
||||
if(s == Cartesian) return (*this)[1];
|
||||
if (s == Cartesian) return (*this)[1];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Cartesian);
|
||||
return t[1];
|
||||
@@ -142,7 +145,7 @@ double PIGeoPosition::y() const {
|
||||
|
||||
|
||||
double PIGeoPosition::z() const {
|
||||
if(s == Cartesian) return (*this)[2];
|
||||
if (s == Cartesian) return (*this)[2];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Cartesian);
|
||||
return t[2];
|
||||
@@ -150,7 +153,7 @@ double PIGeoPosition::z() const {
|
||||
|
||||
|
||||
double PIGeoPosition::latitudeGeodetic() const {
|
||||
if(s == Geodetic) return (*this)[0];
|
||||
if (s == Geodetic) return (*this)[0];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Geodetic);
|
||||
return t[0];
|
||||
@@ -158,7 +161,7 @@ double PIGeoPosition::latitudeGeodetic() const {
|
||||
|
||||
|
||||
double PIGeoPosition::latitudeGeocentric() const {
|
||||
if(s == Geocentric) return (*this)[0];
|
||||
if (s == Geocentric) return (*this)[0];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Geocentric);
|
||||
return t[0];
|
||||
@@ -166,7 +169,7 @@ double PIGeoPosition::latitudeGeocentric() const {
|
||||
|
||||
|
||||
double PIGeoPosition::longitude() const {
|
||||
if(s != Cartesian) return (*this)[1];
|
||||
if (s != Cartesian) return (*this)[1];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Spherical);
|
||||
return t[1];
|
||||
@@ -174,7 +177,7 @@ double PIGeoPosition::longitude() const {
|
||||
|
||||
|
||||
double PIGeoPosition::theta() const {
|
||||
if(s == Spherical) return (*this)[0];
|
||||
if (s == Spherical) return (*this)[0];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Spherical);
|
||||
return t[0];
|
||||
@@ -187,7 +190,7 @@ double PIGeoPosition::phi() const {
|
||||
|
||||
|
||||
double PIGeoPosition::radius() const {
|
||||
if(s == Spherical || s == Geocentric) return (*this)[2];
|
||||
if (s == Spherical || s == Geocentric) return (*this)[2];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Spherical);
|
||||
return t[2];
|
||||
@@ -195,19 +198,21 @@ double PIGeoPosition::radius() const {
|
||||
|
||||
|
||||
double PIGeoPosition::height() const {
|
||||
if(s == Geodetic) return (*this)[2];
|
||||
if (s == Geodetic) return (*this)[2];
|
||||
PIGeoPosition t(*this);
|
||||
t.transformTo(Geodetic);
|
||||
return t[2];
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell) {
|
||||
PIGeoPosition & PIGeoPosition::setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell) {
|
||||
assertm(lat <= 90 && lat >= -90, "Achtung! Invalid latitude in setGeodetic");
|
||||
(*this)[0] = lat;
|
||||
(*this)[1] = lon;
|
||||
if((*this)[1] < 0) (*this)[1] += 360 * (1 + (unsigned long)((*this)[1]/360));
|
||||
else if((*this)[1] >= 360) (*this)[1] -= 360 * (unsigned long)((*this)[1]/360);
|
||||
if ((*this)[1] < 0)
|
||||
(*this)[1] += 360 * (1 + (unsigned long)((*this)[1] / 360));
|
||||
else if ((*this)[1] >= 360)
|
||||
(*this)[1] -= 360 * (unsigned long)((*this)[1] / 360);
|
||||
(*this)[2] = ht;
|
||||
el = ell;
|
||||
s = Geodetic;
|
||||
@@ -215,33 +220,37 @@ PIGeoPosition &PIGeoPosition::setGeodetic(double lat, double lon, double ht, PIE
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::setGeocentric(double lat, double lon, double rad) {
|
||||
PIGeoPosition & PIGeoPosition::setGeocentric(double lat, double lon, double rad) {
|
||||
assertm(lat <= 90 && lat >= -90, "Achtung! Invalid latitude in setGeocentric");
|
||||
assertm(rad >= 0, "Achtung! Invalid radius in setGeocentric");
|
||||
(*this)[0] = lat;
|
||||
(*this)[1] = lon;
|
||||
(*this)[2] = rad;
|
||||
if((*this)[1] < 0) (*this)[1] += 360*(1+(unsigned long)((*this)[1]/360));
|
||||
else if((*this)[1] >= 360) (*this)[1] -= 360*(unsigned long)((*this)[1]/360);
|
||||
if ((*this)[1] < 0)
|
||||
(*this)[1] += 360 * (1 + (unsigned long)((*this)[1] / 360));
|
||||
else if ((*this)[1] >= 360)
|
||||
(*this)[1] -= 360 * (unsigned long)((*this)[1] / 360);
|
||||
s = Geocentric;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::setSpherical(double theta, double phi, double rad) {
|
||||
PIGeoPosition & PIGeoPosition::setSpherical(double theta, double phi, double rad) {
|
||||
assertm(theta <= 180 && theta >= 0, "Achtung! Invalid theta in setSpherical");
|
||||
assertm(rad >= 0, "Achtung! Invalid radius in setSpherical");
|
||||
(*this)[0] = theta;
|
||||
(*this)[1] = phi;
|
||||
(*this)[2] = rad;
|
||||
if((*this)[1] < 0) (*this)[1] += 360*(1+(unsigned long)((*this)[1]/360));
|
||||
else if((*this)[1] >= 360) (*this)[1] -= 360*(unsigned long)((*this)[1]/360);
|
||||
if ((*this)[1] < 0)
|
||||
(*this)[1] += 360 * (1 + (unsigned long)((*this)[1] / 360));
|
||||
else if ((*this)[1] >= 360)
|
||||
(*this)[1] -= 360 * (unsigned long)((*this)[1] / 360);
|
||||
s = Spherical;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::setECEF(double x, double y, double z) {
|
||||
PIGeoPosition & PIGeoPosition::setECEF(double x, double y, double z) {
|
||||
(*this)[0] = x;
|
||||
(*this)[1] = y;
|
||||
(*this)[2] = z;
|
||||
@@ -250,7 +259,7 @@ PIGeoPosition &PIGeoPosition::setECEF(double x, double y, double z) {
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertSphericalToCartesian(const PIMathVectorT3d &tpr, PIMathVectorT3d &xyz) {
|
||||
void PIGeoPosition::convertSphericalToCartesian(const PIMathVectorT3d & tpr, PIMathVectorT3d & xyz) {
|
||||
double st = sin(toRad(tpr[0]));
|
||||
xyz[0] = tpr[2] * st * cos(toRad(tpr[1]));
|
||||
xyz[1] = tpr[2] * st * sin(toRad(tpr[1]));
|
||||
@@ -258,51 +267,51 @@ void PIGeoPosition::convertSphericalToCartesian(const PIMathVectorT3d &tpr, PIMa
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertCartesianToSpherical(const PIMathVectorT3d &xyz, PIMathVectorT3d &tpr) {
|
||||
void PIGeoPosition::convertCartesianToSpherical(const PIMathVectorT3d & xyz, PIMathVectorT3d & tpr) {
|
||||
tpr[2] = xyz.length();
|
||||
if(tpr[2] <= PIGeoPosition::position_tolerance / 5) { // zero-length Cartesian vector
|
||||
if (tpr[2] <= PIGeoPosition::position_tolerance / 5) { // zero-length Cartesian vector
|
||||
tpr[0] = 90.0;
|
||||
tpr[1] = 0.0;
|
||||
return;
|
||||
}
|
||||
tpr[0] = acos(xyz[2] / tpr[2]) * rad2deg;
|
||||
if(sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1]) < PIGeoPosition::position_tolerance / 5) { // pole
|
||||
if (sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1]) < PIGeoPosition::position_tolerance / 5) { // pole
|
||||
tpr[1] = 0.0;
|
||||
return;
|
||||
}
|
||||
tpr[1] = atan2(xyz[1],xyz[0]) * rad2deg;
|
||||
if(tpr[1] < 0.0) tpr[1] += 360.0;
|
||||
tpr[1] = atan2(xyz[1], xyz[0]) * rad2deg;
|
||||
if (tpr[1] < 0.0) tpr[1] += 360.0;
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertCartesianToGeodetic(const PIMathVectorT3d &xyz, PIMathVectorT3d &llh, PIEllipsoidModel ell) {
|
||||
double p,slat,nn,htold,latold;
|
||||
void PIGeoPosition::convertCartesianToGeodetic(const PIMathVectorT3d & xyz, PIMathVectorT3d & llh, PIEllipsoidModel ell) {
|
||||
double p, slat, nn, htold, latold;
|
||||
p = sqrt(xyz[0] * xyz[0] + xyz[1] * xyz[1]);
|
||||
if(p < PIGeoPosition::position_tolerance / 5) { // pole or origin
|
||||
llh[0] = (xyz[2] > 0.0 ? 90.0: -90.0);
|
||||
if (p < PIGeoPosition::position_tolerance / 5) { // pole or origin
|
||||
llh[0] = (xyz[2] > 0.0 ? 90.0 : -90.0);
|
||||
llh[1] = 0.0; // lon undefined, really
|
||||
llh[2] = piAbsd(xyz[2]) - ell.a * sqrt(1.0-ell.eccSquared());
|
||||
llh[2] = piAbsd(xyz[2]) - ell.a * sqrt(1.0 - ell.eccSquared());
|
||||
return;
|
||||
}
|
||||
llh[0] = atan2(xyz[2], p*(1.0-ell.eccSquared()));
|
||||
llh[0] = atan2(xyz[2], p * (1.0 - ell.eccSquared()));
|
||||
llh[2] = 0;
|
||||
for(int i=0; i<5; i++) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
slat = sin(llh[0]);
|
||||
nn = ell.a / sqrt(1.0 - ell.eccSquared() * slat * slat);
|
||||
htold = llh[2];
|
||||
llh[2] = p / cos(llh[0]) - nn;
|
||||
latold = llh[0];
|
||||
llh[0] = atan2(xyz[2], p*(1.0 - ell.eccSquared() * (nn / (nn + llh[2]))));
|
||||
if(piAbsd(llh[0] - latold) < 1.0e-9 && piAbsd(llh[2] - htold) < 1.0e-9 * ell.a) break;
|
||||
llh[0] = atan2(xyz[2], p * (1.0 - ell.eccSquared() * (nn / (nn + llh[2]))));
|
||||
if (piAbsd(llh[0] - latold) < 1.0e-9 && piAbsd(llh[2] - htold) < 1.0e-9 * ell.a) break;
|
||||
}
|
||||
llh[1] = atan2(xyz[1], xyz[0]);
|
||||
if(llh[1] < 0.0) llh[1] += M_2PI;
|
||||
if (llh[1] < 0.0) llh[1] += M_2PI;
|
||||
llh[0] *= rad2deg;
|
||||
llh[1] *= rad2deg;
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertGeodeticToCartesian(const PIMathVectorT3d &llh, PIMathVectorT3d &xyz, PIEllipsoidModel ell) {
|
||||
void PIGeoPosition::convertGeodeticToCartesian(const PIMathVectorT3d & llh, PIMathVectorT3d & xyz, PIEllipsoidModel ell) {
|
||||
double slat = sin(toRad(llh[0]));
|
||||
double clat = cos(toRad(llh[0]));
|
||||
double nn = ell.a / sqrt(1.0 - ell.eccSquared() * slat * slat);
|
||||
@@ -312,31 +321,34 @@ void PIGeoPosition::convertGeodeticToCartesian(const PIMathVectorT3d &llh, PIMat
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertCartesianToGeocentric(const PIMathVectorT3d &xyz, PIMathVectorT3d &llr) {
|
||||
void PIGeoPosition::convertCartesianToGeocentric(const PIMathVectorT3d & xyz, PIMathVectorT3d & llr) {
|
||||
convertCartesianToSpherical(xyz, llr);
|
||||
llr[0] = 90.0 - llr[0]; // convert theta to latitude
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertGeocentricToCartesian(const PIMathVectorT3d &llr, PIMathVectorT3d &xyz) {
|
||||
void PIGeoPosition::convertGeocentricToCartesian(const PIMathVectorT3d & llr, PIMathVectorT3d & xyz) {
|
||||
PIMathVectorT3d llh(llr);
|
||||
llh[0] = 90.0 - llh[0]; // convert latitude to theta
|
||||
convertSphericalToCartesian(llh, xyz);
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertGeocentricToGeodetic(const PIMathVectorT3d &llr, PIMathVectorT3d &llh, PIEllipsoidModel ell) {
|
||||
void PIGeoPosition::convertGeocentricToGeodetic(const PIMathVectorT3d & llr, PIMathVectorT3d & llh, PIEllipsoidModel ell) {
|
||||
double cl, p, sl, slat, nn, htold, latold;
|
||||
llh[1] = llr[1]; // longitude is unchanged
|
||||
cl = sin(toRad(90.0 - llr[0]));
|
||||
sl = cos(toRad(90.0 - llr[0]));
|
||||
if(llr[2] <= PIGeoPosition::position_tolerance / 5) { // radius is below tolerance, hence assign zero-length, arbitrarily set latitude = longitude = 0
|
||||
if (llr[2] <= PIGeoPosition::position_tolerance /
|
||||
5) { // radius is below tolerance, hence assign zero-length, arbitrarily set latitude = longitude = 0
|
||||
llh[0] = llh[1] = 0.0;
|
||||
llh[2] = -ell.a;
|
||||
return;
|
||||
} else if(cl < 1.e-10) { // near pole ... note that 1mm/radius(Earth) = 1.5e-10
|
||||
if(llr[0] < 0.0) llh[0] = -90.0;
|
||||
else llh[0] = 90.0;
|
||||
} else if (cl < 1.e-10) { // near pole ... note that 1mm/radius(Earth) = 1.5e-10
|
||||
if (llr[0] < 0.0)
|
||||
llh[0] = -90.0;
|
||||
else
|
||||
llh[0] = 90.0;
|
||||
llh[1] = 0.0;
|
||||
llh[2] = llr[2] - ell.a * sqrt(1.0 - ell.eccSquared());
|
||||
return;
|
||||
@@ -344,31 +356,34 @@ void PIGeoPosition::convertGeocentricToGeodetic(const PIMathVectorT3d &llr, PIMa
|
||||
llh[0] = atan2(sl, cl * (1.0 - ell.eccSquared()));
|
||||
p = cl * llr[2];
|
||||
llh[2] = 0.0;
|
||||
for(int i=0; i<5; i++) {
|
||||
for (int i = 0; i < 5; i++) {
|
||||
slat = sin(llh[0]);
|
||||
nn = ell.a / sqrt(1.0 - ell.eccSquared() * slat * slat);
|
||||
htold = llh[2];
|
||||
llh[2] = p / cos(llh[0]) - nn;
|
||||
latold = llh[0];
|
||||
llh[0] = atan2(sl, cl * (1.0 - ell.eccSquared() * (nn / (nn + llh[2]))));
|
||||
if(piAbsd(llh[0] - latold) < 1.0e-9 && piAbsd(llh[2] - htold) < 1.0e-9 * ell.a) break;
|
||||
if (piAbsd(llh[0] - latold) < 1.0e-9 && piAbsd(llh[2] - htold) < 1.0e-9 * ell.a) break;
|
||||
}
|
||||
llh[0] *= rad2deg;
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::convertGeodeticToGeocentric(const PIMathVectorT3d &llh, PIMathVectorT3d &llr, PIEllipsoidModel ell) {
|
||||
void PIGeoPosition::convertGeodeticToGeocentric(const PIMathVectorT3d & llh, PIMathVectorT3d & llr, PIEllipsoidModel ell) {
|
||||
double slat = sin(toRad(llh[0]));
|
||||
double nn = ell.a / sqrt(1.0 - ell.eccSquared() * slat * slat);
|
||||
llr[1] = llh[1]; // longitude is unchanged
|
||||
llr[2] = sqrt((nn+llh[2])*(nn+llh[2]) + nn*ell.eccSquared()*(nn*ell.eccSquared()-2*(nn+llh[2]))*slat*slat); // radius
|
||||
if(llr[2] <= PIGeoPosition::position_tolerance/5) { // radius is below tolerance, hence assign zero-length
|
||||
llr[2] =
|
||||
sqrt((nn + llh[2]) * (nn + llh[2]) + nn * ell.eccSquared() * (nn * ell.eccSquared() - 2 * (nn + llh[2])) * slat * slat); // radius
|
||||
if (llr[2] <= PIGeoPosition::position_tolerance / 5) { // radius is below tolerance, hence assign zero-length
|
||||
llr[0] = llr[1] = llr[2] = 0; // arbitrarily set latitude = longitude = 0
|
||||
return;
|
||||
}
|
||||
if(1 - piAbsd(slat) < 1.e-10) { // at the pole
|
||||
if(slat < 0) llr[0] = -90.0;
|
||||
else llr[0] = 90.0;
|
||||
if (1 - piAbsd(slat) < 1.e-10) { // at the pole
|
||||
if (slat < 0)
|
||||
llr[0] = -90.0;
|
||||
else
|
||||
llr[0] = 90.0;
|
||||
llr[1] = 0.0;
|
||||
return;
|
||||
}
|
||||
@@ -386,55 +401,61 @@ double PIGeoPosition::radiusEarth(double geolat, PIEllipsoidModel ell) {
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::operator=(const PIMathVectorT3d &v) {
|
||||
*((PIMathVectorT3d*)(this)) = v;
|
||||
PIGeoPosition & PIGeoPosition::operator=(const PIMathVectorT3d & v) {
|
||||
*((PIMathVectorT3d *)(this)) = v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::operator-=(const PIGeoPosition &right) {
|
||||
PIGeoPosition & PIGeoPosition::operator-=(const PIGeoPosition & right) {
|
||||
PIGeoPosition r(right);
|
||||
CoordinateSystem saves = s;
|
||||
transformTo(Cartesian);
|
||||
r.transformTo(Cartesian);
|
||||
(*(PIMathVectorT3d*)(this)) -= r;
|
||||
(*(PIMathVectorT3d *)(this)) -= r;
|
||||
transformTo(saves);
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
PIGeoPosition &PIGeoPosition::operator+=(const PIGeoPosition &right) {
|
||||
PIGeoPosition & PIGeoPosition::operator+=(const PIGeoPosition & right) {
|
||||
PIGeoPosition r(right);
|
||||
CoordinateSystem saves = s;
|
||||
transformTo(Cartesian);
|
||||
r.transformTo(Cartesian);
|
||||
(*(PIMathVectorT3d*)(this)) += r;
|
||||
(*(PIMathVectorT3d *)(this)) += r;
|
||||
transformTo(saves);
|
||||
return *this;
|
||||
}
|
||||
|
||||
|
||||
bool PIGeoPosition::operator==(const PIGeoPosition &right) const {
|
||||
if(el.a != right.el.a || el.eccSquared() != right.el.eccSquared()) return false;
|
||||
if(range(*this, right) < position_tolerance) return true;
|
||||
else return false;
|
||||
bool PIGeoPosition::operator==(const PIGeoPosition & right) const {
|
||||
if (el.a != right.el.a || el.eccSquared() != right.el.eccSquared()) return false;
|
||||
if (range(*this, right) < position_tolerance)
|
||||
return true;
|
||||
else
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
void PIGeoPosition::initialize(PIMathVectorT3d v, PIGeoPosition::CoordinateSystem sys, PIEllipsoidModel ell) {
|
||||
double a(v[0]), b(v[1]), c(v[2]);
|
||||
if(sys == Geodetic || sys==Geocentric) {
|
||||
if (sys == Geodetic || sys == Geocentric) {
|
||||
assertm(a <= 90 && a >= -90, "Achtung! Invalid latitude in constructor");
|
||||
if(b < 0) b += 360*(1+(unsigned long)(b/360));
|
||||
else if(b >= 360) b -= 360*(unsigned long)(b/360);
|
||||
if (b < 0)
|
||||
b += 360 * (1 + (unsigned long)(b / 360));
|
||||
else if (b >= 360)
|
||||
b -= 360 * (unsigned long)(b / 360);
|
||||
}
|
||||
if(sys==Geocentric || sys==Spherical) {
|
||||
if (sys == Geocentric || sys == Spherical) {
|
||||
assertm(c >= 0, "Achtung! Invalid radius in constructor");
|
||||
}
|
||||
if(sys==Spherical) {
|
||||
if (sys == Spherical) {
|
||||
assertm(a >= 0 && a <= 180, "Achtung! Invalid theta in constructor");
|
||||
if(b < 0) b += 360*(1+(unsigned long)(b/360));
|
||||
else if(b >= 360) b -= 360*(unsigned long)(b/360);
|
||||
if (b < 0)
|
||||
b += 360 * (1 + (unsigned long)(b / 360));
|
||||
else if (b >= 360)
|
||||
b -= 360 * (unsigned long)(b / 360);
|
||||
}
|
||||
(*this)[0] = a;
|
||||
(*this)[1] = b;
|
||||
@@ -444,15 +465,15 @@ void PIGeoPosition::initialize(PIMathVectorT3d v, PIGeoPosition::CoordinateSyste
|
||||
}
|
||||
|
||||
|
||||
double PIGeoPosition::range(const PIGeoPosition &a, const PIGeoPosition &b) {
|
||||
PIGeoPosition l(a),r(b);
|
||||
double PIGeoPosition::range(const PIGeoPosition & a, const PIGeoPosition & b) {
|
||||
PIGeoPosition l(a), r(b);
|
||||
l.transformTo(PIGeoPosition::Cartesian);
|
||||
r.transformTo(PIGeoPosition::Cartesian);
|
||||
return (l - r).length();
|
||||
}
|
||||
|
||||
|
||||
double PIGeoPosition::elevation(const PIGeoPosition &p) const {
|
||||
double PIGeoPosition::elevation(const PIGeoPosition & p) const {
|
||||
PIGeoPosition r(*this), s(p);
|
||||
r.transformTo(Cartesian);
|
||||
s.transformTo(Cartesian);
|
||||
@@ -460,7 +481,7 @@ double PIGeoPosition::elevation(const PIGeoPosition &p) const {
|
||||
}
|
||||
|
||||
|
||||
double PIGeoPosition::elevationGeodetic(const PIGeoPosition &p) const {
|
||||
double PIGeoPosition::elevationGeodetic(const PIGeoPosition & p) const {
|
||||
PIGeoPosition r(*this), s(p);
|
||||
double lat = toRad(r.latitudeGeodetic());
|
||||
double lng = toRad(r.longitude());
|
||||
@@ -480,7 +501,7 @@ double PIGeoPosition::elevationGeodetic(const PIGeoPosition &p) const {
|
||||
}
|
||||
|
||||
|
||||
double PIGeoPosition::azimuth(const PIGeoPosition &p) const {
|
||||
double PIGeoPosition::azimuth(const PIGeoPosition & p) const {
|
||||
PIGeoPosition r(*this), s(p);
|
||||
r.transformTo(Cartesian);
|
||||
s.transformTo(Cartesian);
|
||||
@@ -502,16 +523,18 @@ double PIGeoPosition::azimuth(const PIGeoPosition &p) const {
|
||||
z1 = s[0] - r[0];
|
||||
z2 = s[1] - r[1];
|
||||
z3 = s[2] - r[2];
|
||||
p1 = (xn1 * z1) + (xn2 * z2) + (xn3 * z3) ;
|
||||
p2 = (xe1 * z1) + (xe2 * z2) ;
|
||||
p1 = (xn1 * z1) + (xn2 * z2) + (xn3 * z3);
|
||||
p2 = (xe1 * z1) + (xe2 * z2);
|
||||
assertm((piAbsd(p1) + piAbsd(p2)) >= 1.0e-16, "azAngle(), failed p1+p2 test");
|
||||
alpha = 90 - toDeg(atan2(p1, p2));
|
||||
if (alpha < 0) return alpha + 360;
|
||||
else return alpha;
|
||||
if (alpha < 0)
|
||||
return alpha + 360;
|
||||
else
|
||||
return alpha;
|
||||
}
|
||||
|
||||
|
||||
double PIGeoPosition::azimuthGeodetic(const PIGeoPosition &p) const {
|
||||
double PIGeoPosition::azimuthGeodetic(const PIGeoPosition & p) const {
|
||||
PIGeoPosition r(*this), s(p);
|
||||
double lat = toRad(r.latitudeGeodetic());
|
||||
double lng = toRad(r.longitude());
|
||||
@@ -533,8 +556,10 @@ double PIGeoPosition::azimuthGeodetic(const PIGeoPosition &p) const {
|
||||
double test = piAbsd(local_n) + piAbsd(local_e); // Let's test if computing azimuth has any sense
|
||||
if (test < 1.0e-16) return 0.0; // Warning: If elevation is very close to 90 degrees, we will return azimuth = 0.0
|
||||
double alpha = toDeg(atan2(local_e, local_n));
|
||||
if (alpha < 0.0) return alpha + 360.0;
|
||||
else return alpha;
|
||||
if (alpha < 0.0)
|
||||
return alpha + 360.0;
|
||||
else
|
||||
return alpha;
|
||||
}
|
||||
|
||||
double PIGeoPosition::getCurvMeridian() const {
|
||||
@@ -548,4 +573,3 @@ double PIGeoPosition::getCurvPrimeVertical() const {
|
||||
double slat = sin(toRad(latitudeGeodetic()));
|
||||
return el.a / sqrt(1.0 - el.eccSquared() * slat * slat);
|
||||
}
|
||||
|
||||
|
||||
@@ -29,34 +29,45 @@
|
||||
#include "piellipsoidmodel.h"
|
||||
#include "pimathvector.h"
|
||||
|
||||
class PIP_EXPORT PIGeoPosition : public PIMathVectorT3d
|
||||
{
|
||||
class PIP_EXPORT PIGeoPosition: public PIMathVectorT3d {
|
||||
public:
|
||||
|
||||
enum CoordinateSystem {
|
||||
Unknown=0, /// Unknown coordinate system
|
||||
Unknown = 0, /// Unknown coordinate system
|
||||
Geodetic, /// Geodetic latitude, longitude, and height above ellipsoid
|
||||
Geocentric, /// Geocentric (regular spherical coordinates)
|
||||
Cartesian, /// Cartesian (Earth-centered, Earth-fixed)
|
||||
Spherical /// Spherical coordinates (theta,phi,radius)
|
||||
};
|
||||
|
||||
static const double one_cm_tolerance;/// One centimeter tolerance.
|
||||
static const double one_mm_tolerance;/// One millimeter tolerance.
|
||||
static const double one_um_tolerance;/// One micron tolerance.
|
||||
static double position_tolerance;/// Default tolerance (default 1mm)
|
||||
static double setPositionTolerance(const double tol) {position_tolerance = tol; return position_tolerance;}
|
||||
static double getPositionTolerance() {return position_tolerance;}
|
||||
static const double one_cm_tolerance; /// One centimeter tolerance.
|
||||
static const double one_mm_tolerance; /// One millimeter tolerance.
|
||||
static const double one_um_tolerance; /// One micron tolerance.
|
||||
static double position_tolerance; /// Default tolerance (default 1mm)
|
||||
static double setPositionTolerance(const double tol) {
|
||||
position_tolerance = tol;
|
||||
return position_tolerance;
|
||||
}
|
||||
static double getPositionTolerance() { return position_tolerance; }
|
||||
|
||||
PIGeoPosition();
|
||||
PIGeoPosition(double a, double b, double c, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
PIGeoPosition(PIMathVectorT3d v, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
|
||||
PIGeoPosition &transformTo(CoordinateSystem sys);
|
||||
PIGeoPosition &asGeodetic() {transformTo(Geodetic); return *this; } /// Convert to geodetic coordinate
|
||||
PIGeoPosition &asGeodetic(const PIEllipsoidModel &ell) {setEllipsoidModel(ell); transformTo(Geodetic); return *this;} /// Convert to another ell, then to geodetic coordinates
|
||||
PIGeoPosition &asECEF() {transformTo(Cartesian); return *this; } /// Convert to cartesian coordinates
|
||||
PIGeoPosition & transformTo(CoordinateSystem sys);
|
||||
PIGeoPosition & asGeodetic() {
|
||||
transformTo(Geodetic);
|
||||
return *this;
|
||||
} /// Convert to geodetic coordinate
|
||||
PIGeoPosition & asGeodetic(const PIEllipsoidModel & ell) {
|
||||
setEllipsoidModel(ell);
|
||||
transformTo(Geodetic);
|
||||
return *this;
|
||||
} /// Convert to another ell, then to geodetic coordinates
|
||||
PIGeoPosition & asECEF() {
|
||||
transformTo(Cartesian);
|
||||
return *this;
|
||||
} /// Convert to cartesian coordinates
|
||||
|
||||
double x() const;
|
||||
double y() const;
|
||||
@@ -70,43 +81,51 @@ public:
|
||||
double height() const;
|
||||
|
||||
/// Set the ellipsoid values for this PIGeoPosition given a ellipsoid.
|
||||
void setEllipsoidModel(const PIEllipsoidModel &ell) {el = ell;}
|
||||
void setEllipsoidModel(const PIEllipsoidModel & ell) { el = ell; }
|
||||
|
||||
/// Set the \a PIGeoPosition given geodetic coordinates in degrees. \a CoordinateSystem is set to \a Geodetic.
|
||||
PIGeoPosition &setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
PIGeoPosition & setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
/// Set the \a PIGeoPosition given geocentric coordinates in degrees. \a CoordinateSystem is set to \a Geocentric
|
||||
PIGeoPosition &setGeocentric(double lat, double lon, double rad);
|
||||
PIGeoPosition & setGeocentric(double lat, double lon, double rad);
|
||||
|
||||
/// Set the \a PIGeoPosition given spherical coordinates in degrees. \a CoordinateSystem is set to \a Spherical
|
||||
PIGeoPosition &setSpherical(double theta, double phi, double rad);
|
||||
PIGeoPosition & setSpherical(double theta, double phi, double rad);
|
||||
|
||||
/// Set the \a PIGeoPosition given ECEF coordinates in meeters. \a CoordinateSystem is set to \a Cartesian.
|
||||
PIGeoPosition &setECEF(double x, double y, double z);
|
||||
PIGeoPosition & setECEF(double x, double y, double z);
|
||||
|
||||
/// Fundamental conversion from spherical to cartesian coordinates.
|
||||
static void convertSphericalToCartesian(const PIMathVectorT3d &tpr, PIMathVectorT3d &xyz);
|
||||
static void convertSphericalToCartesian(const PIMathVectorT3d & tpr, PIMathVectorT3d & xyz);
|
||||
|
||||
/// Fundamental routine to convert cartesian to spherical coordinates.
|
||||
static void convertCartesianToSpherical(const PIMathVectorT3d &xyz, PIMathVectorT3d &tpr);
|
||||
static void convertCartesianToSpherical(const PIMathVectorT3d & xyz, PIMathVectorT3d & tpr);
|
||||
|
||||
/// Fundamental routine to convert ECEF (cartesian) to geodetic coordinates,
|
||||
static void convertCartesianToGeodetic(const PIMathVectorT3d &xyz, PIMathVectorT3d &llh, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
static void convertCartesianToGeodetic(const PIMathVectorT3d & xyz,
|
||||
PIMathVectorT3d & llh,
|
||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
/// Fundamental routine to convert geodetic to ECEF (cartesian) coordinates,
|
||||
static void convertGeodeticToCartesian(const PIMathVectorT3d &llh, PIMathVectorT3d &xyz, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
static void convertGeodeticToCartesian(const PIMathVectorT3d & llh,
|
||||
PIMathVectorT3d & xyz,
|
||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
/// Fundamental routine to convert cartesian (ECEF) to geocentric
|
||||
static void convertCartesianToGeocentric(const PIMathVectorT3d &xyz, PIMathVectorT3d &llr);
|
||||
static void convertCartesianToGeocentric(const PIMathVectorT3d & xyz, PIMathVectorT3d & llr);
|
||||
|
||||
/// Fundamental routine to convert geocentric to cartesian (ECEF)
|
||||
static void convertGeocentricToCartesian(const PIMathVectorT3d &llr, PIMathVectorT3d &xyz);
|
||||
static void convertGeocentricToCartesian(const PIMathVectorT3d & llr, PIMathVectorT3d & xyz);
|
||||
|
||||
/// Fundamental routine to convert geocentric to geodetic
|
||||
static void convertGeocentricToGeodetic(const PIMathVectorT3d &llr, PIMathVectorT3d &llh, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
static void convertGeocentricToGeodetic(const PIMathVectorT3d & llr,
|
||||
PIMathVectorT3d & llh,
|
||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
/// Fundamental routine to convert geodetic to geocentric
|
||||
static void convertGeodeticToGeocentric(const PIMathVectorT3d &llh, PIMathVectorT3d &llr, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
static void convertGeodeticToGeocentric(const PIMathVectorT3d & llh,
|
||||
PIMathVectorT3d & llr,
|
||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
|
||||
/// Compute the radius of the ellipsoidal Earth, given the geodetic latitude.
|
||||
static double radiusEarth(double geolat, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||
@@ -117,22 +136,20 @@ public:
|
||||
}
|
||||
|
||||
/// Compute the range in meters between two PIGeoPositions.
|
||||
static double range(const PIGeoPosition &a, const PIGeoPosition &b);
|
||||
double range(const PIGeoPosition &p) const {
|
||||
return range((*this), p);
|
||||
}
|
||||
static double range(const PIGeoPosition & a, const PIGeoPosition & b);
|
||||
double range(const PIGeoPosition & p) const { return range((*this), p); }
|
||||
|
||||
/// Computes the elevation of the input (p) position as seen from this PIGeoPosition.
|
||||
double elevation(const PIGeoPosition &p) const;
|
||||
double elevation(const PIGeoPosition & p) const;
|
||||
|
||||
/// Computes the elevation of the input (p) position as seen from this PIGeoPosition, using a Geodetic (ellipsoidal) system.
|
||||
double elevationGeodetic(const PIGeoPosition &p) const;
|
||||
double elevationGeodetic(const PIGeoPosition & p) const;
|
||||
|
||||
/// Computes the azimuth of the input (p) position as seen from this PIGeoPosition.
|
||||
double azimuth(const PIGeoPosition &p) const;
|
||||
double azimuth(const PIGeoPosition & p) const;
|
||||
|
||||
/// Computes the azimuth of the input (p) position as seen from this PIGeoPosition, using a Geodetic (ellipsoidal) system.
|
||||
double azimuthGeodetic(const PIGeoPosition &p) const;
|
||||
double azimuthGeodetic(const PIGeoPosition & p) const;
|
||||
|
||||
/// Computes the radius of curvature of the meridian (Rm) corresponding to this PIGeoPosition.
|
||||
double getCurvMeridian() const;
|
||||
@@ -141,19 +158,19 @@ public:
|
||||
double getCurvPrimeVertical() const;
|
||||
|
||||
/// Returns as PIMathVectorT3d
|
||||
const PIMathVectorT3d & vector() const {return *this;}
|
||||
const PIMathVectorT3d & vector() const { return *this; }
|
||||
|
||||
PIGeoPosition &operator=(const PIMathVectorT3d & v);
|
||||
PIGeoPosition &operator-=(const PIGeoPosition &right);
|
||||
PIGeoPosition &operator+=(const PIGeoPosition &right);
|
||||
friend PIGeoPosition operator-(const PIGeoPosition &left, const PIGeoPosition &right);
|
||||
friend PIGeoPosition operator+(const PIGeoPosition &left, const PIGeoPosition &right);
|
||||
friend PIGeoPosition operator*(const double &scale, const PIGeoPosition &right);
|
||||
friend PIGeoPosition operator*(const PIGeoPosition &left, const double &scale);
|
||||
friend PIGeoPosition operator*(const int &scale, const PIGeoPosition &right);
|
||||
friend PIGeoPosition operator*(const PIGeoPosition &left, const int &scale);
|
||||
bool operator==(const PIGeoPosition &right) const;
|
||||
bool operator!=(const PIGeoPosition &right) const {return !(operator==(right));}
|
||||
PIGeoPosition & operator=(const PIMathVectorT3d & v);
|
||||
PIGeoPosition & operator-=(const PIGeoPosition & right);
|
||||
PIGeoPosition & operator+=(const PIGeoPosition & right);
|
||||
friend PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right);
|
||||
friend PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right);
|
||||
friend PIGeoPosition operator*(const double & scale, const PIGeoPosition & right);
|
||||
friend PIGeoPosition operator*(const PIGeoPosition & left, const double & scale);
|
||||
friend PIGeoPosition operator*(const int & scale, const PIGeoPosition & right);
|
||||
friend PIGeoPosition operator*(const PIGeoPosition & left, const int & scale);
|
||||
bool operator==(const PIGeoPosition & right) const;
|
||||
bool operator!=(const PIGeoPosition & right) const { return !(operator==(right)); }
|
||||
|
||||
|
||||
private:
|
||||
@@ -161,15 +178,36 @@ private:
|
||||
|
||||
PIEllipsoidModel el;
|
||||
CoordinateSystem s;
|
||||
|
||||
};
|
||||
|
||||
|
||||
inline PIGeoPosition operator-(const PIGeoPosition &left, const PIGeoPosition &right) {PIGeoPosition l(left),r(right); l.transformTo(PIGeoPosition::Cartesian); r.transformTo(PIGeoPosition::Cartesian); l -= r; return l;}
|
||||
inline PIGeoPosition operator+(const PIGeoPosition &left, const PIGeoPosition &right) {PIGeoPosition l(left),r(right); l.transformTo(PIGeoPosition::Cartesian); r.transformTo(PIGeoPosition::Cartesian); l += r; return l;}
|
||||
inline PIGeoPosition operator*(const double &scale, const PIGeoPosition &right) {PIMathVectorT3d tmp(right); tmp *= scale; return PIGeoPosition(tmp);}
|
||||
inline PIGeoPosition operator*(const PIGeoPosition &left, const double &scale) {return operator* (scale, left);}
|
||||
inline PIGeoPosition operator*(const int &scale, const PIGeoPosition &right) {return operator* (double(scale), right);}
|
||||
inline PIGeoPosition operator*(const PIGeoPosition &left, const int &scale) {return operator* (double(scale), left);}
|
||||
inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||
PIGeoPosition l(left), r(right);
|
||||
l.transformTo(PIGeoPosition::Cartesian);
|
||||
r.transformTo(PIGeoPosition::Cartesian);
|
||||
l -= r;
|
||||
return l;
|
||||
}
|
||||
inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||
PIGeoPosition l(left), r(right);
|
||||
l.transformTo(PIGeoPosition::Cartesian);
|
||||
r.transformTo(PIGeoPosition::Cartesian);
|
||||
l += r;
|
||||
return l;
|
||||
}
|
||||
inline PIGeoPosition operator*(const double & scale, const PIGeoPosition & right) {
|
||||
PIMathVectorT3d tmp(right);
|
||||
tmp *= scale;
|
||||
return PIGeoPosition(tmp);
|
||||
}
|
||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const double & scale) {
|
||||
return operator*(scale, left);
|
||||
}
|
||||
inline PIGeoPosition operator*(const int & scale, const PIGeoPosition & right) {
|
||||
return operator*(double(scale), right);
|
||||
}
|
||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const int & scale) {
|
||||
return operator*(double(scale), left);
|
||||
}
|
||||
|
||||
#endif // PIGEOPOSITION_H
|
||||
|
||||
@@ -61,13 +61,12 @@ class PIIntrospection;
|
||||
class PIIntrospectionServer;
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
#define __PIINTROSPECTION_SINGLETON_H__(T) \
|
||||
static PIIntrospection##T##Interface * instance();
|
||||
# define __PIINTROSPECTION_SINGLETON_H__(T) static PIIntrospection##T##Interface * instance();
|
||||
|
||||
#define __PIINTROSPECTION_SINGLETON_CPP__(T) \
|
||||
PIIntrospection##T##Interface * PIIntrospection##T##Interface::instance() {\
|
||||
static PIIntrospection##T##Interface ret;\
|
||||
return &ret;\
|
||||
# define __PIINTROSPECTION_SINGLETON_CPP__(T) \
|
||||
PIIntrospection##T##Interface * PIIntrospection##T##Interface::instance() { \
|
||||
static PIIntrospection##T##Interface ret; \
|
||||
return &ret; \
|
||||
}
|
||||
#endif // PIP_INTROSPECTION
|
||||
#endif // PIINTROSPECTION_BASE_H
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
|
||||
PIIntrospectionContainersType::~PIIntrospectionContainersType() {
|
||||
if (has_demangled) {
|
||||
//free((void*)demangled);
|
||||
// free((void*)demangled);
|
||||
has_demangled = false;
|
||||
}
|
||||
}
|
||||
@@ -29,11 +29,11 @@ PIIntrospectionContainersType::~PIIntrospectionContainersType() {
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
#include "piintrospection_containers_p.h"
|
||||
# include "piintrospection_containers_p.h"
|
||||
|
||||
__PIINTROSPECTION_SINGLETON_CPP__(Containers)
|
||||
|
||||
#ifdef CC_GCC
|
||||
# ifdef CC_GCC
|
||||
# include <cxxabi.h>
|
||||
const char * demangle(const char * name) {
|
||||
int status = -4;
|
||||
@@ -41,9 +41,11 @@ const char * demangle(const char * name) {
|
||||
if (status == 0) return res;
|
||||
return name;
|
||||
}
|
||||
#else
|
||||
const char * demangle(const char * name) {return name;}
|
||||
#endif
|
||||
# else
|
||||
const char * demangle(const char * name) {
|
||||
return name;
|
||||
}
|
||||
# endif
|
||||
|
||||
|
||||
void PIIntrospectionContainersType::finish() {
|
||||
@@ -53,11 +55,10 @@ void PIIntrospectionContainersType::finish() {
|
||||
return;
|
||||
}
|
||||
size_t l = strlen(name);
|
||||
if (l > 0)
|
||||
id = piHashData((const uchar*)name, int(l));
|
||||
if (l > 0) id = piHashData((const uchar *)name, int(l));
|
||||
demangled = demangle(name);
|
||||
has_demangled = name != demangled;
|
||||
//printf("create typeinfo for %s -> %s\n", name, demangled);
|
||||
// printf("create typeinfo for %s -> %s\n", name, demangled);
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -58,11 +58,11 @@ private:
|
||||
# define PIINTROSPECTION_CONTAINERS (PIIntrospectionContainersInterface::instance())
|
||||
|
||||
// clang-format off
|
||||
# define PIINTROSPECTION_CONTAINER_NEW (t, isz) PIINTROSPECTION_CONTAINERS->containerNew (PIIntrospectionContainersTypeInfo<t>::get(), isz);
|
||||
# define PIINTROSPECTION_CONTAINER_DELETE(t ) PIINTROSPECTION_CONTAINERS->containerDelete(PIIntrospectionContainersTypeInfo<t>::get() );
|
||||
# define PIINTROSPECTION_CONTAINER_ALLOC (t, cnt) PIINTROSPECTION_CONTAINERS->containerAlloc (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_FREE (t, cnt) PIINTROSPECTION_CONTAINERS->containerFree (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_USED (t, cnt) PIINTROSPECTION_CONTAINERS->containerUsed (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_NEW(t, isz) PIINTROSPECTION_CONTAINERS->containerNew (PIIntrospectionContainersTypeInfo<t>::get(), isz);
|
||||
# define PIINTROSPECTION_CONTAINER_DELETE(t) PIINTROSPECTION_CONTAINERS->containerDelete(PIIntrospectionContainersTypeInfo<t>::get() );
|
||||
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt) PIINTROSPECTION_CONTAINERS->containerAlloc (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt) PIINTROSPECTION_CONTAINERS->containerFree (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_USED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUsed (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUnused(PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||
// clang-format on
|
||||
|
||||
|
||||
@@ -18,18 +18,20 @@
|
||||
*/
|
||||
|
||||
#include "piintrospection_containers_p.h"
|
||||
|
||||
#include "piintrospection_containers.h"
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
|
||||
PIIntrospectionContainers::PIIntrospectionContainers() {
|
||||
//printf("PIIntrospectionContainers %p\n", this);
|
||||
// printf("PIIntrospectionContainers %p\n", this);
|
||||
}
|
||||
|
||||
|
||||
void PIIntrospectionContainers::containerNew(const PIIntrospectionContainersType & ti, uint isz) {
|
||||
PISpinlockLocker _ml(mutex);
|
||||
//printf("containerNew lock\n");
|
||||
// printf("containerNew lock\n");
|
||||
PIIntrospectionContainersType & t(types[ti.id]);
|
||||
_Type & d(data[ti.id]);
|
||||
if (!t.inited) {
|
||||
@@ -38,7 +40,7 @@ void PIIntrospectionContainers::containerNew(const PIIntrospectionContainersType
|
||||
d.item_size = isz;
|
||||
}
|
||||
d.count++;
|
||||
//printf("containerNew unlock\n");
|
||||
// printf("containerNew unlock\n");
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +51,7 @@ void PIIntrospectionContainers::containerDelete(const PIIntrospectionContainersT
|
||||
|
||||
|
||||
void PIIntrospectionContainers::containerAlloc(const PIIntrospectionContainersType & ti, ullong cnt) {
|
||||
//printf(" alloc %s %d\n", tn, cnt);
|
||||
// printf(" alloc %s %d\n", tn, cnt);
|
||||
if (cnt == 0) return;
|
||||
PISpinlockLocker _ml(mutex);
|
||||
data[ti.id].allocated += cnt;
|
||||
@@ -57,7 +59,7 @@ void PIIntrospectionContainers::containerAlloc(const PIIntrospectionContainersTy
|
||||
|
||||
|
||||
void PIIntrospectionContainers::containerFree(const PIIntrospectionContainersType & ti, ullong cnt) {
|
||||
//printf(" free %s %d\n", tn, cnt);
|
||||
// printf(" free %s %d\n", tn, cnt);
|
||||
if (cnt == 0) return;
|
||||
PISpinlockLocker _ml(mutex);
|
||||
data[ti.id].allocated -= cnt;
|
||||
@@ -65,7 +67,7 @@ void PIIntrospectionContainers::containerFree(const PIIntrospectionContainersTyp
|
||||
|
||||
|
||||
void PIIntrospectionContainers::containerUsed(const PIIntrospectionContainersType & ti, ullong cnt) {
|
||||
//printf(" used %s %d\n", tn, cnt);
|
||||
// printf(" used %s %d\n", tn, cnt);
|
||||
if (cnt == 0) return;
|
||||
PISpinlockLocker _ml(mutex);
|
||||
data[ti.id].used += cnt;
|
||||
@@ -73,7 +75,7 @@ void PIIntrospectionContainers::containerUsed(const PIIntrospectionContainersTyp
|
||||
|
||||
|
||||
void PIIntrospectionContainers::containerUnused(const PIIntrospectionContainersType & ti, ullong cnt) {
|
||||
//printf("unused %s %d\n", tn, cnt);
|
||||
// printf("unused %s %d\n", tn, cnt);
|
||||
if (cnt == 0) return;
|
||||
PISpinlockLocker _ml(mutex);
|
||||
data[ti.id].used -= cnt;
|
||||
@@ -91,7 +93,7 @@ PIVector<PIIntrospectionContainers::TypeInfo> PIIntrospectionContainers::getInfo
|
||||
ret.push_back(TypeInfo());
|
||||
TypeInfo & ti(ret.back());
|
||||
_Type & _t(d[i->first]);
|
||||
memcpy((void*)&ti, (const void*)&_t, sizeof(_t));
|
||||
memcpy((void *)&ti, (const void *)&_t, sizeof(_t));
|
||||
ti.name = PIStringAscii(i->second.demangled);
|
||||
}
|
||||
return ret;
|
||||
|
||||
@@ -19,10 +19,11 @@
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
#include "piintrospection_server.h"
|
||||
#include "piintrospection_server_p.h"
|
||||
#include "piprocess.h"
|
||||
#include "pichunkstream.h"
|
||||
# include "piintrospection_server.h"
|
||||
|
||||
# include "pichunkstream.h"
|
||||
# include "piintrospection_server_p.h"
|
||||
# include "piprocess.h"
|
||||
|
||||
|
||||
PRIVATE_DEFINITION_START(PIIntrospectionServer)
|
||||
@@ -39,8 +40,7 @@ PIIntrospectionServer::PIIntrospectionServer(): PIPeer(genName()) {
|
||||
PIIntrospectionServer::~PIIntrospectionServer() {
|
||||
PIPeer::stop();
|
||||
if (sysmon)
|
||||
if (sysmon->property("__iserver__").toBool())
|
||||
delete sysmon;
|
||||
if (sysmon->property("__iserver__").toBool()) delete sysmon;
|
||||
sysmon = 0;
|
||||
}
|
||||
|
||||
@@ -78,24 +78,21 @@ PIString PIIntrospectionServer::genName() {
|
||||
void PIIntrospectionServer::dataReceived(const PIString & from, const PIByteArray & data) {
|
||||
if (data.size() < 8) return;
|
||||
PIByteArray rba(data);
|
||||
uint _sign(0); rba >> _sign;
|
||||
uint _sign(0);
|
||||
rba >> _sign;
|
||||
if (_sign != PIIntrospection::sign) return;
|
||||
PIIntrospection::RequiredInfo ri;
|
||||
rba >> ri;
|
||||
PIChunkStream cs;
|
||||
if (ri.types[PIIntrospection::itInfo])
|
||||
cs.add(PIIntrospection::itInfo, PIIntrospection::packInfo());
|
||||
if (ri.types[PIIntrospection::itInfo]) cs.add(PIIntrospection::itInfo, PIIntrospection::packInfo());
|
||||
if (ri.types[PIIntrospection::itProcStat]) {
|
||||
sysmon_mutex.lock();
|
||||
cs.add(PIIntrospection::itProcStat, PIIntrospection::packProcStat(sysmon));
|
||||
sysmon_mutex.unlock();
|
||||
}
|
||||
if (ri.types[PIIntrospection::itContainers])
|
||||
cs.add(PIIntrospection::itContainers, PIIntrospection::packContainers());
|
||||
if (ri.types[PIIntrospection::itObjects])
|
||||
cs.add(PIIntrospection::itObjects, PIIntrospection::packObjects());
|
||||
if (ri.types[PIIntrospection::itThreads])
|
||||
cs.add(PIIntrospection::itThreads, PIIntrospection::packThreads());
|
||||
if (ri.types[PIIntrospection::itContainers]) cs.add(PIIntrospection::itContainers, PIIntrospection::packContainers());
|
||||
if (ri.types[PIIntrospection::itObjects]) cs.add(PIIntrospection::itObjects, PIIntrospection::packObjects());
|
||||
if (ri.types[PIIntrospection::itThreads]) cs.add(PIIntrospection::itThreads, PIIntrospection::packThreads());
|
||||
PIByteArray ba;
|
||||
ba << PIIntrospection::sign;
|
||||
ba.append(cs.data());
|
||||
|
||||
@@ -37,7 +37,7 @@
|
||||
|
||||
# if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
#include "pipeer.h"
|
||||
# include "pipeer.h"
|
||||
|
||||
class PIIntrospectionServer;
|
||||
class PISystemMonitor;
|
||||
@@ -47,6 +47,7 @@ class PISystemMonitor;
|
||||
|
||||
class PIP_EXPORT PIIntrospectionServer: public PIPeer {
|
||||
PIOBJECT_SUBCLASS(PIIntrospectionServer, PIPeer);
|
||||
|
||||
public:
|
||||
static PIIntrospectionServer * instance();
|
||||
|
||||
@@ -65,7 +66,6 @@ private:
|
||||
PITimer itimer;
|
||||
PISystemMonitor * sysmon;
|
||||
PIMutex sysmon_mutex;
|
||||
|
||||
};
|
||||
|
||||
# else
|
||||
|
||||
@@ -18,10 +18,11 @@
|
||||
*/
|
||||
|
||||
#include "piintrospection_server_p.h"
|
||||
|
||||
#include "pichunkstream.h"
|
||||
#include "piinit.h"
|
||||
#include "pisysteminfo.h"
|
||||
#include "piobject.h"
|
||||
#include "pisysteminfo.h"
|
||||
|
||||
|
||||
const uint PIIntrospection::sign = 0x0F1C2B3A;
|
||||
@@ -61,12 +62,12 @@ PIIntrospection::ProcessInfo PIIntrospection::getInfo() {
|
||||
PIVector<PIIntrospection::ObjectInfo> PIIntrospection::getObjects() {
|
||||
PIVector<PIIntrospection::ObjectInfo> ret;
|
||||
PIObject::mutexObjects().lock();
|
||||
const PIVector<PIObject * > & ao(PIObject::objects());
|
||||
const PIVector<PIObject *> & ao(PIObject::objects());
|
||||
ret.resize(ao.size());
|
||||
for (int i = 0; i < ao.size_s(); ++i) {
|
||||
ret[i].classname = PIStringAscii(ao[i]->className());
|
||||
ret[i].name = ao[i]->name();
|
||||
//ret[i].properties = ao[i]->properties();
|
||||
// ret[i].properties = ao[i]->properties();
|
||||
ret[i].parents = ao[i]->scopeList();
|
||||
ao[i]->mutex_queue.lock();
|
||||
ret[i].queued_events = ao[i]->events_queue.size_s();
|
||||
@@ -77,8 +78,6 @@ PIVector<PIIntrospection::ObjectInfo> PIIntrospection::getObjects() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
PIByteArray PIIntrospection::packInfo() {
|
||||
PIByteArray ret;
|
||||
ret << getInfo();
|
||||
@@ -137,7 +136,7 @@ PIByteArray PIIntrospection::packThreads() {
|
||||
#endif
|
||||
if (p) {
|
||||
p->mutex.lock();
|
||||
PIMap<PIThread*, PIIntrospectionThreads::ThreadInfo> & tm(p->threads);
|
||||
PIMap<PIThread *, PIIntrospectionThreads::ThreadInfo> & tm(p->threads);
|
||||
auto it = tm.makeIterator();
|
||||
while (it.next()) {
|
||||
it.value().classname = PIStringAscii(it.key()->className());
|
||||
|
||||
@@ -20,17 +20,16 @@
|
||||
#ifndef PIINTROSPECTION_SERVER_P_H
|
||||
#define PIINTROSPECTION_SERVER_P_H
|
||||
|
||||
#include "pichunkstream.h"
|
||||
#include "piintrospection_containers.h"
|
||||
#include "piintrospection_containers_p.h"
|
||||
#include "piintrospection_threads.h"
|
||||
#include "piintrospection_threads_p.h"
|
||||
#include "pichunkstream.h"
|
||||
#include "pisystemmonitor.h"
|
||||
|
||||
|
||||
class PIP_EXPORT PIIntrospection {
|
||||
public:
|
||||
|
||||
enum InfoTypes {
|
||||
itInfo = 0x01,
|
||||
itProcStat = 0x02,
|
||||
@@ -89,7 +88,6 @@ public:
|
||||
|
||||
static PIByteArray packObjects();
|
||||
static void unpackObjects(PIByteArray & ba, PIVector<PIIntrospection::ObjectInfo> & objects);
|
||||
|
||||
};
|
||||
|
||||
|
||||
@@ -100,7 +98,8 @@ BINARY_STREAM_WRITE(PIIntrospection::RequiredInfo) {
|
||||
return s;
|
||||
}
|
||||
BINARY_STREAM_READ(PIIntrospection::RequiredInfo) {
|
||||
PIByteArray csba; s >> csba;
|
||||
PIByteArray csba;
|
||||
s >> csba;
|
||||
PIChunkStream cs(csba);
|
||||
while (!cs.atEnd()) {
|
||||
switch (cs.read()) {
|
||||
@@ -113,13 +112,21 @@ BINARY_STREAM_READ(PIIntrospection::RequiredInfo) {
|
||||
|
||||
BINARY_STREAM_WRITE(PIIntrospection::ProcessInfo) {
|
||||
PIChunkStream cs;
|
||||
cs.add(1, v.architecture).add(2, v.execCommand).add(3, v.execDateTime).add(4, v.hostname).add(5, v.OS_name)
|
||||
.add(6, v.OS_version).add(7, v.processorsCount).add(8, v.user).add(9, v.build_options);
|
||||
cs.add(1, v.architecture)
|
||||
.add(2, v.execCommand)
|
||||
.add(3, v.execDateTime)
|
||||
.add(4, v.hostname)
|
||||
.add(5, v.OS_name)
|
||||
.add(6, v.OS_version)
|
||||
.add(7, v.processorsCount)
|
||||
.add(8, v.user)
|
||||
.add(9, v.build_options);
|
||||
s << cs.data();
|
||||
return s;
|
||||
}
|
||||
BINARY_STREAM_READ(PIIntrospection::ProcessInfo) {
|
||||
PIByteArray csba; s >> csba;
|
||||
PIByteArray csba;
|
||||
s >> csba;
|
||||
PIChunkStream cs(csba);
|
||||
while (!cs.atEnd()) {
|
||||
switch (cs.read()) {
|
||||
@@ -145,7 +152,8 @@ BINARY_STREAM_WRITE(PIIntrospection::ObjectInfo) {
|
||||
return s;
|
||||
}
|
||||
BINARY_STREAM_READ(PIIntrospection::ObjectInfo) {
|
||||
PIByteArray csba; s >> csba;
|
||||
PIByteArray csba;
|
||||
s >> csba;
|
||||
PIChunkStream cs(csba);
|
||||
while (!cs.atEnd()) {
|
||||
switch (cs.read()) {
|
||||
|
||||
@@ -19,8 +19,9 @@
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
#include "piintrospection_threads.h"
|
||||
#include "piintrospection_threads_p.h"
|
||||
# include "piintrospection_threads.h"
|
||||
|
||||
# include "piintrospection_threads_p.h"
|
||||
|
||||
__PIINTROSPECTION_SINGLETON_CPP__(Threads)
|
||||
|
||||
|
||||
@@ -28,15 +28,13 @@ class PIIntrospectionThreads;
|
||||
|
||||
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
|
||||
|
||||
// clang-format off
|
||||
# define PIINTROSPECTION_THREAD_NEW (t ) PIINTROSPECTION_THREADS->threadNew (t );
|
||||
# define PIINTROSPECTION_THREAD_DELETE (t ) PIINTROSPECTION_THREADS->threadDelete (t );
|
||||
# define PIINTROSPECTION_THREAD_START (t ) PIINTROSPECTION_THREADS->threadStart (t );
|
||||
# define PIINTROSPECTION_THREAD_RUN (t ) PIINTROSPECTION_THREADS->threadRun (t );
|
||||
# define PIINTROSPECTION_THREAD_WAIT (t ) PIINTROSPECTION_THREADS->threadWait (t );
|
||||
# define PIINTROSPECTION_THREAD_STOP (t ) PIINTROSPECTION_THREADS->threadStop (t );
|
||||
# define PIINTROSPECTION_THREAD_RUN_DONE(t,us) PIINTROSPECTION_THREADS->threadRunDone(t,us);
|
||||
// clang-format on
|
||||
# define PIINTROSPECTION_THREAD_NEW(t) PIINTROSPECTION_THREADS->threadNew(t);
|
||||
# define PIINTROSPECTION_THREAD_DELETE(t) PIINTROSPECTION_THREADS->threadDelete(t);
|
||||
# define PIINTROSPECTION_THREAD_START(t) PIINTROSPECTION_THREADS->threadStart(t);
|
||||
# define PIINTROSPECTION_THREAD_RUN(t) PIINTROSPECTION_THREADS->threadRun(t);
|
||||
# define PIINTROSPECTION_THREAD_WAIT(t) PIINTROSPECTION_THREADS->threadWait(t);
|
||||
# define PIINTROSPECTION_THREAD_STOP(t) PIINTROSPECTION_THREADS->threadStop(t);
|
||||
# define PIINTROSPECTION_THREAD_RUN_DONE(t, us) PIINTROSPECTION_THREADS->threadRunDone(t, us);
|
||||
|
||||
class PIP_EXPORT PIIntrospectionThreadsInterface {
|
||||
friend class PIIntrospection;
|
||||
|
||||
@@ -28,10 +28,7 @@ PIIntrospectionThreads::ThreadInfo::ThreadInfo() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
PIIntrospectionThreads::PIIntrospectionThreads() {
|
||||
}
|
||||
PIIntrospectionThreads::PIIntrospectionThreads() {}
|
||||
|
||||
|
||||
void PIIntrospectionThreads::threadNew(PIThread * t) {
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
#include "pibinarylog.h"
|
||||
|
||||
#include "pidir.h"
|
||||
#include "pipropertystorage.h"
|
||||
|
||||
@@ -45,7 +46,7 @@
|
||||
*
|
||||
*/
|
||||
|
||||
static const uchar binlog_sig[] = {'B','I','N','L','O','G'};
|
||||
static const uchar binlog_sig[] = {'B', 'I', 'N', 'L', 'O', 'G'};
|
||||
|
||||
#define PIBINARYLOG_VERSION 0x32
|
||||
#define PIBINARYLOG_SIGNATURE_SIZE sizeof(binlog_sig)
|
||||
@@ -75,7 +76,7 @@ PIBinaryLog::PIBinaryLog() {
|
||||
setFilePrefix(PIString());
|
||||
setRapidStart(false);
|
||||
file.setName("__S__PIBinaryLog::file");
|
||||
// piCoutObj << "created";
|
||||
// piCoutObj << "created";
|
||||
}
|
||||
|
||||
|
||||
@@ -101,14 +102,16 @@ bool PIBinaryLog::openDevice() {
|
||||
return false;
|
||||
}
|
||||
if (path().isEmpty() && mode_ == WriteOnly) {
|
||||
if (f_new_path) setPath(f_new_path());
|
||||
else setPath(getLogfilePath(logDir(), filePrefix()));
|
||||
if (f_new_path)
|
||||
setPath(f_new_path());
|
||||
else
|
||||
setPath(getLogfilePath(logDir(), filePrefix()));
|
||||
}
|
||||
if (path().isEmpty() && mode_ == ReadOnly) {
|
||||
PIDir ld(logDir());
|
||||
if (ld.isExists()) {
|
||||
PIVector<PIFile::FileInfo> es = ld.allEntries();
|
||||
piForeachC(PIFile::FileInfo &i, es) {
|
||||
piForeachC(PIFile::FileInfo & i, es) {
|
||||
if (i.extension() == "binlog" && i.isFile() && i.baseName().startsWith(filePrefix())) {
|
||||
setPath(i.path);
|
||||
break;
|
||||
@@ -170,8 +173,8 @@ bool PIBinaryLog::closeDevice() {
|
||||
}
|
||||
|
||||
|
||||
bool PIBinaryLog::threadedRead(const uchar *readed, ssize_t size) {
|
||||
// piCout << "binlog threaded read";
|
||||
bool PIBinaryLog::threadedRead(const uchar * readed, ssize_t size) {
|
||||
// piCout << "binlog threaded read";
|
||||
if (!canRead() || isEnd()) return PIIODevice::threadedRead(readed, size);
|
||||
is_thread_ok = false;
|
||||
logmutex.lock();
|
||||
@@ -192,8 +195,7 @@ bool PIBinaryLog::threadedRead(const uchar *readed, ssize_t size) {
|
||||
pausemutex.unlock();
|
||||
pt = PISystemTime::current() - startlogtime;
|
||||
if (is_started) {
|
||||
if (lastrec_timestamp > pt)
|
||||
(lastrec_timestamp - pt).sleep();
|
||||
if (lastrec_timestamp > pt) (lastrec_timestamp - pt).sleep();
|
||||
} else {
|
||||
startlogtime = PISystemTime::current() - lastrec_timestamp;
|
||||
is_started = true;
|
||||
@@ -201,7 +203,7 @@ bool PIBinaryLog::threadedRead(const uchar *readed, ssize_t size) {
|
||||
break;
|
||||
case PlayVariableSpeed:
|
||||
delay = lastrec_timestamp.toMilliseconds() - play_time;
|
||||
//piCoutObj << "delay" << delay;
|
||||
// piCoutObj << "delay" << delay;
|
||||
double cdelay;
|
||||
int dtc;
|
||||
if (is_started) {
|
||||
@@ -210,34 +212,38 @@ bool PIBinaryLog::threadedRead(const uchar *readed, ssize_t size) {
|
||||
return false;
|
||||
}
|
||||
if (delay > 0) {
|
||||
cdelay = delay * play_speed;// TODO: rewrite with condvar
|
||||
dtc = int(cdelay) / 100;// TODO: rewrite with condvar
|
||||
cdelay = delay * play_speed; // TODO: rewrite with condvar
|
||||
dtc = int(cdelay) / 100; // TODO: rewrite with condvar
|
||||
if (play_speed <= 0.) dtc = 2;
|
||||
//piCout << play_speed << dtc;
|
||||
for (int j=0; j<dtc; j++) {
|
||||
cdelay = delay * play_speed;// TODO: rewrite with condvar
|
||||
dtc = int(cdelay) / 100;// TODO: rewrite with condvar
|
||||
piMSleep(100);// TODO: rewrite with condvar
|
||||
if (play_speed <= 0.) {dtc = 2; j = 0;}
|
||||
//piCout << " " << play_speed << dtc << j;
|
||||
// piCout << play_speed << dtc;
|
||||
for (int j = 0; j < dtc; j++) {
|
||||
cdelay = delay * play_speed; // TODO: rewrite with condvar
|
||||
dtc = int(cdelay) / 100; // TODO: rewrite with condvar
|
||||
piMSleep(100); // TODO: rewrite with condvar
|
||||
if (play_speed <= 0.) {
|
||||
dtc = 2;
|
||||
j = 0;
|
||||
}
|
||||
cdelay = cdelay - dtc*100;// TODO: rewrite with condvar
|
||||
// piCout << " " << play_speed << dtc << j;
|
||||
}
|
||||
cdelay = cdelay - dtc * 100; // TODO: rewrite with condvar
|
||||
PISystemTime::fromMilliseconds(cdelay).sleep();
|
||||
}
|
||||
} else is_started = true;
|
||||
} else
|
||||
is_started = true;
|
||||
play_time = lastrec_timestamp.toMilliseconds();
|
||||
break;
|
||||
case PlayStaticDelay:
|
||||
if (is_started) {
|
||||
if (is_pause) {
|
||||
piMSleep(100);// TODO: rewrite with condvar
|
||||
piMSleep(100); // TODO: rewrite with condvar
|
||||
return false;
|
||||
}
|
||||
play_delay.sleep();
|
||||
} else is_started = true;
|
||||
} else
|
||||
is_started = true;
|
||||
break;
|
||||
default:
|
||||
return false;
|
||||
default: return false;
|
||||
}
|
||||
bool res = PIIODevice::threadedRead(readed, size);
|
||||
is_thread_ok = true;
|
||||
@@ -249,7 +255,8 @@ PIString PIBinaryLog::getLogfilePath(const PIString & log_dir, const PIString &
|
||||
PIDir dir(log_dir);
|
||||
dir.setDir(dir.absolutePath());
|
||||
if (!dir.isExists()) {
|
||||
piCout << "[PIBinaryLog]" << "Creating directory" << dir.path();
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Creating directory" << dir.path();
|
||||
dir.make(true);
|
||||
}
|
||||
PIString npath = log_dir + PIDir::separator + prefix + PIDateTime::current().toString("yyyy_MM_dd__hh_mm_ss");
|
||||
@@ -265,8 +272,10 @@ PIString PIBinaryLog::getLogfilePath(const PIString & log_dir, const PIString &
|
||||
PIString PIBinaryLog::createNewFile() {
|
||||
if (!file.close()) return PIString();
|
||||
PIString cnpath;
|
||||
if (f_new_path) cnpath = f_new_path();
|
||||
else cnpath = getLogfilePath(logDir(), filePrefix());
|
||||
if (f_new_path)
|
||||
cnpath = f_new_path();
|
||||
else
|
||||
cnpath = getLogfilePath(logDir(), filePrefix());
|
||||
if (open(cnpath, PIIODevice::WriteOnly)) {
|
||||
newFile(file.path());
|
||||
return file.path();
|
||||
@@ -276,27 +285,27 @@ PIString PIBinaryLog::createNewFile() {
|
||||
}
|
||||
|
||||
|
||||
void PIBinaryLog::createNewFile(const PIString &path) {
|
||||
void PIBinaryLog::createNewFile(const PIString & path) {
|
||||
if (open(path, PIIODevice::WriteOnly)) {
|
||||
newFile(file.path());
|
||||
}
|
||||
else piCoutObj << "Can't create new file, maybe path" << ("\"" + path + "\"") << "is invalid.";
|
||||
} else
|
||||
piCoutObj << "Can't create new file, maybe path" << ("\"" + path + "\"") << "is invalid.";
|
||||
}
|
||||
|
||||
|
||||
void PIBinaryLog::setPause(bool pause) {
|
||||
pausemutex.lock();
|
||||
is_pause = pause;
|
||||
if (pause) pause_time = PISystemTime::current();
|
||||
if (pause)
|
||||
pause_time = PISystemTime::current();
|
||||
else {
|
||||
if (pause_time > PISystemTime())
|
||||
pause_time = PISystemTime::current() - pause_time;
|
||||
if (pause_time > PISystemTime()) pause_time = PISystemTime::current() - pause_time;
|
||||
}
|
||||
pausemutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
int PIBinaryLog::writeBinLog(int id, const void *data, int size) {
|
||||
int PIBinaryLog::writeBinLog(int id, const void * data, int size) {
|
||||
if (size <= 0 || !canWrite()) return -1;
|
||||
if (id == 0) {
|
||||
piCoutObj << "Error: can`t write with id = 0! Id must be > 0";
|
||||
@@ -323,12 +332,14 @@ int PIBinaryLog::writeBinLog(int id, const void *data, int size) {
|
||||
default: break;
|
||||
}
|
||||
logmutex.unlock();
|
||||
if (res > 0) return size;
|
||||
else return res;
|
||||
if (res > 0)
|
||||
return size;
|
||||
else
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
int PIBinaryLog::writeBinLog_raw(int id, const PISystemTime &time, const void *data, int size) {
|
||||
int PIBinaryLog::writeBinLog_raw(int id, const PISystemTime & time, const void * data, int size) {
|
||||
if (size <= 0 || !canWrite()) return -1;
|
||||
PIByteArray logdata;
|
||||
logdata << id << size << time << PIMemoryBlock(data, size);
|
||||
@@ -338,8 +349,10 @@ int PIBinaryLog::writeBinLog_raw(int id, const PISystemTime &time, const void *d
|
||||
write_count++;
|
||||
log_size = file.size();
|
||||
logmutex.unlock();
|
||||
if (res > 0) return size;
|
||||
else return res;
|
||||
if (res > 0)
|
||||
return size;
|
||||
else
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
@@ -359,7 +372,8 @@ PIByteArray PIBinaryLog::readBinLog(int id, PISystemTime * time, int * readed_id
|
||||
return br.data;
|
||||
}
|
||||
logmutex.lock();
|
||||
while (br.id != id && !isEnd()) br = readRecord();
|
||||
while (br.id != id && !isEnd())
|
||||
br = readRecord();
|
||||
logmutex.unlock();
|
||||
if (br.id == -1) {
|
||||
piCoutObj << "End of BinLog file";
|
||||
@@ -376,7 +390,7 @@ PIByteArray PIBinaryLog::readBinLog(int id, PISystemTime * time, int * readed_id
|
||||
}
|
||||
|
||||
|
||||
int PIBinaryLog::readBinLog(int id, void *read_to, int max_size, PISystemTime * time, int * readed_id) {
|
||||
int PIBinaryLog::readBinLog(int id, void * read_to, int max_size, PISystemTime * time, int * readed_id) {
|
||||
if (max_size <= 0 || read_to == 0) return -1;
|
||||
PIByteArray ba = readBinLog(id, time, readed_id);
|
||||
if (ba.isEmpty()) return -1;
|
||||
@@ -401,10 +415,10 @@ PIByteArray PIBinaryLog::getHeader() {
|
||||
}
|
||||
|
||||
|
||||
ssize_t PIBinaryLog::readDevice(void *read_to, ssize_t max_size) {
|
||||
ssize_t PIBinaryLog::readDevice(void * read_to, ssize_t max_size) {
|
||||
PIMutexLocker _ml(logmutex);
|
||||
if (lastrecord.id == -1 || isEnd()) return 0;
|
||||
if(!is_thread_ok && lastrecord.id > 0) return lastrecord.data.size();
|
||||
if (!is_thread_ok && lastrecord.id > 0) return lastrecord.data.size();
|
||||
if (!canRead()) return -1;
|
||||
if (max_size <= 0 || read_to == 0) return -1;
|
||||
BinLogRecord br;
|
||||
@@ -412,7 +426,8 @@ ssize_t PIBinaryLog::readDevice(void *read_to, ssize_t max_size) {
|
||||
if (filterID.isEmpty()) {
|
||||
br = readRecord();
|
||||
} else {
|
||||
while (!filterID.contains(br.id) && !isEnd()) br = readRecord();
|
||||
while (!filterID.contains(br.id) && !isEnd())
|
||||
br = readRecord();
|
||||
}
|
||||
if (br.id == -1) {
|
||||
fileEnd();
|
||||
@@ -468,10 +483,11 @@ bool PIBinaryLog::writeFileHeader() {
|
||||
bool PIBinaryLog::checkFileHeader() {
|
||||
binfo.user_header.clear();
|
||||
uchar read_sig[PIBINARYLOG_SIGNATURE_SIZE];
|
||||
for (uint i=0; i<PIBINARYLOG_SIGNATURE_SIZE; i++) read_sig[i] = 0;
|
||||
for (uint i = 0; i < PIBINARYLOG_SIGNATURE_SIZE; i++)
|
||||
read_sig[i] = 0;
|
||||
if (file.read(read_sig, PIBINARYLOG_SIGNATURE_SIZE) < 0) return false;
|
||||
bool correct = true;
|
||||
for (uint i=0; i<PIBINARYLOG_SIGNATURE_SIZE; i++)
|
||||
for (uint i = 0; i < PIBINARYLOG_SIGNATURE_SIZE; i++)
|
||||
if (read_sig[i] != binlog_sig[i]) correct = false;
|
||||
if (!correct) {
|
||||
piCoutObj << "BinLogFile signature is corrupted or invalid file";
|
||||
@@ -492,18 +508,15 @@ bool PIBinaryLog::checkFileHeader() {
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if (read_version == 0)
|
||||
piCoutObj << "BinLogFile has invalid version";
|
||||
if (read_version < PIBINARYLOG_VERSION)
|
||||
piCoutObj << "BinLogFile has too old verion";
|
||||
if (read_version > PIBINARYLOG_VERSION)
|
||||
piCoutObj << "BinLogFile has too newest version";
|
||||
if (read_version == 0) piCoutObj << "BinLogFile has invalid version";
|
||||
if (read_version < PIBINARYLOG_VERSION) piCoutObj << "BinLogFile has too old verion";
|
||||
if (read_version > PIBINARYLOG_VERSION) piCoutObj << "BinLogFile has too newest version";
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
PIBinaryLog::BinLogRecord PIBinaryLog::readRecord() {
|
||||
// piCoutObj << "readRecord";
|
||||
// piCoutObj << "readRecord";
|
||||
logmutex.lock();
|
||||
PIByteArray ba;
|
||||
BinLogRecord br;
|
||||
@@ -511,29 +524,31 @@ PIBinaryLog::BinLogRecord PIBinaryLog::readRecord() {
|
||||
lastrecord.data.clear();
|
||||
lastrecord.timestamp = PISystemTime();
|
||||
ba.resize(sizeof(BinLogRecord) - sizeof(PIByteArray));
|
||||
if(file.read(ba.data(), ba.size_s()) > 0) {
|
||||
if (file.read(ba.data(), ba.size_s()) > 0) {
|
||||
ba >> br.id >> br.size >> br.timestamp;
|
||||
} else {
|
||||
br.id = -1;
|
||||
logmutex.unlock();
|
||||
// piCoutObj << "readRecord done";
|
||||
// piCoutObj << "readRecord done";
|
||||
return br;
|
||||
}
|
||||
if (br.id > 0 && br.size > 0) {
|
||||
ba.resize(br.size);
|
||||
if(file.read(ba.data(), ba.size_s()) > 0) br.data = ba;
|
||||
else br.id = 0;
|
||||
} else br.id = 0;
|
||||
if (file.read(ba.data(), ba.size_s()) > 0)
|
||||
br.data = ba;
|
||||
else
|
||||
br.id = 0;
|
||||
} else
|
||||
br.id = 0;
|
||||
lastrecord = br;
|
||||
if (br.id == 0) fileError();
|
||||
moveIndex(index_pos.value(file.pos(), -1));
|
||||
logmutex.unlock();
|
||||
// piCoutObj << "readRecord done";
|
||||
// piCoutObj << "readRecord done";
|
||||
return br;
|
||||
}
|
||||
|
||||
|
||||
|
||||
void PIBinaryLog::parseLog(PIFile * f, PIBinaryLog::BinLogInfo * info, PIVector<PIBinaryLog::BinLogIndex> * index) {
|
||||
if (!info && !index) return;
|
||||
if (info) {
|
||||
@@ -549,12 +564,13 @@ void PIBinaryLog::parseLog(PIFile * f, PIBinaryLog::BinLogInfo * info, PIVector<
|
||||
info->log_size = f->size();
|
||||
}
|
||||
uchar read_sig[PIBINARYLOG_SIGNATURE_SIZE];
|
||||
for (uint i=0; i<PIBINARYLOG_SIGNATURE_SIZE; i++) read_sig[i] = 0;
|
||||
for (uint i = 0; i < PIBINARYLOG_SIGNATURE_SIZE; i++)
|
||||
read_sig[i] = 0;
|
||||
if (f->read(read_sig, PIBINARYLOG_SIGNATURE_SIZE) < 0) {
|
||||
if (info) info->records_count = -1;
|
||||
return;
|
||||
}
|
||||
for (uint i=0; i<PIBINARYLOG_SIGNATURE_SIZE; i++) {
|
||||
for (uint i = 0; i < PIBINARYLOG_SIGNATURE_SIZE; i++) {
|
||||
if (read_sig[i] != binlog_sig[i]) {
|
||||
if (info) info->records_count = -2;
|
||||
return;
|
||||
@@ -596,13 +612,14 @@ void PIBinaryLog::parseLog(PIFile * f, PIBinaryLog::BinLogInfo * info, PIVector<
|
||||
{
|
||||
if (f->read(ba.data(), ba.size()) > 0) {
|
||||
ba >> br.id >> br.size >> br.timestamp;
|
||||
} else break;
|
||||
} else
|
||||
break;
|
||||
if (info) {
|
||||
if (info->log_size - f->pos() >= br.size) {
|
||||
f->seek(f->pos() + br.size);
|
||||
}
|
||||
}
|
||||
else break;
|
||||
} else
|
||||
break;
|
||||
}
|
||||
if (br.id > 0) {
|
||||
if (index) {
|
||||
@@ -619,7 +636,7 @@ void PIBinaryLog::parseLog(PIFile * f, PIBinaryLog::BinLogInfo * info, PIVector<
|
||||
info->start_time = br.timestamp;
|
||||
first = false;
|
||||
}
|
||||
BinLogRecordInfo &bri(info->records[br.id]);
|
||||
BinLogRecordInfo & bri(info->records[br.id]);
|
||||
bri.count++;
|
||||
if (bri.id == 0) {
|
||||
bri.id = br.id;
|
||||
@@ -659,7 +676,8 @@ PIBinaryLog::BinLogInfo PIBinaryLog::getLogInfo(const PIString & path) {
|
||||
bool PIBinaryLog::cutBinLog(const PIBinaryLog::BinLogInfo & src, const PIString & dst, int from, int to) {
|
||||
PIBinaryLog slog;
|
||||
if (!slog.open(src.path, PIIODevice::ReadOnly)) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't open" << src.path;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't open" << src.path;
|
||||
return false;
|
||||
}
|
||||
PIVector<int> ids = src.records.keys();
|
||||
@@ -667,7 +685,8 @@ bool PIBinaryLog::cutBinLog(const PIBinaryLog::BinLogInfo & src, const PIString
|
||||
PIBinaryLog dlog;
|
||||
dlog.createNewFile(dst);
|
||||
if (!dlog.isOpened()) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't create" << dst;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't create" << dst;
|
||||
return false;
|
||||
}
|
||||
bool first = true;
|
||||
@@ -682,29 +701,34 @@ bool PIBinaryLog::cutBinLog(const PIBinaryLog::BinLogInfo & src, const PIString
|
||||
}
|
||||
if (ids.contains(br.id)) {
|
||||
if (dlog.writeBinLog_raw(br.id, br.timestamp - st, br.data) <= 0) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't write to file" << dst;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't write to file" << dst;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (tm.elapsed_s() > 1) {
|
||||
tm.reset();
|
||||
piCout << "[PIBinaryLog]" << "process" << PITime::fromSystemTime(br.timestamp).toString();
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "process" << PITime::fromSystemTime(br.timestamp).toString();
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
bool PIBinaryLog::joinBinLogsSerial(const PIStringList & src, const PIString & dst, std::function<bool (const PIString &, PISystemTime)> progress) {
|
||||
bool PIBinaryLog::joinBinLogsSerial(const PIStringList & src,
|
||||
const PIString & dst,
|
||||
std::function<bool(const PIString &, PISystemTime)> progress) {
|
||||
PIBinaryLog slog;
|
||||
PIBinaryLog dlog;
|
||||
PISystemTime dtime;
|
||||
PISystemTime lt;
|
||||
PITimeMeasurer tm;
|
||||
bool first = true;
|
||||
for (const PIString & fn : src) {
|
||||
for (const PIString & fn: src) {
|
||||
if (!slog.open(fn, PIIODevice::ReadOnly)) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't open" << fn;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't open" << fn;
|
||||
return false;
|
||||
}
|
||||
if (first) {
|
||||
@@ -712,10 +736,12 @@ bool PIBinaryLog::joinBinLogsSerial(const PIStringList & src, const PIString & d
|
||||
dlog.setHeader(slog.getHeader());
|
||||
dlog.createNewFile(dst);
|
||||
if (!dlog.isOpened()) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't create" << dst;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't create" << dst;
|
||||
return false;
|
||||
}
|
||||
piCout << "[PIBinaryLog]" << "Start join binlogs to" << dst;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Start join binlogs to" << dst;
|
||||
} else {
|
||||
dtime = lt;
|
||||
}
|
||||
@@ -728,7 +754,8 @@ bool PIBinaryLog::joinBinLogsSerial(const PIStringList & src, const PIString & d
|
||||
st = br.timestamp;
|
||||
lt = dtime + br.timestamp;
|
||||
if (dlog.writeBinLog_raw(br.id, lt, br.data) <= 0) {
|
||||
piCout << "[PIBinaryLog]" << "Error, can't write to file" << dst;
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Error, can't write to file" << dst;
|
||||
return false;
|
||||
}
|
||||
if (tm.elapsed_s() > 0.1) {
|
||||
@@ -741,14 +768,16 @@ bool PIBinaryLog::joinBinLogsSerial(const PIStringList & src, const PIString & d
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
piCout << "[PIBinaryLog]" << "process" << PITime::fromSystemTime(lt).toString();
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "process" << PITime::fromSystemTime(lt).toString();
|
||||
}
|
||||
}
|
||||
}
|
||||
slog.close();
|
||||
//piCout << "[PIBinaryLog]" << "complete" << fn;
|
||||
// piCout << "[PIBinaryLog]" << "complete" << fn;
|
||||
}
|
||||
piCout << "[PIBinaryLog]" << "Finish join binlogs, total time" << PITime::fromSystemTime(lt).toString();
|
||||
piCout << "[PIBinaryLog]"
|
||||
<< "Finish join binlogs, total time" << PITime::fromSystemTime(lt).toString();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -762,7 +791,8 @@ bool PIBinaryLog::createIndex() {
|
||||
parseLog(&file, &binfo, &index);
|
||||
file.seek(cp);
|
||||
is_indexed = !index.isEmpty();
|
||||
for (uint i=0; i<index.size(); i++) index_pos[index[i].pos] = i;
|
||||
for (uint i = 0; i < index.size(); i++)
|
||||
index_pos[index[i].pos] = i;
|
||||
logmutex.unlock();
|
||||
return is_indexed;
|
||||
}
|
||||
@@ -781,20 +811,20 @@ int PIBinaryLog::posForTime(const PISystemTime & time) {
|
||||
|
||||
|
||||
void PIBinaryLog::seekTo(int rindex) {
|
||||
// piCoutObj << "seekTo";
|
||||
// piCoutObj << "seekTo";
|
||||
logmutex.lock();
|
||||
pausemutex.lock();
|
||||
if (rindex < index.size_s() && rindex >= 0) {
|
||||
file.seek(index[rindex].pos);
|
||||
moveIndex(index_pos.value(file.pos(), -1));
|
||||
//double prev_pt = play_time;
|
||||
// double prev_pt = play_time;
|
||||
play_time = index[rindex].timestamp.toMilliseconds();
|
||||
lastrecord.timestamp = index[rindex].timestamp;
|
||||
if (play_mode == PlayRealTime) {
|
||||
startlogtime = PISystemTime::current() - lastrecord.timestamp;
|
||||
}
|
||||
}
|
||||
// piCoutObj << "seekTo done";
|
||||
// piCoutObj << "seekTo done";
|
||||
pausemutex.unlock();
|
||||
logmutex.unlock();
|
||||
}
|
||||
@@ -812,7 +842,7 @@ bool PIBinaryLog::seek(const PISystemTime & time) {
|
||||
|
||||
bool PIBinaryLog::seek(llong filepos) {
|
||||
int ci = -1;
|
||||
for (uint i=0; i<index.size(); i++) {
|
||||
for (uint i = 0; i < index.size(); i++) {
|
||||
if (filepos <= index[i].pos && (filterID.contains(index[i].id) || filterID.isEmpty())) {
|
||||
ci = i;
|
||||
break;
|
||||
@@ -830,18 +860,10 @@ PIString PIBinaryLog::constructFullPathDevice() const {
|
||||
PIString ret;
|
||||
ret += logDir() + ":" + filePrefix() + ":" + PIString::fromNumber(defaultID()) + ":";
|
||||
switch (play_mode) {
|
||||
case PlayRealTime:
|
||||
ret += "RT";
|
||||
break;
|
||||
case PlayVariableSpeed:
|
||||
ret += PIString::fromNumber(playSpeed()) + "X";
|
||||
break;
|
||||
case PlayStaticDelay:
|
||||
ret += PIString::fromNumber(playDelay().toMilliseconds()) + "M";
|
||||
break;
|
||||
default:
|
||||
ret += "RT";
|
||||
break;
|
||||
case PlayRealTime: ret += "RT"; break;
|
||||
case PlayVariableSpeed: ret += PIString::fromNumber(playSpeed()) + "X"; break;
|
||||
case PlayStaticDelay: ret += PIString::fromNumber(playDelay().toMilliseconds()) + "M"; break;
|
||||
default: ret += "RT"; break;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -872,7 +894,9 @@ PIPropertyStorage PIBinaryLog::constructVariantDevice() const {
|
||||
ret.addProperty("log dir", PIVariantTypes::Dir(logDir()));
|
||||
ret.addProperty("file prefix", filePrefix());
|
||||
ret.addProperty("default ID", defaultID());
|
||||
e << "real-time" << "variable speed" << "static delay";
|
||||
e << "real-time"
|
||||
<< "variable speed"
|
||||
<< "static delay";
|
||||
e.selectValue((int)playMode());
|
||||
ret.addProperty("play mode", e);
|
||||
ret.addProperty("play speed", playSpeed());
|
||||
@@ -902,6 +926,5 @@ void PIBinaryLog::propertyChanged(const char * s) {
|
||||
split_time = property("splitTime").toSystemTime();
|
||||
split_size = property("splitFileSize").toLLong();
|
||||
split_count = property("splitRecordCount").toInt();
|
||||
// piCoutObj << "propertyChanged" << s << play_mode;
|
||||
// piCoutObj << "propertyChanged" << s << play_mode;
|
||||
}
|
||||
|
||||
|
||||
@@ -32,25 +32,25 @@
|
||||
//! \~\brief
|
||||
//! \~english Binary log
|
||||
//! \~russian Бинарный лог
|
||||
class PIP_EXPORT PIBinaryLog: public PIIODevice
|
||||
{
|
||||
class PIP_EXPORT PIBinaryLog: public PIIODevice {
|
||||
PIIODEVICE(PIBinaryLog, "binlog");
|
||||
|
||||
public:
|
||||
explicit PIBinaryLog();
|
||||
virtual ~PIBinaryLog();
|
||||
|
||||
//! \brief Play modes for \a PIBinaryLog
|
||||
enum PlayMode {
|
||||
PlayRealTime /*! Play in system realtime, default mode */ ,
|
||||
PlayVariableSpeed /*! Play in software realtime with speed, set by \a setSpeed */ ,
|
||||
PlayRealTime /*! Play in system realtime, default mode */,
|
||||
PlayVariableSpeed /*! Play in software realtime with speed, set by \a setSpeed */,
|
||||
PlayStaticDelay /*! Play with custom static delay, ignoring timestamp */
|
||||
};
|
||||
|
||||
//! \brief Different split modes for writing \a PIBinaryLog, which can separate files by size, by time or by records count
|
||||
enum SplitMode {
|
||||
SplitNone /*! Without separate, default mode */ ,
|
||||
SplitTime /*! Separate files by record time */ ,
|
||||
SplitSize /*! Separate files by size */ ,
|
||||
SplitNone /*! Without separate, default mode */,
|
||||
SplitTime /*! Separate files by record time */,
|
||||
SplitSize /*! Separate files by size */,
|
||||
SplitCount /*! Separate files by records count */
|
||||
};
|
||||
|
||||
@@ -89,81 +89,96 @@ public:
|
||||
|
||||
|
||||
//! Current \a PlayMode
|
||||
PlayMode playMode() const {return play_mode;}
|
||||
PlayMode playMode() const { return play_mode; }
|
||||
|
||||
//! Current \a SplitMode
|
||||
SplitMode splitMode() const {return split_mode;}
|
||||
SplitMode splitMode() const { return split_mode; }
|
||||
|
||||
//! Current directory where billogs wiil be saved
|
||||
PIString logDir() const {return property("logDir").toString();}
|
||||
PIString logDir() const { return property("logDir").toString(); }
|
||||
|
||||
//! Returns current file prefix
|
||||
PIString filePrefix() const {return property("filePrefix").toString();}
|
||||
PIString filePrefix() const { return property("filePrefix").toString(); }
|
||||
|
||||
//! Default ID, used in \a write function
|
||||
int defaultID() const {return default_id;}
|
||||
int defaultID() const { return default_id; }
|
||||
|
||||
//! Returns current play speed
|
||||
double playSpeed() const {return play_speed > 0 ? 1. / play_speed : 0.;}
|
||||
double playSpeed() const { return play_speed > 0 ? 1. / play_speed : 0.; }
|
||||
|
||||
//! Returns current play delay
|
||||
PISystemTime playDelay() const {return play_delay;}
|
||||
PISystemTime playDelay() const { return play_delay; }
|
||||
|
||||
//! Returns current binlog file split time
|
||||
PISystemTime splitTime() const {return split_time;}
|
||||
PISystemTime splitTime() const { return split_time; }
|
||||
|
||||
//! Returns current binlog file split size
|
||||
llong splitFileSize() const {return split_size;}
|
||||
llong splitFileSize() const { return split_size; }
|
||||
|
||||
//! Returns current binlog file split records count
|
||||
int splitRecordCount() const {return split_count;}
|
||||
int splitRecordCount() const { return split_count; }
|
||||
|
||||
//! Returns if rapid start enabled
|
||||
bool rapidStart() const {return rapid_start;}
|
||||
bool rapidStart() const { return rapid_start; }
|
||||
|
||||
//! Create binlog file with Filename = path
|
||||
void createNewFile(const PIString &path);
|
||||
void createNewFile(const PIString & path);
|
||||
|
||||
//! Set \a PlayMode
|
||||
void setPlayMode(PlayMode mode) {setProperty("playMode", (int)mode);}
|
||||
void setPlayMode(PlayMode mode) { setProperty("playMode", (int)mode); }
|
||||
|
||||
//! Set \a SplitMode
|
||||
void setSplitMode(SplitMode mode) {setProperty("splitMode", (int)mode);}
|
||||
void setSplitMode(SplitMode mode) { setProperty("splitMode", (int)mode); }
|
||||
|
||||
//! Set path to directory where binlogs will be saved
|
||||
void setLogDir(const PIString & path) {setProperty("logDir", path);}
|
||||
void setLogDir(const PIString & path) { setProperty("logDir", path); }
|
||||
|
||||
//! Set file prefix, used to
|
||||
void setFilePrefix(const PIString & prefix) {setProperty("filePrefix", prefix);}
|
||||
void setFilePrefix(const PIString & prefix) { setProperty("filePrefix", prefix); }
|
||||
|
||||
//! Set defaultID, used in \a write function
|
||||
void setDefaultID(int id) {setProperty("defaultID", id);}
|
||||
void setDefaultID(int id) { setProperty("defaultID", id); }
|
||||
|
||||
//! If enabled BinLog \a ThreadedRead starts without delay for first record, i.e. first record will be readed immediately
|
||||
void setRapidStart(bool enabled) {setProperty("rapidStart", enabled);}
|
||||
void setRapidStart(bool enabled) { setProperty("rapidStart", enabled); }
|
||||
|
||||
//! Set play speed to "speed", default value is 1.0x
|
||||
//! Also this function set \a playMode to \a PlayVariableSpeed
|
||||
void setPlaySpeed(double speed) {setPlayMode(PlayVariableSpeed); setProperty("playSpeed", speed);}
|
||||
void setPlaySpeed(double speed) {
|
||||
setPlayMode(PlayVariableSpeed);
|
||||
setProperty("playSpeed", speed);
|
||||
}
|
||||
|
||||
//! Setting static delay between records, default value is 1 sec
|
||||
//! Also this function set \a playMode to \a PlayStaticDelay
|
||||
void setPlayDelay(const PISystemTime & delay) {setPlayMode(PlayStaticDelay); setProperty("playDelay", delay);}
|
||||
void setPlayDelay(const PISystemTime & delay) {
|
||||
setPlayMode(PlayStaticDelay);
|
||||
setProperty("playDelay", delay);
|
||||
}
|
||||
|
||||
//! Set \a playMode to \a PlayRealTime
|
||||
void setPlayRealTime() {setPlayMode(PlayRealTime);}
|
||||
void setPlayRealTime() { setPlayMode(PlayRealTime); }
|
||||
|
||||
//! Set binlog file split time
|
||||
//! Also this function set \a splitMode to \a SplitTime
|
||||
void setSplitTime(const PISystemTime & time) {setSplitMode(SplitTime); setProperty("splitTime", time);}
|
||||
void setSplitTime(const PISystemTime & time) {
|
||||
setSplitMode(SplitTime);
|
||||
setProperty("splitTime", time);
|
||||
}
|
||||
|
||||
//! Set binlog file split size
|
||||
//! Also this function set \a splitMode to \a SplitSize
|
||||
void setSplitFileSize(llong size) {setSplitMode(SplitSize); setProperty("splitFileSize", size);}
|
||||
void setSplitFileSize(llong size) {
|
||||
setSplitMode(SplitSize);
|
||||
setProperty("splitFileSize", size);
|
||||
}
|
||||
|
||||
//! Set binlog file split records count
|
||||
//! Also this function set \a splitMode to \a SplitCount
|
||||
void setSplitRecordCount(int count) {setSplitMode(SplitCount); setProperty("splitRecordCount", count);}
|
||||
void setSplitRecordCount(int count) {
|
||||
setSplitMode(SplitCount);
|
||||
setProperty("splitRecordCount", count);
|
||||
}
|
||||
|
||||
//! Set pause while playing via \a threadedRead or writing via write
|
||||
void setPause(bool pause);
|
||||
@@ -171,20 +186,22 @@ public:
|
||||
//! Set function wich returns new binlog file path when using split mode.
|
||||
//! Overrides internal file path generator (logdir() + prefix() + current_time()).
|
||||
//! To restore internal file path generator set this function to "nullptr".
|
||||
void setFuncGetNewFilePath(std::function<PIString()> f) {f_new_path = f;}
|
||||
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = f; }
|
||||
|
||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
||||
int writeBinLog(int id, PIByteArray data) {return writeBinLog(id, data.data(), data.size_s());}
|
||||
int writeBinLog(int id, PIByteArray data) { return writeBinLog(id, data.data(), data.size_s()); }
|
||||
|
||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
||||
int writeBinLog(int id, const void * data, int size);
|
||||
|
||||
//! Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||
int writeBinLog_raw(int id, const PISystemTime &time, const PIByteArray &data) {return writeBinLog_raw(id, time, data.data(), data.size_s());}
|
||||
int writeBinLog_raw(int id, const PISystemTime &time, const void * data, int size);
|
||||
int writeBinLog_raw(int id, const PISystemTime & time, const PIByteArray & data) {
|
||||
return writeBinLog_raw(id, time, data.data(), data.size_s());
|
||||
}
|
||||
int writeBinLog_raw(int id, const PISystemTime & time, const void * data, int size);
|
||||
|
||||
//! Returns count of writed records
|
||||
int writeCount() const {return write_count;}
|
||||
int writeCount() const { return write_count; }
|
||||
|
||||
//! Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||
PIByteArray readBinLog(int id = 0, PISystemTime * time = 0, int * readed_id = 0);
|
||||
@@ -193,38 +210,41 @@ public:
|
||||
int readBinLog(int id, void * read_to, int max_size, PISystemTime * time = 0, int * readed_id = 0);
|
||||
|
||||
//! Returns binary log file size
|
||||
llong logSize() const {return log_size;}
|
||||
llong logSize() const { return log_size; }
|
||||
|
||||
//! Return position in current binlog file
|
||||
llong logPos() const {return file.pos();}
|
||||
llong logPos() const { return file.pos(); }
|
||||
|
||||
//! Return true, if position at the end of BinLog file
|
||||
bool isEnd() const {if (isClosed()) return true; return file.isEnd();}
|
||||
bool isEnd() const {
|
||||
if (isClosed()) return true;
|
||||
return file.isEnd();
|
||||
}
|
||||
|
||||
//! Returns if BinLog file is empty
|
||||
bool isEmpty() const;
|
||||
|
||||
//! Returns BinLog pause status
|
||||
bool isPause() const {return is_pause;}
|
||||
bool isPause() const { return is_pause; }
|
||||
|
||||
//! Returns id of last readed record
|
||||
int lastReadedID() const {return lastrecord.id;}
|
||||
int lastReadedID() const { return lastrecord.id; }
|
||||
|
||||
//! Returns timestamp of last readed record
|
||||
PISystemTime lastReadedTimestamp() const {return lastrecord.timestamp;}
|
||||
PISystemTime lastReadedTimestamp() const { return lastrecord.timestamp; }
|
||||
|
||||
//! Returns timestamp of log start
|
||||
PISystemTime logStartTimestamp() const {return startlogtime;}
|
||||
PISystemTime logStartTimestamp() const { return startlogtime; }
|
||||
|
||||
//!Set custom file header, you can get it back when read this binlog
|
||||
//! Set custom file header, you can get it back when read this binlog
|
||||
void setHeader(const PIByteArray & header);
|
||||
|
||||
//!Get custom file header
|
||||
//! Get custom file header
|
||||
PIByteArray getHeader();
|
||||
|
||||
#ifdef DOXYGEN
|
||||
//! Read one message from binlog file, with ID contains in "filterID" or any ID, if "filterID" is empty
|
||||
int read(void *read_to, int max_size);
|
||||
int read(void * read_to, int max_size);
|
||||
|
||||
//! Write one record to BinLog file, with ID = "defaultID"
|
||||
int write(const void * data, int size);
|
||||
@@ -237,16 +257,19 @@ public:
|
||||
void restart();
|
||||
|
||||
//! Get binlog info \a BinLogInfo
|
||||
BinLogInfo logInfo() const {if (is_indexed) return binfo; return getLogInfo(path());}
|
||||
BinLogInfo logInfo() const {
|
||||
if (is_indexed) return binfo;
|
||||
return getLogInfo(path());
|
||||
}
|
||||
|
||||
//! Get binlog index \a BinLogIndex, need \a createIndex before getting index
|
||||
const PIVector<BinLogIndex> & logIndex() const {return index;}
|
||||
const PIVector<BinLogIndex> & logIndex() const { return index; }
|
||||
|
||||
//! Create index of current binlog file
|
||||
bool createIndex();
|
||||
|
||||
//! Return if current binlog file is indexed
|
||||
bool isIndexed() {return is_indexed;}
|
||||
bool isIndexed() { return is_indexed; }
|
||||
|
||||
//! Find nearest record of time \"time\". Returns -1 if not indexed or time less than first record
|
||||
int posForTime(const PISystemTime & time);
|
||||
@@ -261,7 +284,10 @@ public:
|
||||
bool seek(llong filepos);
|
||||
|
||||
//! Get current record index (position record in file)
|
||||
int pos() const {if (is_indexed) return current_index; return -1;}
|
||||
int pos() const {
|
||||
if (is_indexed) return current_index;
|
||||
return -1;
|
||||
}
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
@@ -298,20 +324,22 @@ public:
|
||||
static bool cutBinLog(const BinLogInfo & src, const PIString & dst, int from, int to);
|
||||
|
||||
//! Create new binlog from serial splitted binlogs "src"
|
||||
static bool joinBinLogsSerial(const PIStringList & src, const PIString & dst, std::function<bool (const PIString &, PISystemTime)> progress = nullptr);
|
||||
static bool joinBinLogsSerial(const PIStringList & src,
|
||||
const PIString & dst,
|
||||
std::function<bool(const PIString &, PISystemTime)> progress = nullptr);
|
||||
|
||||
protected:
|
||||
PIString constructFullPathDevice() const override;
|
||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||
PIPropertyStorage constructVariantDevice() const override;
|
||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||
ssize_t readDevice(void *read_to, ssize_t max_size) override;
|
||||
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
||||
ssize_t writeDevice(const void * data, ssize_t size) override;
|
||||
bool openDevice() override;
|
||||
bool closeDevice() override;
|
||||
void propertyChanged(const char * s) override;
|
||||
bool threadedRead(const uchar *readed, ssize_t size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Reliable;}
|
||||
bool threadedRead(const uchar * readed, ssize_t size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
struct PIP_EXPORT BinLogRecord {
|
||||
@@ -324,7 +352,7 @@ private:
|
||||
bool writeFileHeader();
|
||||
bool checkFileHeader();
|
||||
BinLogRecord readRecord();
|
||||
static void parseLog(PIFile *f, BinLogInfo *info, PIVector<BinLogIndex> * index);
|
||||
static void parseLog(PIFile * f, BinLogInfo * info, PIVector<BinLogIndex> * index);
|
||||
void moveIndex(int i);
|
||||
static PIString getLogfilePath(const PIString & log_dir, const PIString & prefix);
|
||||
|
||||
@@ -347,7 +375,7 @@ private:
|
||||
};
|
||||
|
||||
//! \relatesalso PICout \brief Output operator PIBinaryLog::BinLogInfo to PICout
|
||||
inline PICout operator <<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||
inline PICout operator<<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "[PIBinaryLog] " << bi.path << "\n";
|
||||
@@ -360,7 +388,8 @@ inline PICout operator <<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||
s << "Invalid empty file";
|
||||
s.restoreControls();
|
||||
return s;
|
||||
} if (bi.records_count < 0 && bi.records_count > -4) {
|
||||
}
|
||||
if (bi.records_count < 0 && bi.records_count > -4) {
|
||||
s << "Invalid file or corrupted signature";
|
||||
s.restoreControls();
|
||||
return s;
|
||||
@@ -373,7 +402,7 @@ inline PICout operator <<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||
s << "read records " << bi.records_count << " in " << bi.records.size() << " types, log size " << bi.log_size;
|
||||
s << "\nlog start " << bi.start_time << " , log end " << bi.end_time;
|
||||
PIVector<int> keys = bi.records.keys();
|
||||
for (int i : keys) {
|
||||
for (int i: keys) {
|
||||
PIBinaryLog::BinLogRecordInfo bri = bi.records.at(i);
|
||||
s << "\n record id " << bri.id << " , count " << bri.count;
|
||||
s << "\n record start " << bri.start_time << " , end " << bri.end_time;
|
||||
|
||||
@@ -17,16 +17,17 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "pican.h"
|
||||
|
||||
#include "pipropertystorage.h"
|
||||
#include "piwaitevent_p.h"
|
||||
#if !defined(WINDOWS) && !defined(MAC_OS) && !defined(MICRO_PIP)
|
||||
# define PIP_CAN
|
||||
#endif
|
||||
#ifdef PIP_CAN
|
||||
# include <sys/ioctl.h>
|
||||
# include <net/if.h>
|
||||
# include <linux/can.h>
|
||||
# include <linux/can/raw.h>
|
||||
# include <net/if.h>
|
||||
# include <sys/ioctl.h>
|
||||
# ifndef AF_CAN
|
||||
# define AF_CAN 29
|
||||
# endif
|
||||
@@ -44,7 +45,7 @@ PRIVATE_DEFINITION_START(PICAN)
|
||||
PRIVATE_DEFINITION_END(PICAN)
|
||||
|
||||
|
||||
PICAN::PICAN(const PIString & path, PIIODevice::DeviceMode mode) : PIIODevice(path, mode) {
|
||||
PICAN::PICAN(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode) {
|
||||
setThreadedReadBufferSize(256);
|
||||
setPath(path);
|
||||
can_id = 0;
|
||||
@@ -64,27 +65,27 @@ bool PICAN::openDevice() {
|
||||
#ifdef PIP_CAN
|
||||
piCout << "PICAN open device" << path();
|
||||
sock = socket(PF_CAN, SOCK_RAW, CAN_RAW);
|
||||
if(sock < 0){
|
||||
if (sock < 0) {
|
||||
piCoutObj << "Error! while opening socket";
|
||||
return false;
|
||||
}
|
||||
ifreq ifr;
|
||||
strcpy(ifr.ifr_name, path().dataAscii());
|
||||
piCout << "PICAN try to get interface index...";
|
||||
if(ioctl(sock, SIOCGIFINDEX, &ifr) < 0){
|
||||
if (ioctl(sock, SIOCGIFINDEX, &ifr) < 0) {
|
||||
piCoutObj << "Error! while determin the interface ioctl";
|
||||
return false;
|
||||
}
|
||||
struct timeval tv;
|
||||
tv.tv_sec = 1;
|
||||
tv.tv_usec = 0;
|
||||
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char*)&tv, sizeof tv);
|
||||
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof tv);
|
||||
// bind socket to all CAN interface
|
||||
sockaddr_can addr;
|
||||
addr.can_family = AF_CAN;
|
||||
addr.can_ifindex = ifr.ifr_ifindex;
|
||||
piCout << "PICAN try to bind socket to interface" << ifr.ifr_ifindex;
|
||||
if(bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0){
|
||||
if (bind(sock, (struct sockaddr *)&addr, sizeof(addr)) < 0) {
|
||||
piCoutObj << "Error! while binding socket";
|
||||
return false;
|
||||
}
|
||||
@@ -108,13 +109,14 @@ bool PICAN::closeDevice() {
|
||||
|
||||
ssize_t PICAN::readDevice(void * read_to, ssize_t max_size) {
|
||||
#ifdef PIP_CAN
|
||||
//piCout << "PICAN read";
|
||||
// piCout << "PICAN read";
|
||||
can_frame frame;
|
||||
ssize_t ret = 0;
|
||||
if (PRIVATE->event.wait(sock))
|
||||
ret = ::read(sock, &frame, sizeof(can_frame));
|
||||
if (ret < 0) {/*piCoutObj << "Error while read CAN frame " << ret;*/ return -1;}
|
||||
//piCoutObj << "receive CAN frame Id =" << frame.can_id;
|
||||
if (PRIVATE->event.wait(sock)) ret = ::read(sock, &frame, sizeof(can_frame));
|
||||
if (ret < 0) { /*piCoutObj << "Error while read CAN frame " << ret;*/
|
||||
return -1;
|
||||
}
|
||||
// piCoutObj << "receive CAN frame Id =" << frame.can_id;
|
||||
memcpy(read_to, frame.data, piMini(frame.can_dlc, max_size));
|
||||
readed_id = frame.can_id;
|
||||
return piMini(frame.can_dlc, max_size);
|
||||
@@ -125,15 +127,21 @@ ssize_t PICAN::readDevice(void * read_to, ssize_t max_size) {
|
||||
|
||||
ssize_t PICAN::writeDevice(const void * data, ssize_t max_size) {
|
||||
#ifdef PIP_CAN
|
||||
//piCout << "PICAN write" << can_id << max_size;
|
||||
if (max_size > 8) {piCoutObj << "Can't send CAN frame bigger than 8 bytes (requested " << max_size << ")!"; return -1;}
|
||||
// piCout << "PICAN write" << can_id << max_size;
|
||||
if (max_size > 8) {
|
||||
piCoutObj << "Can't send CAN frame bigger than 8 bytes (requested " << max_size << ")!";
|
||||
return -1;
|
||||
}
|
||||
can_frame frame;
|
||||
frame.can_id = can_id;
|
||||
frame.can_dlc = max_size;
|
||||
memcpy(frame.data, data, max_size);
|
||||
ssize_t ret = 0;
|
||||
ret = ::write(sock, &frame, sizeof(can_frame));
|
||||
if (ret < 0) {piCoutObj << "Error while send CAN frame " << ret; return -1;}
|
||||
if (ret < 0) {
|
||||
piCoutObj << "Error while send CAN frame " << ret;
|
||||
return -1;
|
||||
}
|
||||
return max_size;
|
||||
#endif
|
||||
return 0;
|
||||
@@ -183,7 +191,7 @@ void PICAN::configureFromFullPathDevice(const PIString & full_path) {
|
||||
PIPropertyStorage PICAN::constructVariantDevice() const {
|
||||
PIPropertyStorage ret;
|
||||
ret.addProperty("path", path());
|
||||
ret.addProperty("CAN ID", PIString::fromNumber(CANID(),16));
|
||||
ret.addProperty("CAN ID", PIString::fromNumber(CANID(), 16));
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
@@ -29,9 +29,9 @@
|
||||
#include "piiodevice.h"
|
||||
|
||||
|
||||
class PIP_EXPORT PICAN: public PIIODevice
|
||||
{
|
||||
class PIP_EXPORT PICAN: public PIIODevice {
|
||||
PIIODEVICE(PICAN, "can");
|
||||
|
||||
public:
|
||||
explicit PICAN(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
virtual ~PICAN();
|
||||
@@ -50,7 +50,7 @@ protected:
|
||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||
PIPropertyStorage constructVariantDevice() const override;
|
||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Reliable;}
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
PRIVATE_DECLARATION(PIP_EXPORT)
|
||||
|
||||
@@ -19,10 +19,12 @@
|
||||
|
||||
|
||||
#include "piconfig.h"
|
||||
|
||||
#include "pifile.h"
|
||||
#include "piiostring.h"
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
# include "pistring_std.h"
|
||||
|
||||
# include <iostream>
|
||||
#endif
|
||||
/*! \class PIConfig
|
||||
@@ -88,14 +90,14 @@
|
||||
* internal instance of %PIConfig::Entry with "default" value will be returned.
|
||||
* \snippet piconfig.cpp PIConfig::Entry
|
||||
*
|
||||
*/
|
||||
*/
|
||||
|
||||
/*! \class PIConfig::Branch
|
||||
* \brief %Branch is a list of entries of configuration file
|
||||
* \details %Branch provides some features to get entries lists.
|
||||
* \snippet piconfig.cpp PIConfig::Branch
|
||||
*
|
||||
*/
|
||||
*/
|
||||
|
||||
|
||||
PIConfig::Entry PIConfig::Branch::_empty;
|
||||
@@ -105,9 +107,11 @@ PIConfig::Entry PIConfig::Entry::_empty;
|
||||
PIConfig::Branch PIConfig::Branch::allLeaves() {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, *this) {
|
||||
if (i->isLeaf()) b << i;
|
||||
else allLeaves(b, i);
|
||||
piForeach(Entry * i, *this) {
|
||||
if (i->isLeaf())
|
||||
b << i;
|
||||
else
|
||||
allLeaves(b, i);
|
||||
}
|
||||
return b;
|
||||
}
|
||||
@@ -124,7 +128,7 @@ PIConfig::Entry & PIConfig::Branch::getValue(const PIString & vname, const PIStr
|
||||
PIString name = tree.front();
|
||||
tree.pop_front();
|
||||
Entry * ce = 0;
|
||||
piForeach (Entry * i, *this)
|
||||
piForeach(Entry * i, *this)
|
||||
if (i->_name == name) {
|
||||
ce = i;
|
||||
break;
|
||||
@@ -136,7 +140,7 @@ PIConfig::Entry & PIConfig::Branch::getValue(const PIString & vname, const PIStr
|
||||
if (exist != 0) *exist = false;
|
||||
return _empty;
|
||||
}
|
||||
piForeach (PIString & i, tree) {
|
||||
piForeach(PIString & i, tree) {
|
||||
ce = ce->findChild(i);
|
||||
if (ce == 0) {
|
||||
_empty._name = vname;
|
||||
@@ -154,14 +158,12 @@ PIConfig::Entry & PIConfig::Branch::getValue(const PIString & vname, const PIStr
|
||||
PIConfig::Branch PIConfig::Branch::getValues(const PIString & name) {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, *this) {
|
||||
piForeach(Entry * i, *this) {
|
||||
if (i->isLeaf()) {
|
||||
if (i->_name.find(name) >= 0)
|
||||
b << i;
|
||||
if (i->_name.find(name) >= 0) b << i;
|
||||
} else {
|
||||
piForeach (Entry * j, i->_children)
|
||||
if (j->_name.find(name) >= 0)
|
||||
b << j;
|
||||
piForeach(Entry * j, i->_children)
|
||||
if (j->_name.find(name) >= 0) b << j;
|
||||
}
|
||||
}
|
||||
return b;
|
||||
@@ -171,9 +173,8 @@ PIConfig::Branch PIConfig::Branch::getValues(const PIString & name) {
|
||||
PIConfig::Branch PIConfig::Branch::getLeaves() {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, *this)
|
||||
if (i->isLeaf())
|
||||
b << i;
|
||||
piForeach(Entry * i, *this)
|
||||
if (i->isLeaf()) b << i;
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -181,9 +182,8 @@ PIConfig::Branch PIConfig::Branch::getLeaves() {
|
||||
PIConfig::Branch PIConfig::Branch::getBranches() {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, *this)
|
||||
if (!i->isLeaf())
|
||||
b << i;
|
||||
piForeach(Entry * i, *this)
|
||||
if (!i->isLeaf()) b << i;
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -203,7 +203,7 @@ bool PIConfig::Branch::entryExists(const Entry * e, const PIString & name) const
|
||||
if (e->_children.isEmpty()) {
|
||||
return (e->_name == name);
|
||||
}
|
||||
piForeachC (Entry * i, e->_children)
|
||||
piForeachC(Entry * i, e->_children)
|
||||
if (entryExists(i, name)) return true;
|
||||
return false;
|
||||
}
|
||||
@@ -212,7 +212,7 @@ bool PIConfig::Branch::entryExists(const Entry * e, const PIString & name) const
|
||||
PIConfig::Entry & PIConfig::Entry::getValue(const PIString & vname, const PIString & def, bool * exist) {
|
||||
PIStringList tree = vname.split(delim);
|
||||
Entry * ce = this;
|
||||
piForeach (PIString & i, tree) {
|
||||
piForeach(PIString & i, tree) {
|
||||
ce = ce->findChild(i);
|
||||
if (ce == 0) {
|
||||
_empty._name = vname;
|
||||
@@ -230,9 +230,8 @@ PIConfig::Entry & PIConfig::Entry::getValue(const PIString & vname, const PIStri
|
||||
PIConfig::Branch PIConfig::Entry::getValues(const PIString & vname) {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, _children)
|
||||
if (i->_name.find(vname) >= 0)
|
||||
b << i;
|
||||
piForeach(Entry * i, _children)
|
||||
if (i->_name.find(vname) >= 0) b << i;
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -241,7 +240,7 @@ bool PIConfig::Entry::entryExists(const Entry * e, const PIString & name) const
|
||||
if (e->_children.isEmpty()) {
|
||||
return (e->_name == name);
|
||||
}
|
||||
piForeachC (Entry * i, e->_children)
|
||||
piForeachC(Entry * i, e->_children)
|
||||
if (entryExists(i, name)) return true;
|
||||
return false;
|
||||
}
|
||||
@@ -250,18 +249,24 @@ bool PIConfig::Entry::entryExists(const Entry * e, const PIString & name) const
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
void PIConfig::Entry::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);
|
||||
if (!_value.isEmpty())
|
||||
s << p << _name << " = " << _value << std::endl;
|
||||
else
|
||||
std::cout << p << _name << std::endl;
|
||||
piForeachC(Entry * i, _children)
|
||||
i->coutt(s, nl);
|
||||
}
|
||||
#endif
|
||||
|
||||
|
||||
void PIConfig::Entry::piCoutt(PICout s, const PIString & p) const {
|
||||
PIString nl = p + " ";
|
||||
if (!_value.isEmpty()) s << p << _name << " = " << _value << " (" << _type << " " << _comment << ")" << PICoutManipulators::NewLine;
|
||||
else s << p << _name << PICoutManipulators::NewLine;
|
||||
piForeachC (Entry * i, _children) i->piCoutt(s, nl);
|
||||
if (!_value.isEmpty())
|
||||
s << p << _name << " = " << _value << " (" << _type << " " << _comment << ")" << PICoutManipulators::NewLine;
|
||||
else
|
||||
s << p << _name << PICoutManipulators::NewLine;
|
||||
piForeachC(Entry * i, _children)
|
||||
i->piCoutt(s, nl);
|
||||
}
|
||||
|
||||
|
||||
@@ -319,8 +324,7 @@ bool PIConfig::open(const PIString & path, PIIODevice::DeviceMode mode) {
|
||||
incdirs << PIFile::fileInfo(path).dir();
|
||||
own_dev = true;
|
||||
dev = new PIFile(path, mode);
|
||||
if (!dev->isOpened())
|
||||
dev->open(path, mode);
|
||||
if (!dev->isOpened()) dev->open(path, mode);
|
||||
_setupDev();
|
||||
parse();
|
||||
return dev->isOpened();
|
||||
@@ -343,8 +347,7 @@ bool PIConfig::open(PIIODevice * device, PIIODevice::DeviceMode mode) {
|
||||
dev = device;
|
||||
if (dev) {
|
||||
dev->open(mode);
|
||||
if (dev->isTypeOf<PIFile>())
|
||||
incdirs << PIFile::fileInfo(((PIFile*)dev)->path()).dir();
|
||||
if (dev->isTypeOf<PIFile>()) incdirs << PIFile::fileInfo(((PIFile *)dev)->path()).dir();
|
||||
}
|
||||
_setupDev();
|
||||
parse();
|
||||
@@ -368,7 +371,7 @@ void PIConfig::_destroy() {
|
||||
}
|
||||
if (own_dev && dev) delete dev;
|
||||
dev = nullptr;
|
||||
piForeach (PIConfig * c, inc_devs)
|
||||
piForeach(PIConfig * c, inc_devs)
|
||||
delete c;
|
||||
inc_devs.clear();
|
||||
}
|
||||
@@ -383,14 +386,22 @@ void PIConfig::_setupDev() {
|
||||
|
||||
void PIConfig::_clearDev() {
|
||||
if (!dev) return;
|
||||
if (PIString(dev->className()) == "PIFile") {((PIFile*)dev)->clear(); return;}
|
||||
if (PIString(dev->className()) == "PIIOString") {((PIIOString*)dev)->clear(); return;}
|
||||
if (PIString(dev->className()) == "PIFile") {
|
||||
((PIFile *)dev)->clear();
|
||||
return;
|
||||
}
|
||||
if (PIString(dev->className()) == "PIIOString") {
|
||||
((PIIOString *)dev)->clear();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
void PIConfig::_flushDev() {
|
||||
if (!dev) return;
|
||||
if (PIString(dev->className()) == "PIFile") {((PIFile*)dev)->flush();}
|
||||
if (PIString(dev->className()) == "PIFile") {
|
||||
((PIFile *)dev)->flush();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -402,8 +413,14 @@ bool PIConfig::_isEndDev() {
|
||||
|
||||
void PIConfig::_seekToBeginDev() {
|
||||
if (!dev) return;
|
||||
if (PIString(dev->className()) == "PIFile") {((PIFile*)dev)->seekToBegin(); return;}
|
||||
if (PIString(dev->className()) == "PIIOString") {((PIIOString*)dev)->seekToBegin(); return;}
|
||||
if (PIString(dev->className()) == "PIFile") {
|
||||
((PIFile *)dev)->seekToBegin();
|
||||
return;
|
||||
}
|
||||
if (PIString(dev->className()) == "PIIOString") {
|
||||
((PIIOString *)dev)->seekToBegin();
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -414,7 +431,7 @@ PIString PIConfig::_readLineDev() {
|
||||
|
||||
|
||||
void PIConfig::_writeDev(const PIString & l) {
|
||||
//piCout << "write \"" << l << "\"";
|
||||
// piCout << "write \"" << l << "\"";
|
||||
if (!stream) return;
|
||||
stream->append(l);
|
||||
}
|
||||
@@ -429,7 +446,7 @@ bool PIConfig::isOpened() const {
|
||||
PIConfig::Entry & PIConfig::getValue(const PIString & vname, const PIString & def, bool * exist) {
|
||||
PIStringList tree = vname.split(delim);
|
||||
Entry * ce = &root;
|
||||
piForeach (PIString & i, tree) {
|
||||
piForeach(PIString & i, tree) {
|
||||
ce = ce->findChild(i);
|
||||
if (ce == 0) {
|
||||
if (exist != 0) *exist = false;
|
||||
@@ -447,23 +464,21 @@ PIConfig::Entry & PIConfig::getValue(const PIString & vname, const PIString & de
|
||||
PIConfig::Branch PIConfig::getValues(const PIString & vname) {
|
||||
Branch b;
|
||||
b.delim = delim;
|
||||
piForeach (Entry * i, root._children)
|
||||
if (i->_name.find(vname) >= 0)
|
||||
b << i;
|
||||
piForeach(Entry * i, root._children)
|
||||
if (i->_name.find(vname) >= 0) b << i;
|
||||
return b;
|
||||
};
|
||||
|
||||
|
||||
void PIConfig::addEntry(const PIString & name, const PIString & value, const PIString & type, bool write) {
|
||||
if (getValue(name)._parent != 0)
|
||||
return;
|
||||
if (getValue(name)._parent != 0) return;
|
||||
bool toRoot = false;
|
||||
PIStringList tree = name.split(delim);
|
||||
PIString ename = tree.back();
|
||||
tree.pop_back();
|
||||
Entry * te, * ce, * entry = &root;
|
||||
Entry *te, *ce, *entry = &root;
|
||||
if (tree.isEmpty()) toRoot = true;
|
||||
piForeach (PIString & i, tree) {
|
||||
piForeach(PIString & i, tree) {
|
||||
te = entry->findChild(i);
|
||||
if (te == 0) {
|
||||
ce = new Entry();
|
||||
@@ -474,7 +489,8 @@ void PIConfig::addEntry(const PIString & name, const PIString & value, const PIS
|
||||
ce->_parent = entry;
|
||||
entry->_children << ce;
|
||||
entry = ce;
|
||||
} else entry = te;
|
||||
} else
|
||||
entry = te;
|
||||
}
|
||||
PIConfig::Branch ch = entry->_children;
|
||||
ch.sort(PIConfig::Entry::compare);
|
||||
@@ -486,11 +502,14 @@ void PIConfig::addEntry(const PIString & name, const PIString & value, const PIS
|
||||
ce->_type = type;
|
||||
if (te == 0) {
|
||||
ce->_tab = entry->_tab;
|
||||
if (toRoot) ce->_line = other.size_s() - 1;
|
||||
else ce->_line = entry->_line;
|
||||
if (toRoot)
|
||||
ce->_line = other.size_s() - 1;
|
||||
else
|
||||
ce->_line = entry->_line;
|
||||
} else {
|
||||
ce->_tab = te->_tab;
|
||||
if (toRoot) ce->_line = other.size_s() - 1;
|
||||
if (toRoot)
|
||||
ce->_line = other.size_s() - 1;
|
||||
else {
|
||||
ch = entry->_parent->_children;
|
||||
ch.sort(PIConfig::Entry::compare);
|
||||
@@ -510,8 +529,7 @@ void PIConfig::addEntry(const PIString & name, const PIString & value, const PIS
|
||||
if (b[i] == ce) {
|
||||
found = true;
|
||||
if (i > 0)
|
||||
if (b[i - 1]->_line == b[i]->_line)
|
||||
b[i - 1]->_line++;
|
||||
if (b[i - 1]->_line == b[i]->_line) b[i - 1]->_line++;
|
||||
}
|
||||
}
|
||||
if (write) writeAll();
|
||||
@@ -533,10 +551,9 @@ void PIConfig::setValue(const PIString & name, const PIString & value, const PIS
|
||||
int PIConfig::entryIndex(const PIString & name) {
|
||||
PIStringList tree = name.split(delim);
|
||||
Entry * ce = &root;
|
||||
piForeach (PIString & i, tree) {
|
||||
piForeach(PIString & i, tree) {
|
||||
ce = ce->findChild(i);
|
||||
if (ce == 0)
|
||||
return -1;
|
||||
if (ce == 0) return -1;
|
||||
}
|
||||
return allLeaves().indexOf(ce);
|
||||
}
|
||||
@@ -600,8 +617,7 @@ void PIConfig::removeEntry(Branch & b, PIConfig::Entry * e) {
|
||||
leaf = false;
|
||||
} else {
|
||||
int cc = e->_children.size_s();
|
||||
piForTimes (cc)
|
||||
removeEntry(b, e->_children.back());
|
||||
piForTimes(cc) removeEntry(b, e->_children.back());
|
||||
}
|
||||
bool found = false;
|
||||
for (int i = 0; i < b.size_s(); ++i) {
|
||||
@@ -620,10 +636,16 @@ void PIConfig::removeEntry(Branch & b, PIConfig::Entry * e) {
|
||||
|
||||
PIString PIConfig::getPrefixFromLine(PIString line, bool * exists) {
|
||||
line.trim();
|
||||
if (line.left(1) == "#") {if (exists) *exists = false; return PIString();}
|
||||
if (line.left(1) == "#") {
|
||||
if (exists) *exists = false;
|
||||
return PIString();
|
||||
}
|
||||
int ci = line.find("#");
|
||||
if (ci >= 0) line.cutRight(line.size() - ci);
|
||||
if (line.find("=") >= 0) {if (exists) *exists = false; return PIString();}
|
||||
if (line.find("=") >= 0) {
|
||||
if (exists) *exists = false;
|
||||
return PIString();
|
||||
}
|
||||
if (line.find("[") >= 0 && line.find("]") >= 0) {
|
||||
if (exists) *exists = true;
|
||||
return line.takeRange('[', ']').trim();
|
||||
@@ -634,51 +656,47 @@ PIString PIConfig::getPrefixFromLine(PIString line, bool * exists) {
|
||||
|
||||
|
||||
void PIConfig::writeAll() {
|
||||
//cout << this << " write < " << size() << endl;
|
||||
// cout << this << " write < " << size() << endl;
|
||||
_clearDev();
|
||||
buildFullNames(&root);
|
||||
Branch b = allLeaves();
|
||||
PIString prefix, tprefix;
|
||||
bool isPrefix;
|
||||
//for (int i = 0; i < b.size_s(); ++i)
|
||||
// for (int i = 0; i < b.size_s(); ++i)
|
||||
// cout << b[i]->_name << " = " << b[i]->_value << endl;
|
||||
int j = 0;
|
||||
for (int i = 0; i < other.size_s(); ++i) {
|
||||
//cout << j << endl;
|
||||
// cout << j << endl;
|
||||
if (j >= 0 && j < b.size_s()) {
|
||||
if (b[j]->_line == i) {
|
||||
b[j]->buildLine();
|
||||
_writeDev((b[j]->_all).cutLeft(prefix.size()) + "\n");
|
||||
//cout << this << " " << b[j]->_all << endl;
|
||||
// cout << this << " " << b[j]->_all << endl;
|
||||
++j;
|
||||
} else {
|
||||
_writeDev(other[i]);
|
||||
tprefix = getPrefixFromLine(other[i], &isPrefix);
|
||||
if (isPrefix) {
|
||||
prefix = tprefix;
|
||||
if (!prefix.isEmpty())
|
||||
prefix += delim;
|
||||
if (!prefix.isEmpty()) prefix += delim;
|
||||
}
|
||||
if (i < other.size_s() - 1)
|
||||
_writeDev('\n');
|
||||
//cout << this << " " << other[i] << endl;
|
||||
if (i < other.size_s() - 1) _writeDev('\n');
|
||||
// cout << this << " " << other[i] << endl;
|
||||
}
|
||||
} else {
|
||||
_writeDev(other[i]);
|
||||
tprefix = getPrefixFromLine(other[i], &isPrefix);
|
||||
if (isPrefix) {
|
||||
prefix = tprefix;
|
||||
if (!prefix.isEmpty())
|
||||
prefix += delim;
|
||||
if (!prefix.isEmpty()) prefix += delim;
|
||||
}
|
||||
if (i < other.size_s() - 1)
|
||||
_writeDev('\n');
|
||||
//cout << this << " " << other[i] << endl;
|
||||
if (i < other.size_s() - 1) _writeDev('\n');
|
||||
// cout << this << " " << other[i] << endl;
|
||||
}
|
||||
}
|
||||
_flushDev();
|
||||
readAll();
|
||||
//cout << this << " write > " << size() << endl;
|
||||
// cout << this << " write > " << size() << endl;
|
||||
}
|
||||
|
||||
|
||||
@@ -699,7 +717,7 @@ bool PIConfig::entryExists(const Entry * e, const PIString & name) const {
|
||||
if (e->_children.isEmpty()) {
|
||||
return (e->_name == name);
|
||||
}
|
||||
piForeachC (Entry * i, e->_children)
|
||||
piForeachC(Entry * i, e->_children)
|
||||
if (entryExists(i, name)) return true;
|
||||
return false;
|
||||
}
|
||||
@@ -708,7 +726,7 @@ bool PIConfig::entryExists(const Entry * e, const PIString & name) const {
|
||||
void PIConfig::updateIncludes() {
|
||||
if (internal) return;
|
||||
all_includes.clear();
|
||||
piForeach (PIConfig * c, includes)
|
||||
piForeach(PIConfig * c, includes)
|
||||
all_includes << c->allLeaves();
|
||||
}
|
||||
|
||||
@@ -727,7 +745,7 @@ PIString PIConfig::parseLine(PIString v) {
|
||||
if (ex) {
|
||||
r = me._value;
|
||||
} else {
|
||||
piForeachC (PIConfig::Entry * e, all_includes)
|
||||
piForeachC(PIConfig::Entry * e, all_includes)
|
||||
if (e->_full_name == w) {
|
||||
r = e->_value;
|
||||
break;
|
||||
@@ -740,13 +758,13 @@ PIString PIConfig::parseLine(PIString v) {
|
||||
|
||||
|
||||
void PIConfig::parse() {
|
||||
//piCout << "[PIConfig] charset" << PIFile::defaultCharset();
|
||||
// piCout << "[PIConfig] charset" << PIFile::defaultCharset();
|
||||
PIString src, str, tab, comm, all, name, type, prefix, tprefix;
|
||||
PIStringList tree;
|
||||
Entry * entry = 0, * te = 0, * ce = 0;
|
||||
Entry *entry = 0, *te = 0, *ce = 0;
|
||||
int ind, sind;
|
||||
bool isNew = false, isPrefix = false, wasMultiline = false, isMultiline = false;
|
||||
piForeach (PIConfig * c, inc_devs)
|
||||
piForeach(PIConfig * c, inc_devs)
|
||||
delete c;
|
||||
inc_devs.clear();
|
||||
includes.clear();
|
||||
@@ -760,10 +778,9 @@ void PIConfig::parse() {
|
||||
tprefix = getPrefixFromLine(src, &isPrefix);
|
||||
if (isPrefix) {
|
||||
prefix = tprefix;
|
||||
if (!prefix.isEmpty())
|
||||
prefix += delim;
|
||||
if (!prefix.isEmpty()) prefix += delim;
|
||||
}
|
||||
//piCout << "line \"" << str << "\"";
|
||||
// piCout << "line \"" << str << "\"";
|
||||
tab = str.left(str.find(str.trimmed().left(1)));
|
||||
str.trim();
|
||||
all = str;
|
||||
@@ -774,7 +791,8 @@ void PIConfig::parse() {
|
||||
if (!comm.isEmpty()) {
|
||||
type = comm[0];
|
||||
comm.cutLeft(1).trim();
|
||||
} else type = "s";
|
||||
} else
|
||||
type = "s";
|
||||
str = str.left(sind).trim();
|
||||
} else {
|
||||
type = "s";
|
||||
@@ -798,14 +816,14 @@ void PIConfig::parse() {
|
||||
ce = 0;
|
||||
wasMultiline = isMultiline;
|
||||
|
||||
//piCout << "[PIConfig] str" << str.size() << str << str.toUTF8();
|
||||
// piCout << "[PIConfig] str" << str.size() << str << str.toUTF8();
|
||||
ind = str.find('=');
|
||||
if ((ind > 0) && (str[0] != '#')) {
|
||||
tree = (prefix + str.left(ind).trimmed()).split(delim);
|
||||
if (tree.front() == "include") {
|
||||
name = str.mid(ind + 1).trimmed();
|
||||
PIConfig * iconf = new PIConfig(name, incdirs);
|
||||
//piCout << "include" << name << iconf->dev;
|
||||
// piCout << "include" << name << iconf->dev;
|
||||
if (!iconf->dev) {
|
||||
delete iconf;
|
||||
} else {
|
||||
@@ -818,7 +836,7 @@ void PIConfig::parse() {
|
||||
name = tree.back();
|
||||
tree.pop_back();
|
||||
entry = &root;
|
||||
piForeachC (PIString & i, tree) {
|
||||
piForeachC(PIString & i, tree) {
|
||||
te = entry->findChild(i);
|
||||
if (te == 0) {
|
||||
ce = new Entry();
|
||||
@@ -829,7 +847,8 @@ void PIConfig::parse() {
|
||||
ce->_parent = entry;
|
||||
entry->_children << ce;
|
||||
entry = ce;
|
||||
} else entry = te;
|
||||
} else
|
||||
entry = te;
|
||||
}
|
||||
isNew = false;
|
||||
ce = entry->findChild(name);
|
||||
@@ -843,8 +862,8 @@ void PIConfig::parse() {
|
||||
ce->_value = str.mid(ind + 1).trimmed();
|
||||
ce->_type = type;
|
||||
ce->_comment = comm;
|
||||
//piCout << "[PIConfig] comm" << comm.size() << comm << comm.toUTF8();
|
||||
//piCout << "[PIConfig] type" << type.size() << type << type.toUTF8();
|
||||
// piCout << "[PIConfig] comm" << comm.size() << comm << comm.toUTF8();
|
||||
// piCout << "[PIConfig] type" << type.size() << type << type.toUTF8();
|
||||
ce->_line = lines;
|
||||
ce->_all = all;
|
||||
if (isNew) {
|
||||
@@ -852,7 +871,8 @@ void PIConfig::parse() {
|
||||
entry->_children << ce;
|
||||
}
|
||||
}
|
||||
} else other.back() = src;
|
||||
} else
|
||||
other.back() = src;
|
||||
lines++;
|
||||
}
|
||||
setEntryDelim(&root, delim);
|
||||
@@ -861,13 +881,13 @@ void PIConfig::parse() {
|
||||
|
||||
|
||||
#ifdef PIP_STD_IOSTREAM
|
||||
std::ostream &operator <<(std::ostream & s, const PIConfig::Entry & v) {
|
||||
std::ostream & operator<<(std::ostream & s, const PIConfig::Entry & v) {
|
||||
s << v.value();
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
std::ostream &operator <<(std::ostream & s, const PIConfig::Branch & v) {
|
||||
std::ostream & operator<<(std::ostream & s, const PIConfig::Branch & v) {
|
||||
v.coutt(s, "");
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -16,9 +16,10 @@
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "piincludes_p.h"
|
||||
#include "pidir.h"
|
||||
|
||||
#include "piincludes_p.h"
|
||||
|
||||
|
||||
const PIChar PIDir::separator = '/';
|
||||
#ifdef QNX
|
||||
@@ -70,7 +71,7 @@ PIDir::PIDir(const PIFile & file) {
|
||||
}
|
||||
|
||||
|
||||
bool PIDir::operator ==(const PIDir & d) const {
|
||||
bool PIDir::operator==(const PIDir & d) const {
|
||||
return d.absolutePath() == absolutePath();
|
||||
}
|
||||
|
||||
@@ -150,8 +151,7 @@ PIDir & PIDir::cleanPath() {
|
||||
break;
|
||||
}
|
||||
path_ = l.join(separator);
|
||||
if (is_abs)
|
||||
path_.prepend(separator);
|
||||
if (is_abs) path_.prepend(separator);
|
||||
if (path_.isEmpty()) path_ = ".";
|
||||
return *this;
|
||||
}
|
||||
@@ -160,7 +160,7 @@ PIDir & PIDir::cleanPath() {
|
||||
PIString PIDir::relative(const PIString & path) const {
|
||||
PIDir td(path);
|
||||
PIStringList dl(absolutePath().split(separator)), pl(td.absolutePath().split(separator)), rl;
|
||||
//piCout << pl << "rel to" << dl;
|
||||
// piCout << pl << "rel to" << dl;
|
||||
while (!dl.isEmpty() && !pl.isEmpty()) {
|
||||
if (dl.front() != pl.front()) break;
|
||||
dl.pop_front();
|
||||
@@ -179,8 +179,7 @@ PIDir & PIDir::setDir(const PIString & path) {
|
||||
#ifdef WINDOWS
|
||||
path_.replaceAll("\\", separator);
|
||||
if (path_.length() > 2)
|
||||
if (path_.mid(1, 2).contains(":"))
|
||||
path_.prepend(separator);
|
||||
if (path_.mid(1, 2).contains(":")) path_.prepend(separator);
|
||||
#endif
|
||||
cleanPath();
|
||||
return *this;
|
||||
@@ -197,17 +196,17 @@ PIDir & PIDir::cd(const PIString & path) {
|
||||
|
||||
bool PIDir::make(bool withParents) {
|
||||
PIDir d = cleanedPath();
|
||||
//PIString tp;
|
||||
// PIString tp;
|
||||
#ifndef WINDOWS
|
||||
bool is_abs = isAbsolute();
|
||||
#endif
|
||||
if (withParents) {
|
||||
PIStringList l = d.path().split(separator);
|
||||
//piCout << l;
|
||||
// piCout << l;
|
||||
l.removeAll("");
|
||||
//piCout << l;
|
||||
// piCout << l;
|
||||
PIString cdp;
|
||||
piForeachC (PIString & i, l) {
|
||||
piForeachC(PIString & i, l) {
|
||||
if (!cdp.isEmpty()
|
||||
#ifndef WINDOWS
|
||||
|| is_abs
|
||||
@@ -215,10 +214,9 @@ bool PIDir::make(bool withParents) {
|
||||
)
|
||||
cdp += separator;
|
||||
cdp += i;
|
||||
//piCout << "dir" << cdp;
|
||||
// piCout << "dir" << cdp;
|
||||
if (!isExists(cdp))
|
||||
if (!makeDir(cdp))
|
||||
return false;
|
||||
if (!makeDir(cdp)) return false;
|
||||
}
|
||||
/*for (int i = l.size_s() - 1; i >= 0; --i) {
|
||||
if (i > 1) tp = PIStringList(l).remove(i, l.size_s() - i).join(separator);
|
||||
@@ -238,15 +236,14 @@ bool PIDir::make(bool withParents) {
|
||||
};
|
||||
}*/
|
||||
return true;
|
||||
} else
|
||||
if (makeDir(d.path())) return true;
|
||||
} else if (makeDir(d.path()))
|
||||
return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
bool PIDir::rename(const PIString & new_name) {
|
||||
if (!PIDir::rename(path(), new_name))
|
||||
return false;
|
||||
if (!PIDir::rename(path(), new_name)) return false;
|
||||
setDir(new_name);
|
||||
return true;
|
||||
}
|
||||
@@ -278,8 +275,10 @@ PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
if (!isExists()) return l;
|
||||
PIString dp = absolutePath();
|
||||
PIString p(dp);
|
||||
if (dp == ".") dp.clear();
|
||||
else if (!dp.endsWith(separator)) dp += separator;
|
||||
if (dp == ".")
|
||||
dp.clear();
|
||||
else if (!dp.endsWith(separator))
|
||||
dp += separator;
|
||||
// piCout << "start entries from" << p;
|
||||
#ifdef WINDOWS
|
||||
if (dp == separator) {
|
||||
@@ -298,7 +297,8 @@ PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
clet += PIChar(letters[i]);
|
||||
}
|
||||
} else {
|
||||
WIN32_FIND_DATAA fd; memset(&fd, 0, sizeof(fd));
|
||||
WIN32_FIND_DATAA fd;
|
||||
memset(&fd, 0, sizeof(fd));
|
||||
p += "\\*";
|
||||
void * hf = FindFirstFileA((LPCSTR)(p.data()), &fd);
|
||||
if (!hf) return l;
|
||||
@@ -334,7 +334,9 @@ PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
}
|
||||
# else
|
||||
dirent ** list;
|
||||
int cnt = scandir(p.data(), &list, 0,
|
||||
int cnt = scandir(p.data(),
|
||||
&list,
|
||||
0,
|
||||
# if defined(MAC_OS) || defined(ANDROID) || defined(BLACKBERRY)
|
||||
alphasort);
|
||||
# else
|
||||
@@ -347,7 +349,7 @@ PIVector<PIFile::FileInfo> PIDir::entries() {
|
||||
free(list);
|
||||
# endif
|
||||
#endif
|
||||
// piCout << "end entries from" << p;
|
||||
// piCout << "end entries from" << p;
|
||||
return l;
|
||||
}
|
||||
|
||||
@@ -370,16 +372,17 @@ PIVector<PIFile::FileInfo> PIDir::allEntries() {
|
||||
PIStringList cdirs, ndirs;
|
||||
cdirs << path();
|
||||
while (!cdirs.isEmpty()) {
|
||||
piForeachC (PIString & d, cdirs) {
|
||||
piForeachC(PIString & d, cdirs) {
|
||||
scan_ = d;
|
||||
PIVector<PIFile::FileInfo> el = PIDir(d).entries();
|
||||
piForeachC (PIFile::FileInfo & de, el) {
|
||||
piForeachC(PIFile::FileInfo & de, el) {
|
||||
if (de.name() == "." || de.name() == "..") continue;
|
||||
if (de.isSymbolicLink()) continue; /// TODO: resolve symlinks
|
||||
if (de.isDir()) {
|
||||
dirs << de;
|
||||
ndirs << de.path;
|
||||
} else ret << de;
|
||||
} else
|
||||
ret << de;
|
||||
}
|
||||
}
|
||||
cdirs = ndirs;
|
||||
@@ -391,7 +394,6 @@ PIVector<PIFile::FileInfo> PIDir::allEntries() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool PIDir::isExists(const PIString & path) {
|
||||
#ifdef WINDOWS
|
||||
DWORD ret = GetFileAttributes((LPCTSTR)(path.data()));
|
||||
@@ -434,20 +436,20 @@ PIDir PIDir::home() {
|
||||
#ifdef WINDOWS
|
||||
rc = new char[1024];
|
||||
memset(rc, 0, 1024);
|
||||
if (ExpandEnvironmentStrings((LPCTSTR)"%HOMEPATH%", (LPTSTR)rc, 1024) == 0) {
|
||||
if (ExpandEnvironmentStrings((LPCTSTR) "%HOMEPATH%", (LPTSTR)rc, 1024) == 0) {
|
||||
delete[] rc;
|
||||
return PIDir();
|
||||
}
|
||||
PIString hp(rc);
|
||||
memset(rc, 0, 1024);
|
||||
if (ExpandEnvironmentStrings((LPCTSTR)"%HOMEDRIVE%", (LPTSTR)rc, 1024) == 0) {
|
||||
if (ExpandEnvironmentStrings((LPCTSTR) "%HOMEDRIVE%", (LPTSTR)rc, 1024) == 0) {
|
||||
delete[] rc;
|
||||
return PIDir();
|
||||
}
|
||||
PIString hd(rc);
|
||||
hp.replaceAll("\\", PIDir::separator);
|
||||
delete[] rc;
|
||||
//s.prepend(separator);
|
||||
// s.prepend(separator);
|
||||
return PIDir(hd + hp);
|
||||
#else
|
||||
# ifndef ESP_PLATFORM
|
||||
@@ -485,7 +487,7 @@ PIDir PIDir::temporary() {
|
||||
}
|
||||
|
||||
|
||||
PIVector<PIFile::FileInfo> PIDir::allEntries(const PIString &path) {
|
||||
PIVector<PIFile::FileInfo> PIDir::allEntries(const PIString & path) {
|
||||
return PIDir(path).allEntries();
|
||||
}
|
||||
|
||||
@@ -535,5 +537,3 @@ bool PIDir::renameDir(const PIString & path, const PIString & new_name) {
|
||||
printf("[PIDir] renameDir(\"%s\", \"%s\") error: %s\n", path.data(), new_name.data(), errorString().data());
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -33,10 +33,8 @@
|
||||
//! \~\brief
|
||||
//! \~english Local directory.
|
||||
//! \~russian Локальная директория.
|
||||
class PIP_EXPORT PIDir
|
||||
{
|
||||
class PIP_EXPORT PIDir {
|
||||
public:
|
||||
|
||||
//! \~english Constructs directory with path "dir"
|
||||
//! \~russian Создает директорию с путём "dir"
|
||||
PIDir(const PIString & dir = PIString());
|
||||
@@ -48,7 +46,7 @@ public:
|
||||
|
||||
//! \~english Returns if this directory exists
|
||||
//! \~russian Возвращает существует ли эта директория
|
||||
bool isExists() const {return PIDir::isExists(path());}
|
||||
bool isExists() const { return PIDir::isExists(path()); }
|
||||
|
||||
//! \~english Returns if path of this directory is absolute
|
||||
//! \~russian Возвращает абсолютный ли путь у директории
|
||||
@@ -56,11 +54,11 @@ public:
|
||||
|
||||
//! \~english Returns if path of this directory is relative
|
||||
//! \~russian Возвращает относительный ли путь у директории
|
||||
bool isRelative() const {return !isAbsolute();}
|
||||
bool isRelative() const { return !isAbsolute(); }
|
||||
|
||||
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions
|
||||
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries()
|
||||
const PIString & scanDir() const {return scan_;}
|
||||
const PIString & scanDir() const { return scan_; }
|
||||
|
||||
|
||||
//! \~english Returns path of this directory
|
||||
@@ -77,7 +75,11 @@ public:
|
||||
|
||||
//! \~english Returns %PIDir with simplified path of this directory
|
||||
//! \~russian Возвращает %PIDir с упрощённым путём директории
|
||||
PIDir cleanedPath() const {PIDir d(path()); d.cleanPath(); return d;}
|
||||
PIDir cleanedPath() const {
|
||||
PIDir d(path());
|
||||
d.cleanPath();
|
||||
return d;
|
||||
}
|
||||
|
||||
//! \~english Returns relative to this directory path "path"
|
||||
//! \~russian Возвращает путь "path" относительно этой директории
|
||||
@@ -89,7 +91,7 @@ public:
|
||||
|
||||
//! \~english Set this directory path as current for application
|
||||
//! \~russian Устанавливает путь директории текущим путём приложения
|
||||
bool setCurrent() {return PIDir::setCurrent(path());}
|
||||
bool setCurrent() { return PIDir::setCurrent(path()); }
|
||||
|
||||
|
||||
//! \~english Returns this directory content
|
||||
@@ -106,7 +108,7 @@ public:
|
||||
|
||||
//! \~english Remove this directory
|
||||
//! \~russian Удаляет эту директорию
|
||||
bool remove() {return PIDir::remove(path());}
|
||||
bool remove() { return PIDir::remove(path()); }
|
||||
|
||||
//! \~english Rename this directory
|
||||
//! \~russian Переименовывает эту директорию
|
||||
@@ -118,15 +120,15 @@ public:
|
||||
|
||||
//! \~english Change this directory to parent
|
||||
//! \~russian Изменяет директорию на родительскую
|
||||
PIDir & up() {return cd("..");}
|
||||
PIDir & up() { return cd(".."); }
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
bool operator ==(const PIDir & d) const;
|
||||
bool operator==(const PIDir & d) const;
|
||||
|
||||
//! \~english Compare operator
|
||||
//! \~russian Оператор сравнения
|
||||
bool operator !=(const PIDir & d) const {return !((*this) == d);}
|
||||
bool operator!=(const PIDir & d) const { return !((*this) == d); }
|
||||
|
||||
static const PIChar separator;
|
||||
|
||||
@@ -157,11 +159,11 @@ public:
|
||||
|
||||
//! \~english Remove directory "path"
|
||||
//! \~russian Удаляет директорию "path"
|
||||
static bool remove(const PIString & path) {return removeDir(path);}
|
||||
static bool remove(const PIString & path) { return removeDir(path); }
|
||||
|
||||
//! \~english Rename directory "path"
|
||||
//! \~russian Переименовывает директорию "path"
|
||||
static bool rename(const PIString & path, const PIString & new_name) {return PIDir::renameDir(path, new_name);}
|
||||
static bool rename(const PIString & path, const PIString & new_name) { return PIDir::renameDir(path, new_name); }
|
||||
|
||||
//! \~english Set path "path" as current for application
|
||||
//! \~russian Устанавливает путь "path" текущим путём приложения
|
||||
@@ -169,7 +171,7 @@ public:
|
||||
|
||||
//! \~english Set directory "dir" path as current for application
|
||||
//! \~russian Устанавливает путь директории "dir" текущим путём приложения
|
||||
static bool setCurrent(const PIDir & dir) {return setCurrent(dir.path());}
|
||||
static bool setCurrent(const PIDir & dir) { return setCurrent(dir.path()); }
|
||||
|
||||
private:
|
||||
static bool makeDir(const PIString & path);
|
||||
@@ -177,19 +179,31 @@ private:
|
||||
static bool renameDir(const PIString & path, const PIString & new_name);
|
||||
|
||||
PIString path_, scan_;
|
||||
|
||||
};
|
||||
|
||||
|
||||
inline bool operator <(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path < v1.path);}
|
||||
inline bool operator >(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path > v1.path);}
|
||||
inline bool operator ==(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path == v1.path);}
|
||||
inline bool operator !=(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {return (v0.path != v1.path);}
|
||||
inline bool operator<(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
return (v0.path < v1.path);
|
||||
}
|
||||
inline bool operator>(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
return (v0.path > v1.path);
|
||||
}
|
||||
inline bool operator==(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
return (v0.path == v1.path);
|
||||
}
|
||||
inline bool operator!=(const PIFile::FileInfo & v0, const PIFile::FileInfo & v1) {
|
||||
return (v0.path != v1.path);
|
||||
}
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
inline PICout operator <<(PICout s, const PIDir & v) {s.saveAndSetControls(0); s << "PIDir(\"" << v.path() << "\")"; s.restoreControls(); return s;}
|
||||
inline PICout operator<<(PICout s, const PIDir & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "PIDir(\"" << v.path() << "\")";
|
||||
s.restoreControls();
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
#endif // PIDIR_H
|
||||
|
||||
@@ -16,25 +16,27 @@
|
||||
You should have received a copy of the GNU Lesser General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
#include "piincludes_p.h"
|
||||
#include "piethernet.h"
|
||||
|
||||
#include "piconfig.h"
|
||||
#include "pisysteminfo.h"
|
||||
#include "pipropertystorage.h"
|
||||
#include "piconstchars.h"
|
||||
#include "piincludes_p.h"
|
||||
#include "pipropertystorage.h"
|
||||
#include "pisysteminfo.h"
|
||||
// clang-format off
|
||||
#ifdef QNX
|
||||
# include <arpa/inet.h>
|
||||
# include <fcntl.h>
|
||||
# include <hw/nicinfo.h>
|
||||
# include <ifaddrs.h>
|
||||
# include <net/if.h>
|
||||
# include <net/if_dl.h>
|
||||
# include <hw/nicinfo.h>
|
||||
# include <netdb.h>
|
||||
# include <netinet/in.h>
|
||||
# include <sys/ioctl.h>
|
||||
# include <sys/socket.h>
|
||||
# include <sys/time.h>
|
||||
# include <sys/types.h>
|
||||
# include <sys/ioctl.h>
|
||||
# include <netinet/in.h>
|
||||
# include <arpa/inet.h>
|
||||
# include <ifaddrs.h>
|
||||
# include <fcntl.h>
|
||||
# ifdef BLACKBERRY
|
||||
# include <netinet/in.h>
|
||||
# else
|
||||
@@ -67,7 +69,9 @@
|
||||
# endif
|
||||
# endif
|
||||
#endif
|
||||
// clang-format on
|
||||
#include "piwaitevent_p.h"
|
||||
|
||||
#include <errno.h>
|
||||
|
||||
|
||||
@@ -95,7 +99,7 @@
|
||||
|
||||
#ifndef WINDOWS
|
||||
PIString getSockAddr(sockaddr * s) {
|
||||
return s == 0 ? PIString() : PIStringAscii(inet_ntoa(((sockaddr_in*)s)->sin_addr));
|
||||
return s == 0 ? PIString() : PIStringAscii(inet_ntoa(((sockaddr_in *)s)->sin_addr));
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -145,7 +149,8 @@ void PIEthernet::Address::setPort(ushort _port) {
|
||||
|
||||
|
||||
void PIEthernet::Address::set(const PIString & ip_port) {
|
||||
PIString _ip; int p(0);
|
||||
PIString _ip;
|
||||
int p(0);
|
||||
splitIPPort(ip_port, &_ip, &p);
|
||||
port_ = p;
|
||||
initIP(_ip);
|
||||
@@ -176,7 +181,8 @@ bool PIEthernet::Address::isNull() const {
|
||||
|
||||
|
||||
PIEthernet::Address PIEthernet::Address::resolve(const PIString & host_port) {
|
||||
PIString host; int port(0);
|
||||
PIString host;
|
||||
int port(0);
|
||||
splitIPPort(host_port, &host, &port);
|
||||
return resolve(host, port);
|
||||
}
|
||||
@@ -185,16 +191,14 @@ PIEthernet::Address PIEthernet::Address::resolve(const PIString & host_port) {
|
||||
PIEthernet::Address PIEthernet::Address::resolve(const PIString & host, ushort port) {
|
||||
Address ret(0, port);
|
||||
hostent * he = gethostbyname(host.dataAscii());
|
||||
if (!he)
|
||||
return ret;
|
||||
if (he->h_addr_list[0])
|
||||
ret.setIP(*((uint*)(he->h_addr_list[0])));
|
||||
if (!he) return ret;
|
||||
if (he->h_addr_list[0]) ret.setIP(*((uint *)(he->h_addr_list[0])));
|
||||
return ret;
|
||||
}
|
||||
|
||||
|
||||
void PIEthernet::Address::splitIPPort(const PIString & ipp, PIString * _ip, int * _port) {
|
||||
//piCout << "parse" << ipp;
|
||||
// piCout << "parse" << ipp;
|
||||
int sp = ipp.findLast(":");
|
||||
if (_ip != 0) *_ip = (sp >= 0 ? ipp.left(sp) : ipp);
|
||||
if (_port != 0 && sp >= 0) *_port = ipp.right(ipp.length() - ipp.find(":") - 1).toInt();
|
||||
@@ -224,7 +228,8 @@ PIEthernet::PIEthernet(): PIIODevice("", ReadWrite) {
|
||||
}
|
||||
|
||||
|
||||
PIEthernet::PIEthernet(PIEthernet::Type type_, const PIString & ip_port, const PIFlags<PIEthernet::Parameters> params_): PIIODevice(ip_port, ReadWrite) {
|
||||
PIEthernet::PIEthernet(PIEthernet::Type type_, const PIString & ip_port, const PIFlags<PIEthernet::Parameters> params_)
|
||||
: PIIODevice(ip_port, ReadWrite) {
|
||||
construct();
|
||||
addr_r.set(ip_port);
|
||||
setType(type_);
|
||||
@@ -244,21 +249,21 @@ PIEthernet::PIEthernet(int sock_, PIString ip_port): PIIODevice("", ReadWrite) {
|
||||
setPath(ip_port);
|
||||
ethNonblocking(sock);
|
||||
PRIVATE->event.create();
|
||||
//piCoutObj << "new tcp client" << sock_;
|
||||
// piCoutObj << "new tcp client" << sock_;
|
||||
}
|
||||
|
||||
|
||||
PIEthernet::~PIEthernet() {
|
||||
//piCout << "~PIEthernet";
|
||||
// piCout << "~PIEthernet";
|
||||
stopAndWait();
|
||||
close();
|
||||
PRIVATE->event.destroy();
|
||||
//piCout << "~PIEthernet done";
|
||||
// piCout << "~PIEthernet done";
|
||||
}
|
||||
|
||||
|
||||
void PIEthernet::construct() {
|
||||
//piCout << " PIEthernet" << uint(this);
|
||||
// piCout << " PIEthernet" << uint(this);
|
||||
setOption(BlockingWrite);
|
||||
connected_ = connecting_ = listen_threaded = server_bounded = false;
|
||||
sock = sock_s = -1;
|
||||
@@ -273,17 +278,16 @@ void PIEthernet::construct() {
|
||||
#else
|
||||
setThreadedReadBufferSize(65536);
|
||||
#endif
|
||||
//setPriority(piHigh);
|
||||
// setPriority(piHigh);
|
||||
}
|
||||
|
||||
|
||||
bool PIEthernet::init() {
|
||||
if (isOpened()) return true;
|
||||
if (sock != -1) return true;
|
||||
//piCout << "init " << type();
|
||||
// piCout << "init " << type();
|
||||
PRIVATE->event.destroy();
|
||||
if (sock_s == sock)
|
||||
sock_s = -1;
|
||||
if (sock_s == sock) sock_s = -1;
|
||||
closeSocket(sock);
|
||||
closeSocket(sock_s);
|
||||
int st = 0, pr = 0;
|
||||
@@ -309,7 +313,7 @@ bool PIEthernet::init() {
|
||||
if (params[PIEthernet::Broadcast]) ethSetsockoptBool(sock, SOL_SOCKET, SO_BROADCAST);
|
||||
applyTimeouts();
|
||||
applyOptInt(IPPROTO_IP, IP_TTL, TTL());
|
||||
//piCoutObj << "inited" << path();
|
||||
// piCoutObj << "inited" << path();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -324,10 +328,10 @@ PIString PIEthernet::macFromBytes(const PIByteArray & mac) {
|
||||
}
|
||||
|
||||
|
||||
PIByteArray PIEthernet::macToBytes(const PIString & mac) {
|
||||
PIByteArray PIEthernet::macToBytes(const PIString & mac) {
|
||||
PIByteArray r;
|
||||
PIStringList sl = mac.split(PIStringAscii(":"));
|
||||
piForeachC (PIString & i, sl)
|
||||
piForeachC(PIString & i, sl)
|
||||
r << uchar(i.toInt(16));
|
||||
return r;
|
||||
}
|
||||
@@ -363,25 +367,26 @@ PIEthernet::Address PIEthernet::getBroadcast(const PIEthernet::Address & ip, con
|
||||
|
||||
bool PIEthernet::openDevice() {
|
||||
if (connected_) return true;
|
||||
//piCoutObj << "open";
|
||||
// piCoutObj << "open";
|
||||
init();
|
||||
if (sock == -1 || path().isEmpty()) return false;
|
||||
addr_r.set(path());
|
||||
//if (type() == TCP_Client)
|
||||
// if (type() == TCP_Client)
|
||||
// connecting_ = true;
|
||||
if (type() != UDP || mode() == PIIODevice::WriteOnly)
|
||||
return true;
|
||||
if (type() != UDP || mode() == PIIODevice::WriteOnly) return true;
|
||||
memset(&PRIVATE->addr_, 0, sizeof(PRIVATE->addr_));
|
||||
PRIVATE->addr_.sin_family = AF_INET;
|
||||
PRIVATE->addr_.sin_port = htons(addr_r.port());
|
||||
if (params[PIEthernet::Broadcast]) PRIVATE->addr_.sin_addr.s_addr = INADDR_ANY;
|
||||
else PRIVATE->addr_.sin_addr.s_addr = addr_r.ip();
|
||||
if (params[PIEthernet::Broadcast])
|
||||
PRIVATE->addr_.sin_addr.s_addr = INADDR_ANY;
|
||||
else
|
||||
PRIVATE->addr_.sin_addr.s_addr = addr_r.ip();
|
||||
#ifdef QNX
|
||||
PRIVATE->addr_.sin_len = sizeof(PRIVATE->addr_);
|
||||
#endif
|
||||
//piCout << "bind to" << (params[PIEthernet::Broadcast] ? "255.255.255.255" : ip_) << ":" << port_ << " ...";
|
||||
// piCout << "bind to" << (params[PIEthernet::Broadcast] ? "255.255.255.255" : ip_) << ":" << port_ << " ...";
|
||||
int tries = 0;
|
||||
while ((bind(sock, (sockaddr * )&PRIVATE->addr_, sizeof(PRIVATE->addr_)) == -1) && (tries < 2)) {
|
||||
while ((bind(sock, (sockaddr *)&PRIVATE->addr_, sizeof(PRIVATE->addr_)) == -1) && (tries < 2)) {
|
||||
init();
|
||||
tries++;
|
||||
}
|
||||
@@ -400,24 +405,22 @@ bool PIEthernet::openDevice() {
|
||||
|
||||
|
||||
bool PIEthernet::closeDevice() {
|
||||
//piCoutObj << "close";
|
||||
// piCoutObj << "close";
|
||||
bool ned = connected_;
|
||||
connected_ = connecting_ = false;
|
||||
server_thread_.stop();
|
||||
PRIVATE->event.interrupt();
|
||||
if (server_thread_.isRunning()) {
|
||||
if (!server_thread_.waitForFinish(1000))
|
||||
server_thread_.terminate();
|
||||
if (!server_thread_.waitForFinish(1000)) server_thread_.terminate();
|
||||
}
|
||||
PRIVATE->event.destroy();
|
||||
if (sock_s == sock)
|
||||
sock_s = -1;
|
||||
if (sock_s == sock) sock_s = -1;
|
||||
closeSocket(sock);
|
||||
closeSocket(sock_s);
|
||||
while (!clients_.isEmpty())
|
||||
delete clients_.back();
|
||||
if (ned) {
|
||||
//piCoutObj << "Disconnect on close";
|
||||
// piCoutObj << "Disconnect on close";
|
||||
disconnected(false);
|
||||
}
|
||||
return true;
|
||||
@@ -425,8 +428,7 @@ bool PIEthernet::closeDevice() {
|
||||
|
||||
|
||||
void PIEthernet::closeSocket(int & sd) {
|
||||
if (sd != -1)
|
||||
ethClosesocket(sd, type() != PIEthernet::UDP);
|
||||
if (sd != -1) ethClosesocket(sd, type() != PIEthernet::UDP);
|
||||
sd = -1;
|
||||
}
|
||||
|
||||
@@ -445,13 +447,14 @@ void PIEthernet::applyTimeouts() {
|
||||
|
||||
void PIEthernet::applyTimeout(int fd, int opt, double ms) {
|
||||
if (fd == 0) return;
|
||||
//piCoutObj << "setReadIsBlocking" << yes;
|
||||
// piCoutObj << "setReadIsBlocking" << yes;
|
||||
#ifdef WINDOWS
|
||||
DWORD _tm = ms;
|
||||
#else
|
||||
double s = ms / 1000.;
|
||||
timeval _tm;
|
||||
_tm.tv_sec = piFloord(s); s -= _tm.tv_sec;
|
||||
_tm.tv_sec = piFloord(s);
|
||||
s -= _tm.tv_sec;
|
||||
_tm.tv_usec = s * 1000000.;
|
||||
#endif
|
||||
ethSetsockopt(fd, SOL_SOCKET, opt, &_tm, sizeof(_tm));
|
||||
@@ -461,8 +464,7 @@ void PIEthernet::applyTimeout(int fd, int opt, double ms) {
|
||||
void PIEthernet::applyOptInt(int level, int opt, int val) {
|
||||
if (sock < 0) return;
|
||||
ethSetsockoptInt(sock, level, opt, val);
|
||||
if (sock_s != sock && sock_s != -1)
|
||||
ethSetsockoptInt(sock_s, level, opt, val);
|
||||
if (sock_s != sock && sock_s != -1) ethSetsockoptInt(sock_s, level, opt, val);
|
||||
}
|
||||
|
||||
|
||||
@@ -474,8 +476,7 @@ bool PIEthernet::joinMulticastGroup(const PIString & group) {
|
||||
return false;
|
||||
}
|
||||
if (isClosed()) {
|
||||
if (mcast_queue.contains(group))
|
||||
return false;
|
||||
if (mcast_queue.contains(group)) return false;
|
||||
mcast_queue.enqueue(group);
|
||||
if (!mcast_groups.contains(group)) mcast_groups << group;
|
||||
return true;
|
||||
@@ -488,7 +489,7 @@ bool PIEthernet::joinMulticastGroup(const PIString & group) {
|
||||
#endif
|
||||
memset(&mreq, 0, sizeof(mreq));
|
||||
#ifdef LINUX
|
||||
//mreq.imr_address.s_addr = INADDR_ANY;
|
||||
// mreq.imr_address.s_addr = INADDR_ANY;
|
||||
/*PIEthernet::InterfaceList il = interfaces();
|
||||
const PIEthernet::Interface * ci = il.getByAddress(addr_r.ipString());
|
||||
if (ci != 0) mreq.imr_ifindex = ci->index;*/
|
||||
@@ -506,7 +507,7 @@ bool PIEthernet::joinMulticastGroup(const PIString & group) {
|
||||
mreq.imr_interface.s_addr = addr_r.ip();
|
||||
#endif
|
||||
|
||||
//piCout << "join group" << group << "ip" << ip_ << "with index" << mreq.imr_ifindex << "socket" << sock;
|
||||
// piCout << "join group" << group << "ip" << ip_ << "with index" << mreq.imr_ifindex << "socket" << sock;
|
||||
mreq.imr_multiaddr.s_addr = inet_addr(group.dataAscii());
|
||||
if (ethSetsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) != 0) {
|
||||
piCoutObj << "Can`t join multicast group" << group << "," << ethErrorString();
|
||||
@@ -592,8 +593,7 @@ bool PIEthernet::listen(bool threaded) {
|
||||
if (server_thread_.isRunning()) {
|
||||
if (!server_bounded) return true;
|
||||
server_thread_.stop();
|
||||
if (!server_thread_.waitForFinish(100))
|
||||
server_thread_.terminate();
|
||||
if (!server_thread_.waitForFinish(100)) server_thread_.terminate();
|
||||
}
|
||||
listen_threaded = true;
|
||||
server_bounded = false;
|
||||
@@ -611,7 +611,7 @@ bool PIEthernet::listen(bool threaded) {
|
||||
#endif
|
||||
opened_ = false;
|
||||
int tries = 0;
|
||||
while ((bind(sock, (sockaddr * )&PRIVATE->addr_, sizeof(PRIVATE->addr_)) == -1) && (tries < 2)) {
|
||||
while ((bind(sock, (sockaddr *)&PRIVATE->addr_, sizeof(PRIVATE->addr_)) == -1) && (tries < 2)) {
|
||||
init();
|
||||
tries++;
|
||||
}
|
||||
@@ -620,7 +620,7 @@ bool PIEthernet::listen(bool threaded) {
|
||||
return false;
|
||||
}
|
||||
if (::listen(sock, 64) == -1) {
|
||||
piCoutObj << "Can`t listen on"<< addr_r << "," << ethErrorString();
|
||||
piCoutObj << "Can`t listen on" << addr_r << "," << ethErrorString();
|
||||
return false;
|
||||
}
|
||||
opened_ = server_bounded = true;
|
||||
@@ -682,17 +682,17 @@ bool PIEthernet::send(const PIEthernet::Address & addr, const PIByteArray & data
|
||||
|
||||
|
||||
void PIEthernet::interrupt() {
|
||||
//piCout << "interrupt";
|
||||
// piCout << "interrupt";
|
||||
PRIVATE->event.interrupt();
|
||||
}
|
||||
|
||||
|
||||
ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
//piCout << "read" << sock;
|
||||
// piCout << "read" << sock;
|
||||
if (sock == -1) init();
|
||||
if (sock == -1 || read_to == 0) return -1;
|
||||
int rs = 0, lerr = 0;
|
||||
//piCoutObj << "read from " << path() << connecting_;
|
||||
// piCoutObj << "read from " << path() << connecting_;
|
||||
switch (type()) {
|
||||
case TCP_Client:
|
||||
if (connecting_) {
|
||||
@@ -704,18 +704,17 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
#ifdef QNX
|
||||
PRIVATE->addr_.sin_len = sizeof(PRIVATE->addr_);
|
||||
#endif
|
||||
//piCoutObj << "connect to " << path() << "...";
|
||||
// piCoutObj << "connect to " << path() << "...";
|
||||
connected_ = connectTCP();
|
||||
//piCoutObj << "connect to " << path() << connected_;
|
||||
if (!connected_)
|
||||
piCoutObj << "Can`t connect to" << addr_r << "," << ethErrorString();
|
||||
// piCoutObj << "connect to " << path() << connected_;
|
||||
if (!connected_) piCoutObj << "Can`t connect to" << addr_r << "," << ethErrorString();
|
||||
opened_.exchange(connected_);
|
||||
if (connected_) {
|
||||
connecting_ = false;
|
||||
connected();
|
||||
} else
|
||||
piMSleep(10);
|
||||
//piCout << "connected to" << path();
|
||||
// piCout << "connected to" << path();
|
||||
}
|
||||
if (!connected_) return -1;
|
||||
errorClear();
|
||||
@@ -725,11 +724,11 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
switch (wr) {
|
||||
case 0: return -1;
|
||||
case FD_READ:
|
||||
//piCout << "fd_read ...";
|
||||
// piCout << "fd_read ...";
|
||||
rs = ethRecv(sock, read_to, max_size);
|
||||
break;
|
||||
case FD_CLOSE:
|
||||
//piCout << "fd_close ...";
|
||||
// piCout << "fd_close ...";
|
||||
rs = -1;
|
||||
break;
|
||||
default: break;
|
||||
@@ -741,10 +740,10 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
rs = ethRecv(sock, read_to, max_size);
|
||||
}
|
||||
#endif
|
||||
//piCoutObj << "readed" << rs;
|
||||
// piCoutObj << "readed" << rs;
|
||||
if (rs <= 0) {
|
||||
lerr = ethErrorCore();
|
||||
//piCoutObj << "readed" << rs << "error" << lerr;
|
||||
// piCoutObj << "readed" << rs << "error" << lerr;
|
||||
|
||||
// async normal returns
|
||||
#ifdef WINDOWS
|
||||
@@ -752,7 +751,7 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
#else
|
||||
if (lerr == EWOULDBLOCK || lerr == EAGAIN || lerr == EINTR) {
|
||||
#endif
|
||||
//piCoutObj << "Ignore would_block" << lerr;
|
||||
// piCoutObj << "Ignore would_block" << lerr;
|
||||
return -1;
|
||||
}
|
||||
|
||||
@@ -763,15 +762,15 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
#else
|
||||
if (lerr == ETIMEDOUT) {
|
||||
#endif
|
||||
//piCoutObj << "Ignore read timeout";
|
||||
// piCoutObj << "Ignore read timeout";
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
// disconnect here
|
||||
//piCoutObj << "Disconnnected, check for event, connected =" << connected_;
|
||||
// piCoutObj << "Disconnnected, check for event, connected =" << connected_;
|
||||
if (connected_.exchange(false)) {
|
||||
opened_ = false;
|
||||
//piCoutObj << "Disconnect on read," << ethErrorString();
|
||||
// piCoutObj << "Disconnect on read," << ethErrorString();
|
||||
closeSocket(sock);
|
||||
init();
|
||||
disconnected(rs < 0);
|
||||
@@ -779,36 +778,36 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
if (params[KeepConnection]) {
|
||||
connect();
|
||||
}
|
||||
//piCoutObj << "eth" << ip_ << "disconnected";
|
||||
// piCoutObj << "eth" << ip_ << "disconnected";
|
||||
}
|
||||
if (rs > 0) received(read_to, rs);
|
||||
return rs;
|
||||
case UDP: {
|
||||
memset(&PRIVATE->raddr_, 0, sizeof(PRIVATE->raddr_));
|
||||
//piCoutObj << "read from" << path() << "...";
|
||||
// piCoutObj << "read from" << path() << "...";
|
||||
#ifdef WINDOWS
|
||||
long wr = waitForEvent(PRIVATE->event, FD_READ | FD_CLOSE);
|
||||
switch (wr) {
|
||||
case FD_READ:
|
||||
//piCout << "fd_read ...";
|
||||
rs = ethRecvfrom(sock, read_to, max_size, 0, (sockaddr*)&PRIVATE->raddr_);
|
||||
// piCout << "fd_read ...";
|
||||
rs = ethRecvfrom(sock, read_to, max_size, 0, (sockaddr *)&PRIVATE->raddr_);
|
||||
break;
|
||||
case FD_CLOSE:
|
||||
//piCout << "fd_close ...";
|
||||
// piCout << "fd_close ...";
|
||||
rs = -1;
|
||||
break;
|
||||
default: break;
|
||||
}
|
||||
#else
|
||||
rs = ethRecvfrom(sock, read_to, max_size, 0, (sockaddr*)&PRIVATE->raddr_);
|
||||
rs = ethRecvfrom(sock, read_to, max_size, 0, (sockaddr *)&PRIVATE->raddr_);
|
||||
#endif
|
||||
//piCoutObj << "read from" << path() << rs << "bytes";
|
||||
// piCoutObj << "read from" << path() << rs << "bytes";
|
||||
if (rs > 0) {
|
||||
addr_lr.set(uint(PRIVATE->raddr_.sin_addr.s_addr), ntohs(PRIVATE->raddr_.sin_port));
|
||||
//piCoutObj << "read from" << ip_r << ":" << port_r << rs << "bytes";
|
||||
// piCoutObj << "read from" << ip_r << ":" << port_r << rs << "bytes";
|
||||
received(read_to, rs);
|
||||
}
|
||||
//else piCoutObj << "read returt" << rs << ", error" << ethErrorString();
|
||||
// else piCoutObj << "read returt" << rs << ", error" << ethErrorString();
|
||||
return rs;
|
||||
}
|
||||
default: break;
|
||||
@@ -820,25 +819,29 @@ ssize_t PIEthernet::readDevice(void * read_to, ssize_t max_size) {
|
||||
ssize_t PIEthernet::writeDevice(const void * data, ssize_t max_size) {
|
||||
if (sock == -1) init();
|
||||
if (sock == -1 || !isWriteable()) {
|
||||
//piCoutObj << "Can`t send to uninitialized socket";
|
||||
// piCoutObj << "Can`t send to uninitialized socket";
|
||||
return -1;
|
||||
}
|
||||
//piCoutObj << "sending to " << ip_s << ":" << port_s << " " << max_size << " bytes";
|
||||
// piCoutObj << "sending to " << ip_s << ":" << port_s << " " << max_size << " bytes";
|
||||
int ret = 0;
|
||||
switch (type()) {
|
||||
case UDP:
|
||||
PRIVATE->saddr_.sin_port = htons(addr_s.port());
|
||||
PRIVATE->saddr_.sin_addr.s_addr = addr_s.ip();
|
||||
PRIVATE->saddr_.sin_family = AF_INET;
|
||||
//piCoutObj << "write to" << ip_s << ":" << port_s << "socket" << sock_s << max_size << "bytes ...";
|
||||
return ethSendto(sock_s, data, max_size,
|
||||
// piCoutObj << "write to" << ip_s << ":" << port_s << "socket" << sock_s << max_size << "bytes ...";
|
||||
return ethSendto(sock_s,
|
||||
data,
|
||||
max_size,
|
||||
#ifndef WINDOWS
|
||||
isOptionSet(BlockingWrite) ? 0 : MSG_DONTWAIT
|
||||
#else
|
||||
0
|
||||
#endif
|
||||
, (sockaddr * )&PRIVATE->saddr_, sizeof(PRIVATE->saddr_));
|
||||
//piCout << "[PIEth] write to" << ip_s << ":" << port_s << "ok";
|
||||
,
|
||||
(sockaddr *)&PRIVATE->saddr_,
|
||||
sizeof(PRIVATE->saddr_));
|
||||
// piCout << "[PIEth] write to" << ip_s << ":" << port_s << "ok";
|
||||
case TCP_Client: {
|
||||
if (connecting_) {
|
||||
memset(&PRIVATE->addr_, 0, sizeof(PRIVATE->addr_));
|
||||
@@ -849,10 +852,9 @@ ssize_t PIEthernet::writeDevice(const void * data, ssize_t max_size) {
|
||||
#ifdef QNX
|
||||
PRIVATE->addr_.sin_len = sizeof(PRIVATE->addr_);
|
||||
#endif
|
||||
//piCoutObj << "connect to " << ip << ":" << port_;
|
||||
// piCoutObj << "connect to " << ip << ":" << port_;
|
||||
connected_ = connectTCP();
|
||||
if (!connected_)
|
||||
piCoutObj << "Can`t connect to" << addr_r << "," << ethErrorString();
|
||||
if (!connected_) piCoutObj << "Can`t connect to" << addr_r << "," << ethErrorString();
|
||||
opened_.exchange(connected_);
|
||||
if (connected_) {
|
||||
connecting_ = false;
|
||||
@@ -860,10 +862,10 @@ ssize_t PIEthernet::writeDevice(const void * data, ssize_t max_size) {
|
||||
}
|
||||
}
|
||||
if (!connected_) return -1;
|
||||
auto disconnectFunc = [this](){
|
||||
auto disconnectFunc = [this]() {
|
||||
if (connected_.exchange(false)) {
|
||||
opened_ = false;
|
||||
//piCoutObj << "Disconnect on write," << ethErrorString();
|
||||
// piCoutObj << "Disconnect on write," << ethErrorString();
|
||||
closeSocket(sock);
|
||||
init();
|
||||
disconnected(true);
|
||||
@@ -888,7 +890,7 @@ ssize_t PIEthernet::writeDevice(const void * data, ssize_t max_size) {
|
||||
if (err == EAGAIN || err == EWOULDBLOCK) {
|
||||
#endif
|
||||
piMinSleep();
|
||||
//piCoutObj << "wait for write";
|
||||
// piCoutObj << "wait for write";
|
||||
continue;
|
||||
} else {
|
||||
disconnectFunc();
|
||||
@@ -899,7 +901,8 @@ ssize_t PIEthernet::writeDevice(const void * data, ssize_t max_size) {
|
||||
remain_size -= sr;
|
||||
}
|
||||
}
|
||||
return ret;}
|
||||
return ret;
|
||||
}
|
||||
default: break;
|
||||
}
|
||||
return -1;
|
||||
@@ -919,13 +922,13 @@ PIIODevice::DeviceInfoFlags PIEthernet::deviceInfoFlags() const {
|
||||
|
||||
void PIEthernet::clientDeleted(PIObject * o) {
|
||||
clients_mutex.lock();
|
||||
clients_.removeOne((PIEthernet*)o);
|
||||
clients_.removeOne((PIEthernet *)o);
|
||||
clients_mutex.unlock();
|
||||
}
|
||||
|
||||
|
||||
void PIEthernet::server_func(void * eth) {
|
||||
PIEthernet * ce = (PIEthernet * )eth;
|
||||
PIEthernet * ce = (PIEthernet *)eth;
|
||||
if (ce->listen_threaded) {
|
||||
if (!ce->server_bounded) {
|
||||
if (!ce->listen(false)) {
|
||||
@@ -949,9 +952,9 @@ void PIEthernet::server_func(void * eth) {
|
||||
return;
|
||||
}
|
||||
#endif
|
||||
//piCout << "server" << "accept ...";
|
||||
int s = accept(ce->sock, (sockaddr * )&client_addr, &slen);
|
||||
//piCout << "server" << "accept done" << ethErrorString();
|
||||
// piCout << "server" << "accept ...";
|
||||
int s = accept(ce->sock, (sockaddr *)&client_addr, &slen);
|
||||
// piCout << "server" << "accept done" << ethErrorString();
|
||||
if (s == -1) {
|
||||
int lerr = ethErrorCore();
|
||||
#ifdef WINDOWS
|
||||
@@ -976,7 +979,7 @@ void PIEthernet::server_func(void * eth) {
|
||||
ce->clients_ << e;
|
||||
ce->clients_mutex.unlock();
|
||||
ce->newConnection(e);
|
||||
//cout << "connected " << ip << endl;
|
||||
// cout << "connected " << ip << endl;
|
||||
}
|
||||
|
||||
|
||||
@@ -992,19 +995,20 @@ void PIEthernet::setType(Type t, bool reopen) {
|
||||
|
||||
|
||||
bool PIEthernet::connectTCP() {
|
||||
::connect(sock, (sockaddr * )&(PRIVATE->addr_), sizeof(PRIVATE->addr_));
|
||||
//piCout << errorString();
|
||||
::connect(sock, (sockaddr *)&(PRIVATE->addr_), sizeof(PRIVATE->addr_));
|
||||
// piCout << errorString();
|
||||
#ifdef WINDOWS
|
||||
long wr = waitForEvent(PRIVATE->event, FD_CONNECT | FD_CLOSE);
|
||||
switch (wr) {
|
||||
case FD_CONNECT:
|
||||
//piCout << "fd_connect ...";
|
||||
// piCout << "fd_connect ...";
|
||||
return ethIsWriteable(sock);
|
||||
default: break;
|
||||
}
|
||||
#else
|
||||
if (PRIVATE->event.wait(sock, PIWaitEvent::CheckWrite)) {
|
||||
if (ethIsWriteable(sock)) return true;
|
||||
if (ethIsWriteable(sock))
|
||||
return true;
|
||||
else {
|
||||
closeSocket(sock);
|
||||
init();
|
||||
@@ -1019,16 +1023,15 @@ bool PIEthernet::connectTCP() {
|
||||
long PIEthernet::waitForEvent(PIWaitEvent & event, long mask) {
|
||||
if (!event.isCreate() || sock < 0) return 0;
|
||||
if (WSAEventSelect(sock, event.getEvent(), mask) == SOCKET_ERROR) {
|
||||
if (ethErrorCore() == WSAEINPROGRESS)
|
||||
return 0;
|
||||
if (ethErrorCore() == WSAEINPROGRESS) return 0;
|
||||
}
|
||||
if (event.wait()) {
|
||||
//DWORD wr = WSAWaitForMultipleEvents(1, &(PRIVATE->read_event), FALSE, WSA_INFINITE, TRUE);
|
||||
//if (wr == WSA_WAIT_EVENT_0) {
|
||||
// DWORD wr = WSAWaitForMultipleEvents(1, &(PRIVATE->read_event), FALSE, WSA_INFINITE, TRUE);
|
||||
// if (wr == WSA_WAIT_EVENT_0) {
|
||||
WSANETWORKEVENTS events;
|
||||
memset(&events, 0, sizeof(events));
|
||||
WSAEnumNetworkEvents(sock, event.getEvent(), &events);
|
||||
//piCoutObj << "wait result" << events.lNetworkEvents;
|
||||
// piCoutObj << "wait result" << events.lNetworkEvents;
|
||||
return events.lNetworkEvents;
|
||||
}
|
||||
return 0;
|
||||
@@ -1037,8 +1040,8 @@ long PIEthernet::waitForEvent(PIWaitEvent & event, long mask) {
|
||||
|
||||
|
||||
bool PIEthernet::configureDevice(const void * e_main, const void * e_parent) {
|
||||
PIConfig::Entry * em = (PIConfig::Entry * )e_main;
|
||||
PIConfig::Entry * ep = (PIConfig::Entry * )e_parent;
|
||||
PIConfig::Entry * em = (PIConfig::Entry *)e_main;
|
||||
PIConfig::Entry * ep = (PIConfig::Entry *)e_parent;
|
||||
setReadIP(readDeviceSetting<PIString>("ip", readIP(), em, ep));
|
||||
setReadPort(readDeviceSetting<int>("port", readPort(), em, ep));
|
||||
setParameter(PIEthernet::Broadcast, readDeviceSetting<bool>("broadcast", isParameterSet(PIEthernet::Broadcast), em, ep));
|
||||
@@ -1061,7 +1064,7 @@ PIString PIEthernet::constructFullPathDevice() const {
|
||||
ret += ":" + readIP() + ":" + PIString::fromNumber(readPort());
|
||||
if (type() == PIEthernet::UDP) {
|
||||
ret += ":" + sendIP() + ":" + PIString::fromNumber(sendPort());
|
||||
piForeachC (PIString & m, multicastGroups())
|
||||
piForeachC(PIString & m, multicastGroups())
|
||||
ret += ":mcast:" + m;
|
||||
}
|
||||
return ret;
|
||||
@@ -1079,14 +1082,26 @@ void PIEthernet::configureFromFullPathDevice(const PIString & full_path) {
|
||||
if (p == "udp") setType(UDP);
|
||||
if (p == "tcp") setType(TCP_Client);
|
||||
break;
|
||||
case 1: setReadIP(p); setSendIP(p); break;
|
||||
case 2: setReadPort(p.toInt()); setSendPort(p.toInt()); break;
|
||||
case 1:
|
||||
setReadIP(p);
|
||||
setSendIP(p);
|
||||
break;
|
||||
case 2:
|
||||
setReadPort(p.toInt());
|
||||
setSendPort(p.toInt());
|
||||
break;
|
||||
case 3: setSendIP(p); break;
|
||||
case 4: setSendPort(p.toInt()); break;
|
||||
}
|
||||
if (i <= 4) continue;
|
||||
if (i % 2 == 1) {if (p.toLowerCase() == "mcast") mcast = true;}
|
||||
else {if (mcast) {joinMulticastGroup(p); mcast = false;}}
|
||||
if (i % 2 == 1) {
|
||||
if (p.toLowerCase() == "mcast") mcast = true;
|
||||
} else {
|
||||
if (mcast) {
|
||||
joinMulticastGroup(p);
|
||||
mcast = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1095,7 +1110,8 @@ PIPropertyStorage PIEthernet::constructVariantDevice() const {
|
||||
PIPropertyStorage ret;
|
||||
PIVariantTypes::Enum e;
|
||||
|
||||
e << "UDP" << "TCP";
|
||||
e << "UDP"
|
||||
<< "TCP";
|
||||
if (type() == PIEthernet::UDP)
|
||||
e.selectValue(0);
|
||||
else
|
||||
@@ -1118,14 +1134,14 @@ void PIEthernet::configureFromVariantDevice(const PIPropertyStorage & d) {
|
||||
setSendIP(d.propertyValueByName("send IP").toString());
|
||||
setSendPort(d.propertyValueByName("send port").toInt());
|
||||
PIStringList mcgl = d.propertyValueByName("multicast").toStringList();
|
||||
piForeachC (PIString & g, mcgl) {
|
||||
piForeachC(PIString & g, mcgl) {
|
||||
joinMulticastGroup(g);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
PIEthernet::InterfaceList PIEthernet::interfaces() {
|
||||
//piCout << "PIEthernet::interfaces()";
|
||||
// piCout << "PIEthernet::interfaces()";
|
||||
PIEthernet::InterfaceList il;
|
||||
Interface ci;
|
||||
ci.index = -1;
|
||||
@@ -1159,7 +1175,7 @@ PIEthernet::InterfaceList PIEthernet::interfaces() {
|
||||
ci.ptp.clear();
|
||||
IP_ADDR_STRING * as = &(pAdapter->IpAddressList);
|
||||
while (as) {
|
||||
// piCout << "[pAdapter]" << ci.name << PIString(as->IpAddress.String);
|
||||
// piCout << "[pAdapter]" << ci.name << PIString(as->IpAddress.String);
|
||||
ci.address = PIStringAscii(as->IpAddress.String);
|
||||
ci.netmask = PIStringAscii(as->IpMask.String);
|
||||
if (ci.address == "0.0.0.0") {
|
||||
@@ -1174,18 +1190,14 @@ PIEthernet::InterfaceList PIEthernet::interfaces() {
|
||||
} else {
|
||||
switch (ret) {
|
||||
case ERROR_NO_DATA: break;
|
||||
case ERROR_NOT_SUPPORTED:
|
||||
piCout << "[PIEthernet] GetAdaptersInfo not supported";
|
||||
break;
|
||||
default:
|
||||
piCout << "[PIEthernet] GetAdaptersInfo failed with error:" << ret;
|
||||
case ERROR_NOT_SUPPORTED: piCout << "[PIEthernet] GetAdaptersInfo not supported"; break;
|
||||
default: piCout << "[PIEthernet] GetAdaptersInfo failed with error:" << ret;
|
||||
}
|
||||
}
|
||||
if (pAdapterInfo)
|
||||
HeapFree(GetProcessHeap(), 0, pAdapterInfo);
|
||||
#else
|
||||
#ifdef MICRO_PIP
|
||||
if (pAdapterInfo) HeapFree(GetProcessHeap(), 0, pAdapterInfo);
|
||||
#else
|
||||
# ifdef MICRO_PIP
|
||||
# else
|
||||
# ifdef ANDROID
|
||||
struct ifconf ifc;
|
||||
int s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
|
||||
@@ -1205,19 +1217,16 @@ PIEthernet::InterfaceList PIEthernet::interfaces() {
|
||||
if (in.isEmpty()) continue;
|
||||
ci.name = in;
|
||||
strcpy(ir.ifr_name, in.dataAscii());
|
||||
if (ioctl(s, SIOCGIFHWADDR, &ir) == 0)
|
||||
ci.mac = macFromBytes(PIByteArray(ir.ifr_hwaddr.sa_data, 6));
|
||||
if (ioctl(s, SIOCGIFADDR, &ir) >= 0)
|
||||
ci.address = getSockAddr(&ir.ifr_addr);
|
||||
if (ioctl(s, SIOCGIFNETMASK, &ir) >= 0)
|
||||
ci.netmask = getSockAddr(&ir.ifr_addr);
|
||||
if (ioctl(s, SIOCGIFHWADDR, &ir) == 0) ci.mac = macFromBytes(PIByteArray(ir.ifr_hwaddr.sa_data, 6));
|
||||
if (ioctl(s, SIOCGIFADDR, &ir) >= 0) ci.address = getSockAddr(&ir.ifr_addr);
|
||||
if (ioctl(s, SIOCGIFNETMASK, &ir) >= 0) ci.netmask = getSockAddr(&ir.ifr_addr);
|
||||
ioctl(s, SIOCGIFMTU, &ci.mtu);
|
||||
if (ci.address == "127.0.0.1") ci.flags |= PIEthernet::ifLoopback;
|
||||
il << ci;
|
||||
}
|
||||
delete ifc.ifc_buf;
|
||||
# else
|
||||
struct ifaddrs * ret, * cif = 0;
|
||||
struct ifaddrs *ret, *cif = 0;
|
||||
int s = ::socket(AF_INET, SOCK_STREAM, IPPROTO_IP);
|
||||
if (getifaddrs(&ret) == 0) {
|
||||
cif = ret;
|
||||
@@ -1276,10 +1285,8 @@ PIEthernet::InterfaceList PIEthernet::interfaces() {
|
||||
if (cif->ifa_flags & IFF_POINTOPOINT) ci.flags |= PIEthernet::ifPTP;
|
||||
ci.broadcast.clear();
|
||||
ci.ptp.clear();
|
||||
if (ci.flags[PIEthernet::ifBroadcast])
|
||||
ci.broadcast = getSockAddr(cif->ifa_broadaddr);
|
||||
if (ci.flags[PIEthernet::ifPTP])
|
||||
ci.ptp = getSockAddr(cif->ifa_dstaddr);
|
||||
if (ci.flags[PIEthernet::ifBroadcast]) ci.broadcast = getSockAddr(cif->ifa_broadaddr);
|
||||
if (ci.flags[PIEthernet::ifPTP]) ci.ptp = getSockAddr(cif->ifa_dstaddr);
|
||||
ci.index = if_nametoindex(cif->ifa_name);
|
||||
il << ci;
|
||||
cif = cif->ifa_next;
|
||||
@@ -1306,10 +1313,9 @@ PIEthernet::Address PIEthernet::interfaceAddress(const PIString & interface_) {
|
||||
int s = ::socket(AF_INET, SOCK_DGRAM, 0);
|
||||
ioctl(s, SIOCGIFADDR, &ifr);
|
||||
::close(s);
|
||||
struct sockaddr_in * sa = (struct sockaddr_in * )&ifr.ifr_addr;
|
||||
struct sockaddr_in * sa = (struct sockaddr_in *)&ifr.ifr_addr;
|
||||
return Address(uint(sa->sin_addr.s_addr));
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
|
||||
@@ -1317,13 +1323,13 @@ PIVector<PIEthernet::Address> PIEthernet::allAddresses() {
|
||||
PIEthernet::InterfaceList il = interfaces();
|
||||
PIVector<Address> ret;
|
||||
bool has_127 = false;
|
||||
piForeachC (PIEthernet::Interface & i, il) {
|
||||
piForeachC(PIEthernet::Interface & i, il) {
|
||||
if (i.address == "127.0.0.1") has_127 = true;
|
||||
Address a(i.address);
|
||||
if (a.ip() == 0) continue;
|
||||
ret << a;
|
||||
}
|
||||
// piCout << "[PIEthernet::allAddresses]" << al;
|
||||
// piCout << "[PIEthernet::allAddresses]" << al;
|
||||
if (!has_127) ret << Address("127.0.0.1");
|
||||
return ret;
|
||||
}
|
||||
@@ -1344,7 +1350,13 @@ PIString PIEthernet::ethErrorString() {
|
||||
#ifdef WINDOWS
|
||||
char * msg = nullptr;
|
||||
int err = WSAGetLastError();
|
||||
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&msg, 0, NULL);
|
||||
FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS,
|
||||
NULL,
|
||||
err,
|
||||
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
|
||||
(LPSTR)&msg,
|
||||
0,
|
||||
NULL);
|
||||
PIString ret = PIStringAscii("code ") + PIString::fromNumber(err) + PIStringAscii(" - ");
|
||||
if (msg) {
|
||||
ret += PIString::fromSystem(msg).trim();
|
||||
@@ -1362,9 +1374,11 @@ int PIEthernet::ethRecv(int sock, void * buf, int size, int flags) {
|
||||
if (sock < 0) return -1;
|
||||
return recv(sock,
|
||||
#ifdef WINDOWS
|
||||
(char*)
|
||||
(char *)
|
||||
#endif
|
||||
buf, size, flags);
|
||||
buf,
|
||||
size,
|
||||
flags);
|
||||
}
|
||||
|
||||
|
||||
@@ -1376,9 +1390,13 @@ int PIEthernet::ethRecvfrom(int sock, void * buf, int size, int flags, sockaddr
|
||||
socklen_t len = sizeof(sockaddr);
|
||||
return recvfrom(sock,
|
||||
# ifdef WINDOWS
|
||||
(char*)
|
||||
(char *)
|
||||
# endif
|
||||
buf, size, flags, addr, &len);
|
||||
buf,
|
||||
size,
|
||||
flags,
|
||||
addr,
|
||||
&len);
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -1387,16 +1405,21 @@ int PIEthernet::ethSendto(int sock, const void * buf, int size, int flags, socka
|
||||
if (sock < 0) return -1;
|
||||
return sendto(sock,
|
||||
#ifdef WINDOWS
|
||||
(const char*)
|
||||
(const char *)
|
||||
#endif
|
||||
buf, size, flags, addr, addr_len);
|
||||
buf,
|
||||
size,
|
||||
flags,
|
||||
addr,
|
||||
addr_len);
|
||||
}
|
||||
|
||||
|
||||
void PIEthernet::ethClosesocket(int sock, bool shutdown) {
|
||||
//piCout << "close socket" << sock << shutdown;
|
||||
// piCout << "close socket" << sock << shutdown;
|
||||
if (sock < 0) return;
|
||||
if (shutdown) ::shutdown(sock,
|
||||
if (shutdown)
|
||||
::shutdown(sock,
|
||||
#ifdef WINDOWS
|
||||
SD_BOTH);
|
||||
closesocket(sock);
|
||||
@@ -1409,11 +1432,14 @@ void PIEthernet::ethClosesocket(int sock, bool shutdown) {
|
||||
|
||||
int PIEthernet::ethSetsockopt(int sock, int level, int optname, const void * optval, int optlen) {
|
||||
if (sock < 0) return -1;
|
||||
return setsockopt(sock, level, optname,
|
||||
return setsockopt(sock,
|
||||
level,
|
||||
optname,
|
||||
#ifdef WINDOWS
|
||||
(char*)
|
||||
(char *)
|
||||
#endif
|
||||
optval, optlen);
|
||||
optval,
|
||||
optlen);
|
||||
}
|
||||
|
||||
|
||||
@@ -1475,7 +1501,7 @@ bool PIEthernet::ethIsWriteable(int sock) {
|
||||
#else
|
||||
int ret = 0;
|
||||
socklen_t len = sizeof(ret);
|
||||
getsockopt(sock, SOL_SOCKET, SO_ERROR, (char*)&ret, &len);
|
||||
getsockopt(sock, SOL_SOCKET, SO_ERROR, (char *)&ret, &len);
|
||||
return ret == 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -26,8 +26,8 @@
|
||||
#ifndef PIETHERNET_H
|
||||
#define PIETHERNET_H
|
||||
|
||||
#include "pitimer.h"
|
||||
#include "piiodevice.h"
|
||||
#include "pitimer.h"
|
||||
|
||||
#ifdef ANDROID
|
||||
struct
|
||||
@@ -36,19 +36,18 @@ class
|
||||
#endif
|
||||
sockaddr;
|
||||
|
||||
class PIP_EXPORT PIEthernet: public PIIODevice
|
||||
{
|
||||
class PIP_EXPORT PIEthernet: public PIIODevice {
|
||||
PIIODEVICE(PIEthernet, "eth");
|
||||
friend class PIPeer;
|
||||
public:
|
||||
|
||||
public:
|
||||
//! Contructs UDP %PIEthernet with empty read address
|
||||
explicit PIEthernet();
|
||||
|
||||
//! \brief Type of %PIEthernet
|
||||
enum Type {
|
||||
UDP /** UDP - User Datagram Protocol */ ,
|
||||
TCP_Client /** TCP client - allow connection to TCP server */ ,
|
||||
UDP /** UDP - User Datagram Protocol */,
|
||||
TCP_Client /** TCP client - allow connection to TCP server */,
|
||||
TCP_Server /** TCP server - receive connections from TCP clients */
|
||||
};
|
||||
|
||||
@@ -57,7 +56,8 @@ public:
|
||||
ReuseAddress /** Rebind address if there is already binded. Enabled by default */ = 0x1,
|
||||
Broadcast /** Broadcast send. Disabled by default */ = 0x2,
|
||||
SeparateSockets /** If this parameter is set, %PIEthernet will initialize two different sockets,
|
||||
for receive and send, instead of single one. Disabled by default */ = 0x4,
|
||||
for receive and send, instead of single one. Disabled by default */
|
||||
= 0x4,
|
||||
MulticastLoop /** Enable receiving multicast packets from same host. Enabled by default */ = 0x8,
|
||||
KeepConnection /** Automatic reconnect TCP connection on disconnect. Enabled by default */ = 0x10,
|
||||
DisonnectOnTimeout /** Disconnect TCP connection on read timeout expired. Disabled by default */ = 0x20
|
||||
@@ -67,8 +67,8 @@ public:
|
||||
//! \brief IPv4 network address, IP and port
|
||||
class PIP_EXPORT Address {
|
||||
friend class PIEthernet;
|
||||
public:
|
||||
|
||||
public:
|
||||
//! Contructs %Address with binary representation of IP and port
|
||||
Address(uint ip = 0, ushort port = 0);
|
||||
|
||||
@@ -79,10 +79,10 @@ public:
|
||||
Address(const PIString & ip, ushort port);
|
||||
|
||||
//! Returns binary IP
|
||||
uint ip() const {return ip_;}
|
||||
uint ip() const { return ip_; }
|
||||
|
||||
//! Returns port
|
||||
ushort port() const {return port_;}
|
||||
ushort port() const { return port_; }
|
||||
|
||||
//! Returns string IP
|
||||
PIString ipString() const;
|
||||
@@ -121,6 +121,7 @@ public:
|
||||
static Address resolve(const PIString & host, ushort port);
|
||||
|
||||
static void splitIPPort(const PIString & ipp, PIString * ip, int * port);
|
||||
|
||||
private:
|
||||
void initIP(const PIString & _ip);
|
||||
union {
|
||||
@@ -132,112 +133,130 @@ public:
|
||||
|
||||
|
||||
//! Contructs %PIEthernet with type "type", read address "ip_port" and parameters "params"
|
||||
explicit PIEthernet(Type type, const PIString & ip_port = PIString(), const PIFlags<Parameters> params = PIEthernet::ReuseAddress | PIEthernet::MulticastLoop | PIEthernet::KeepConnection);
|
||||
explicit PIEthernet(Type type,
|
||||
const PIString & ip_port = PIString(),
|
||||
const PIFlags<Parameters> params = PIEthernet::ReuseAddress | PIEthernet::MulticastLoop |
|
||||
PIEthernet::KeepConnection);
|
||||
|
||||
virtual ~PIEthernet();
|
||||
|
||||
|
||||
//! Set read address
|
||||
void setReadAddress(const PIString & ip, int port) {addr_r.set(ip, port); setPath(addr_r.toString());}
|
||||
void setReadAddress(const PIString & ip, int port) {
|
||||
addr_r.set(ip, port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read address in format "i.i.i.i:p"
|
||||
void setReadAddress(const PIString & ip_port) {addr_r.set(ip_port); setPath(addr_r.toString());}
|
||||
void setReadAddress(const PIString & ip_port) {
|
||||
addr_r.set(ip_port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read address
|
||||
void setReadAddress(const Address & addr) {addr_r = addr; setPath(addr_r.toString());}
|
||||
void setReadAddress(const Address & addr) {
|
||||
addr_r = addr;
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read IP
|
||||
void setReadIP(const PIString & ip) {addr_r.setIP(ip); setPath(addr_r.toString());}
|
||||
void setReadIP(const PIString & ip) {
|
||||
addr_r.setIP(ip);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read port
|
||||
void setReadPort(int port) {addr_r.setPort(port); setPath(addr_r.toString());}
|
||||
void setReadPort(int port) {
|
||||
addr_r.setPort(port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
|
||||
//! Set send address
|
||||
void setSendAddress(const PIString & ip, int port) {addr_s.set(ip, port);}
|
||||
void setSendAddress(const PIString & ip, int port) { addr_s.set(ip, port); }
|
||||
|
||||
//! Set send address in format "i.i.i.i:p"
|
||||
void setSendAddress(const PIString & ip_port) {addr_s.set(ip_port);}
|
||||
void setSendAddress(const PIString & ip_port) { addr_s.set(ip_port); }
|
||||
|
||||
//! Set send address
|
||||
void setSendAddress(const Address & addr) {addr_s = addr;}
|
||||
void setSendAddress(const Address & addr) { addr_s = addr; }
|
||||
|
||||
//! Set send IP
|
||||
void setSendIP(const PIString & ip) {addr_s.setIP(ip);}
|
||||
void setSendIP(const PIString & ip) { addr_s.setIP(ip); }
|
||||
|
||||
//! Set send port
|
||||
void setSendPort(int port) {addr_s.setPort(port);}
|
||||
void setSendPort(int port) { addr_s.setPort(port); }
|
||||
|
||||
|
||||
//! Returns read address in format "i.i.i.i:p"
|
||||
Address readAddress() const {return addr_r;}
|
||||
Address readAddress() const { return addr_r; }
|
||||
|
||||
//! Returns read IP
|
||||
PIString readIP() const {return addr_r.ipString();}
|
||||
PIString readIP() const { return addr_r.ipString(); }
|
||||
|
||||
//! Returns read port
|
||||
int readPort() const {return addr_r.port();}
|
||||
int readPort() const { return addr_r.port(); }
|
||||
|
||||
|
||||
//! Returns send address in format "i.i.i.i:p"
|
||||
Address sendAddress() const {return addr_s;}
|
||||
Address sendAddress() const { return addr_s; }
|
||||
|
||||
//! Returns send IP
|
||||
PIString sendIP() const {return addr_s.ipString();}
|
||||
PIString sendIP() const { return addr_s.ipString(); }
|
||||
|
||||
//! Returns send port
|
||||
int sendPort() const {return addr_s.port();}
|
||||
int sendPort() const { return addr_s.port(); }
|
||||
|
||||
|
||||
//! Returns address of last received UDP packet in format "i.i.i.i:p"
|
||||
Address lastReadAddress() const {return addr_lr;}
|
||||
Address lastReadAddress() const { return addr_lr; }
|
||||
|
||||
//! Returns IP of last received UDP packet
|
||||
PIString lastReadIP() const {return addr_lr.ipString();}
|
||||
PIString lastReadIP() const { return addr_lr.ipString(); }
|
||||
|
||||
//! Returns port of last received UDP packet
|
||||
int lastReadPort() const {return addr_lr.port();}
|
||||
int lastReadPort() const { return addr_lr.port(); }
|
||||
|
||||
|
||||
//! Set parameters to "parameters_". You should to reopen %PIEthernet to apply them
|
||||
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) {params = parameters_;}
|
||||
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) { params = parameters_; }
|
||||
|
||||
//! Set parameter "parameter" to state "on". You should to reopen %PIEthernet to apply this
|
||||
void setParameter(PIEthernet::Parameters parameter, bool on = true) {params.setFlag(parameter, on);}
|
||||
void setParameter(PIEthernet::Parameters parameter, bool on = true) { params.setFlag(parameter, on); }
|
||||
|
||||
//! Returns if parameter "parameter" is set
|
||||
bool isParameterSet(PIEthernet::Parameters parameter) const {return params[parameter];}
|
||||
bool isParameterSet(PIEthernet::Parameters parameter) const { return params[parameter]; }
|
||||
|
||||
//! Returns parameters
|
||||
PIFlags<PIEthernet::Parameters> parameters() const {return params;}
|
||||
PIFlags<PIEthernet::Parameters> parameters() const { return params; }
|
||||
|
||||
//! Returns %PIEthernet type
|
||||
Type type() const {return eth_type;}
|
||||
Type type() const { return eth_type; }
|
||||
|
||||
//! Returns read timeout
|
||||
double readTimeout() const {return property("readTimeout").toDouble();}
|
||||
double readTimeout() const { return property("readTimeout").toDouble(); }
|
||||
|
||||
//! Returns write timeout
|
||||
double writeTimeout() const {return property("writeTimeout").toDouble();}
|
||||
double writeTimeout() const { return property("writeTimeout").toDouble(); }
|
||||
|
||||
//! Set timeout for read
|
||||
void setReadTimeout(double ms) {setProperty("readTimeout", ms);}
|
||||
void setReadTimeout(double ms) { setProperty("readTimeout", ms); }
|
||||
|
||||
//! Set timeout for write
|
||||
void setWriteTimeout(double ms) {setProperty("writeTimeout", ms);}
|
||||
void setWriteTimeout(double ms) { setProperty("writeTimeout", ms); }
|
||||
|
||||
|
||||
//! Returns TTL (Time To Live)
|
||||
int TTL() const {return property("TTL").toInt();}
|
||||
int TTL() const { return property("TTL").toInt(); }
|
||||
|
||||
//! Returns multicast TTL (Time To Live)
|
||||
int multicastTTL() const {return property("MulticastTTL").toInt();}
|
||||
int multicastTTL() const { return property("MulticastTTL").toInt(); }
|
||||
|
||||
//! Set TTL (Time To Live), default is 64
|
||||
void setTTL(int ttl) {setProperty("TTL", ttl);}
|
||||
void setTTL(int ttl) { setProperty("TTL", ttl); }
|
||||
|
||||
//! Set multicast TTL (Time To Live), default is 1
|
||||
void setMulticastTTL(int ttl) {setProperty("MulticastTTL", ttl);}
|
||||
void setMulticastTTL(int ttl) { setProperty("MulticastTTL", ttl); }
|
||||
|
||||
|
||||
//! Join to multicast group with address "group". Use only for UDP
|
||||
@@ -247,7 +266,7 @@ public:
|
||||
bool leaveMulticastGroup(const PIString & group);
|
||||
|
||||
//! Returns joined multicast groups. Use only for UDP
|
||||
const PIStringList & multicastGroups() const {return mcast_groups;}
|
||||
const PIStringList & multicastGroups() const { return mcast_groups; }
|
||||
|
||||
|
||||
//! If \"threaded\" queue connect to TCP server with address \a readAddress() in
|
||||
@@ -256,46 +275,59 @@ public:
|
||||
bool connect(bool threaded = true);
|
||||
|
||||
//! Connect to TCP server with address "ip":"port". Use only for TCP_Client
|
||||
bool connect(const PIString & ip, int port, bool threaded = true) {setPath(ip + PIStringAscii(":") + PIString::fromNumber(port)); return connect(threaded);}
|
||||
bool connect(const PIString & ip, int port, bool threaded = true) {
|
||||
setPath(ip + PIStringAscii(":") + PIString::fromNumber(port));
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Connect to TCP server with address "ip_port". Use only for TCP_Client
|
||||
bool connect(const PIString & ip_port, bool threaded = true) {setPath(ip_port); return connect(threaded);}
|
||||
bool connect(const PIString & ip_port, bool threaded = true) {
|
||||
setPath(ip_port);
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Connect to TCP server with address "addr". Use only for TCP_Client
|
||||
bool connect(const Address & addr, bool threaded = true) {setPath(addr.toString()); return connect(threaded);}
|
||||
bool connect(const Address & addr, bool threaded = true) {
|
||||
setPath(addr.toString());
|
||||
return connect(threaded);
|
||||
}
|
||||
|
||||
//! Returns if %PIEthernet connected to TCP server. Use only for TCP_Client
|
||||
bool isConnected() const {return connected_;}
|
||||
bool isConnected() const { return connected_; }
|
||||
|
||||
//! Returns if %PIEthernet is connecting to TCP server. Use only for TCP_Client
|
||||
bool isConnecting() const {return connecting_;}
|
||||
bool isConnecting() const { return connecting_; }
|
||||
|
||||
|
||||
//! Start listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
|
||||
bool listen(bool threaded = false);
|
||||
|
||||
//! Start listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
|
||||
bool listen(const PIString & ip, int port, bool threaded = false) {return listen(PIEthernet::Address(ip, port), threaded);}
|
||||
bool listen(const PIString & ip, int port, bool threaded = false) { return listen(PIEthernet::Address(ip, port), threaded); }
|
||||
|
||||
//! Start listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
|
||||
bool listen(const PIString & ip_port, bool threaded = false) {return listen(PIEthernet::Address(ip_port), threaded);}
|
||||
bool listen(const PIString & ip_port, bool threaded = false) { return listen(PIEthernet::Address(ip_port), threaded); }
|
||||
|
||||
//! Start listen for incoming TCP connections on address "addr". Use only for TCP_Server
|
||||
bool listen(const Address & addr, bool threaded = false);
|
||||
|
||||
PIEthernet * client(int index) {return clients_[index];}
|
||||
int clientsCount() const {return clients_.size_s();}
|
||||
PIVector<PIEthernet * > clients() const {return clients_;}
|
||||
PIEthernet * client(int index) { return clients_[index]; }
|
||||
int clientsCount() const { return clients_.size_s(); }
|
||||
PIVector<PIEthernet *> clients() const { return clients_; }
|
||||
|
||||
|
||||
//! Send data "data" with size "size" to address \a sendAddress() for UDP or \a readAddress() for TCP_Client
|
||||
bool send(const void * data, int size, bool threaded = false);
|
||||
|
||||
//! Send data "data" with size "size" to address "ip":"port"
|
||||
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {return send(PIEthernet::Address(ip, port), data, size, threaded);}
|
||||
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {
|
||||
return send(PIEthernet::Address(ip, port), data, size, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" with size "size" to address "ip_port"
|
||||
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {return send(PIEthernet::Address(ip_port), data, size, threaded);}
|
||||
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {
|
||||
return send(PIEthernet::Address(ip_port), data, size, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" with size "size" to address "addr"
|
||||
bool send(const Address & addr, const void * data, int size, bool threaded = false);
|
||||
@@ -304,21 +336,25 @@ public:
|
||||
bool send(const PIByteArray & data, bool threaded = false);
|
||||
|
||||
//! Send data "data" to address "ip":"port" for UDP
|
||||
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {return send(PIEthernet::Address(ip, port), data, threaded);}
|
||||
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PIEthernet::Address(ip, port), data, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" to address "ip_port" for UDP
|
||||
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {return send(PIEthernet::Address(ip_port), data, threaded);}
|
||||
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PIEthernet::Address(ip_port), data, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" to address "addr" for UDP
|
||||
bool send(const Address & addr, const PIByteArray & data, bool threaded = false);
|
||||
|
||||
bool canWrite() const override {return mode() & WriteOnly;}
|
||||
bool canWrite() const override { return mode() & WriteOnly; }
|
||||
|
||||
void interrupt() override;
|
||||
|
||||
int socket() const {return sock;}
|
||||
int socket() const { return sock; }
|
||||
|
||||
EVENT1(newConnection, PIEthernet * , client);
|
||||
EVENT1(newConnection, PIEthernet *, client);
|
||||
EVENT0(connected);
|
||||
EVENT1(disconnected, bool, withError);
|
||||
|
||||
@@ -339,7 +375,6 @@ public:
|
||||
|
||||
//! Network interface descriptor
|
||||
struct PIP_EXPORT Interface {
|
||||
|
||||
//! System index
|
||||
int index;
|
||||
|
||||
@@ -368,22 +403,22 @@ public:
|
||||
InterfaceFlags flags;
|
||||
|
||||
//! Returns if interface is active
|
||||
bool isActive() const {return flags[PIEthernet::ifActive];}
|
||||
bool isActive() const { return flags[PIEthernet::ifActive]; }
|
||||
|
||||
//! Returns if interface is running
|
||||
bool isRunning() const {return flags[PIEthernet::ifRunning];}
|
||||
bool isRunning() const { return flags[PIEthernet::ifRunning]; }
|
||||
|
||||
//! Returns if interface support broadcast
|
||||
bool isBroadcast() const {return flags[PIEthernet::ifBroadcast];}
|
||||
bool isBroadcast() const { return flags[PIEthernet::ifBroadcast]; }
|
||||
|
||||
//! Returns if interface support multicast
|
||||
bool isMulticast() const {return flags[PIEthernet::ifMulticast];}
|
||||
bool isMulticast() const { return flags[PIEthernet::ifMulticast]; }
|
||||
|
||||
//! Returns if interface is loopback
|
||||
bool isLoopback() const {return flags[PIEthernet::ifLoopback];}
|
||||
bool isLoopback() const { return flags[PIEthernet::ifLoopback]; }
|
||||
|
||||
//! Returns if interface is point-to-point
|
||||
bool isPTP() const {return flags[PIEthernet::ifPTP];}
|
||||
bool isPTP() const { return flags[PIEthernet::ifPTP]; }
|
||||
};
|
||||
|
||||
|
||||
@@ -393,16 +428,32 @@ public:
|
||||
InterfaceList(): PIVector<PIEthernet::Interface>() {}
|
||||
|
||||
//! Get interface with system index "index" or 0 if there is no one
|
||||
const Interface * getByIndex(int index) const {for (int i = 0; i < size_s(); ++i) if ((*this)[i].index == index) return &((*this)[i]); return 0;}
|
||||
const Interface * getByIndex(int index) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].index == index) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get interface with system name "name" or 0 if there is no one
|
||||
const Interface * getByName(const PIString & name) const {for (int i = 0; i < size_s(); ++i) if ((*this)[i].name == name) return &((*this)[i]); return 0;}
|
||||
const Interface * getByName(const PIString & name) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].name == name) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get interface with IP address "address" or 0 if there is no one
|
||||
const Interface * getByAddress(const PIString & address) const {for (int i = 0; i < size_s(); ++i) if ((*this)[i].address == address) return &((*this)[i]); return 0;}
|
||||
const Interface * getByAddress(const PIString & address) const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].address == address) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
|
||||
//! Get loopback interface or 0 if there is no one
|
||||
const Interface * getLoopback() const {for (int i = 0; i < size_s(); ++i) if ((*this)[i].isLoopback()) return &((*this)[i]); return 0;}
|
||||
const Interface * getLoopback() const {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if ((*this)[i].isLoopback()) return &((*this)[i]);
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -421,8 +472,8 @@ public:
|
||||
static PIString getBroadcast(const PIString & ip, const PIString & mask);
|
||||
static Address getBroadcast(const Address & ip, const Address & mask);
|
||||
|
||||
//! \events
|
||||
//! \{
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void newConnection(PIEthernet * client)
|
||||
//! \brief Raise on new TCP connection received
|
||||
@@ -458,7 +509,7 @@ public:
|
||||
//! \brief time-to-live for multicast, default 1
|
||||
int multicastTTL;
|
||||
#endif
|
||||
//! \}
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
explicit PIEthernet(int sock, PIString ip_port);
|
||||
@@ -475,7 +526,7 @@ protected:
|
||||
DeviceInfoFlags deviceInfoFlags() const override;
|
||||
|
||||
//! Executes when any read function was successful. Default implementation does nothing
|
||||
virtual void received(const void * data, int size) {;}
|
||||
virtual void received(const void * data, int size) { ; }
|
||||
|
||||
void construct();
|
||||
bool init();
|
||||
@@ -493,7 +544,7 @@ protected:
|
||||
Type eth_type;
|
||||
PIThread server_thread_;
|
||||
PIMutex clients_mutex;
|
||||
PIVector<PIEthernet * > clients_;
|
||||
PIVector<PIEthernet *> clients_;
|
||||
PIQueue<PIString> mcast_queue;
|
||||
PIStringList mcast_groups;
|
||||
PIFlags<PIEthernet::Parameters> params;
|
||||
@@ -518,15 +569,30 @@ private:
|
||||
static int ethSetsockoptBool(int sock, int level, int optname, bool value = true);
|
||||
static void ethNonblocking(int sock);
|
||||
static bool ethIsWriteable(int sock);
|
||||
|
||||
};
|
||||
|
||||
inline bool operator <(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {return (v0.name < v1.name);}
|
||||
inline bool operator ==(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {return (v0.name == v1.name && v0.address == v1.address && v0.netmask == v1.netmask);}
|
||||
inline bool operator !=(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {return (v0.name != v1.name || v0.address != v1.address || v0.netmask != v1.netmask);}
|
||||
inline PICout operator <<(PICout s, const PIEthernet::Address & v) {s.space(); s.saveAndSetControls(0); s << "Address(" << v.toString() << ")"; s.restoreControls(); return s;}
|
||||
inline bool operator<(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {
|
||||
return (v0.name < v1.name);
|
||||
}
|
||||
inline bool operator==(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {
|
||||
return (v0.name == v1.name && v0.address == v1.address && v0.netmask == v1.netmask);
|
||||
}
|
||||
inline bool operator!=(const PIEthernet::Interface & v0, const PIEthernet::Interface & v1) {
|
||||
return (v0.name != v1.name || v0.address != v1.address || v0.netmask != v1.netmask);
|
||||
}
|
||||
inline PICout operator<<(PICout s, const PIEthernet::Address & v) {
|
||||
s.space();
|
||||
s.saveAndSetControls(0);
|
||||
s << "Address(" << v.toString() << ")";
|
||||
s.restoreControls();
|
||||
return s;
|
||||
}
|
||||
|
||||
inline bool operator ==(const PIEthernet::Address & v0, const PIEthernet::Address & v1) {return (v0.ip() == v1.ip() && v0.port() == v1.port());}
|
||||
inline bool operator !=(const PIEthernet::Address & v0, const PIEthernet::Address & v1) {return (v0.ip() != v1.ip() || v0.port() != v1.port());}
|
||||
inline bool operator==(const PIEthernet::Address & v0, const PIEthernet::Address & v1) {
|
||||
return (v0.ip() == v1.ip() && v0.port() == v1.port());
|
||||
}
|
||||
inline bool operator!=(const PIEthernet::Address & v0, const PIEthernet::Address & v1) {
|
||||
return (v0.ip() != v1.ip() || v0.port() != v1.port());
|
||||
}
|
||||
|
||||
#endif // PIETHERNET_H
|
||||
|
||||
@@ -17,9 +17,10 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "piincludes_p.h"
|
||||
#include "pifile.h"
|
||||
|
||||
#include "pidir.h"
|
||||
#include "piincludes_p.h"
|
||||
#include "piiostream.h"
|
||||
#include "pitime_win.h"
|
||||
#ifdef WINDOWS
|
||||
@@ -36,9 +37,9 @@
|
||||
# define S_IFCHR 0x10
|
||||
# define S_IFSOCK 0x20
|
||||
#else
|
||||
# include <fcntl.h>
|
||||
# include <sys/stat.h>
|
||||
# include <sys/time.h>
|
||||
# include <fcntl.h>
|
||||
# include <utime.h>
|
||||
#endif
|
||||
#define S_IFHDN 0x40
|
||||
@@ -152,10 +153,7 @@ PIString PIFile::FileInfo::dir() const {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
PIFile::PIFile(): PIIODevice() {
|
||||
}
|
||||
PIFile::PIFile(): PIIODevice() {}
|
||||
|
||||
|
||||
PIFile::PIFile(const PIString & path, PIIODevice::DeviceMode mode): PIIODevice(path, mode) {
|
||||
@@ -196,7 +194,7 @@ bool PIFile::openDevice() {
|
||||
}
|
||||
}
|
||||
PRIVATE->fd = _fopen_call_(p.data(), strType(mode_).data());
|
||||
//piCout << "fopen " << path() << ": " << strType(mode_).data() << PRIVATE->fd;
|
||||
// piCout << "fopen " << path() << ": " << strType(mode_).data() << PRIVATE->fd;
|
||||
bool opened = (PRIVATE->fd != 0);
|
||||
if (opened) {
|
||||
fdi = fileno(PRIVATE->fd);
|
||||
@@ -210,19 +208,19 @@ bool PIFile::openDevice() {
|
||||
_fseek_call_(PRIVATE->fd, 0, SEEK_SET);
|
||||
clearerr(PRIVATE->fd);
|
||||
}
|
||||
//piCout << "open file" << PRIVATE->fd << opened_;
|
||||
// piCout << "open file" << PRIVATE->fd << opened_;
|
||||
return opened;
|
||||
}
|
||||
|
||||
|
||||
bool PIFile::closeDevice() {
|
||||
//piCout << "close file" << PRIVATE->fd << opened_;
|
||||
// piCout << "close file" << PRIVATE->fd << opened_;
|
||||
if (isClosed() || PRIVATE->fd == 0) return true;
|
||||
bool cs = (fclose(PRIVATE->fd) == 0);
|
||||
if (cs) PRIVATE->fd = 0;
|
||||
fdi = -1;
|
||||
_size = -1;
|
||||
//piCout << "closed file" << PRIVATE->fd << opened_;
|
||||
// piCout << "closed file" << PRIVATE->fd << opened_;
|
||||
return cs;
|
||||
}
|
||||
|
||||
@@ -232,9 +230,9 @@ llong PIFile::readAll(void * data) {
|
||||
seekToBegin();
|
||||
if (s < 0) {
|
||||
while (!isEnd())
|
||||
read(&(((char*)data)[++i]), 1);
|
||||
read(&(((char *)data)[++i]), 1);
|
||||
} else
|
||||
read((char * )data, s);
|
||||
read((char *)data, s);
|
||||
seek(cp);
|
||||
return s;
|
||||
}
|
||||
@@ -264,9 +262,11 @@ PIByteArray PIFile::readAll(bool forceRead) {
|
||||
llong PIFile::size() const {
|
||||
if (isClosed()) return -1;
|
||||
llong s, cp = pos();
|
||||
_fseek_call_(PRIVATE->fd, 0, SEEK_END); clearerr(PRIVATE->fd);
|
||||
_fseek_call_(PRIVATE->fd, 0, SEEK_END);
|
||||
clearerr(PRIVATE->fd);
|
||||
s = pos();
|
||||
_fseek_call_(PRIVATE->fd, cp, SEEK_SET); clearerr(PRIVATE->fd);
|
||||
_fseek_call_(PRIVATE->fd, cp, SEEK_SET);
|
||||
clearerr(PRIVATE->fd);
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -289,7 +289,6 @@ void PIFile::resize(llong new_size, uchar fill_) {
|
||||
}
|
||||
|
||||
|
||||
|
||||
bool PIFile::isExists(const PIString & path) {
|
||||
FILE * f = _fopen_call_(PIString(path).data(), "r");
|
||||
bool ok = (f != 0);
|
||||
@@ -378,7 +377,7 @@ void PIFile::seekToLine(llong line) {
|
||||
if (isClosed()) return;
|
||||
seekToBegin();
|
||||
PIIOTextStream ts(this);
|
||||
piForTimes (line) ts.readLine();
|
||||
piForTimes(line) ts.readLine();
|
||||
clearerr(PRIVATE->fd);
|
||||
}
|
||||
|
||||
@@ -410,8 +409,7 @@ bool PIFile::isEnd() const {
|
||||
if (isClosed()) return true;
|
||||
bool ret = (feof(PRIVATE->fd) || ferror(PRIVATE->fd));
|
||||
if (!ret && (_size >= 0)) {
|
||||
if (pos() > _size)
|
||||
ret = true;
|
||||
if (pos() > _size) ret = true;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -466,14 +464,12 @@ void PIFile::remove() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
|
||||
FileInfo ret;
|
||||
if (path.isEmpty()) return ret;
|
||||
ret.path = path.replacedAll("\\", PIDir::separator);
|
||||
PIString n = ret.name();
|
||||
//piCout << "open" << path;
|
||||
// piCout << "open" << path;
|
||||
#ifdef WINDOWS
|
||||
DWORD attr = GetFileAttributesA((LPCSTR)(path.data()));
|
||||
if (attr == 0xFFFFFFFF) return ret;
|
||||
@@ -490,14 +486,16 @@ PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
|
||||
LARGE_INTEGER filesize;
|
||||
filesize.LowPart = filesize.HighPart = 0;
|
||||
if (fi.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ret.flags |= FileInfo::Hidden;
|
||||
if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) ret.flags |= FileInfo::Dir;
|
||||
if (fi.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)
|
||||
ret.flags |= FileInfo::Dir;
|
||||
else {
|
||||
ret.flags |= FileInfo::File;
|
||||
filesize.LowPart = fi.nFileSizeLow;
|
||||
filesize.HighPart = fi.nFileSizeHigh;
|
||||
}
|
||||
PIString ext = ret.extension();
|
||||
ret.perm_user = FileInfo::Permissions(true, (attr & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY, ext == "bat" || ext == "exe");
|
||||
ret.perm_user =
|
||||
FileInfo::Permissions(true, (attr & FILE_ATTRIBUTE_READONLY) != FILE_ATTRIBUTE_READONLY, ext == "bat" || ext == "exe");
|
||||
ret.perm_group = ret.perm_other = ret.perm_user;
|
||||
ret.size = filesize.QuadPart;
|
||||
ret.time_access = FILETIME2PIDateTime(fi.ftLastAccessTime);
|
||||
@@ -512,10 +510,10 @@ PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
|
||||
ret.size = fs.st_size;
|
||||
ret.id_user = fs.st_uid;
|
||||
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_modification = PIDateTime::fromSystemTime(PISystemTime(fs.st_mtime, fs.st_mtime_nsec));
|
||||
#else
|
||||
# else
|
||||
# if defined(QNX) || defined(FREERTOS)
|
||||
ret.time_access = PIDateTime::fromSecondSinceEpoch(fs.st_atime);
|
||||
ret.time_modification = PIDateTime::fromSecondSinceEpoch(fs.st_mtime);
|
||||
@@ -530,8 +528,8 @@ PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
|
||||
ret.time_access = PIDateTime::fromSystemTime(PISystemTime(fs.ATIME.tv_sec, fs.ATIME.tv_nsec));
|
||||
ret.time_modification = PIDateTime::fromSystemTime(PISystemTime(fs.MTIME.tv_sec, fs.MTIME.tv_nsec));
|
||||
# endif
|
||||
#endif
|
||||
#ifndef MICRO_PIP
|
||||
# endif
|
||||
# ifndef MICRO_PIP
|
||||
ret.perm_user = FileInfo::Permissions((mode & S_IRUSR) == S_IRUSR, (mode & S_IWUSR) == S_IWUSR, (mode & S_IXUSR) == S_IXUSR);
|
||||
ret.perm_group = FileInfo::Permissions((mode & S_IRGRP) == S_IRGRP, (mode & S_IWGRP) == S_IWGRP, (mode & S_IXGRP) == S_IXGRP);
|
||||
ret.perm_other = FileInfo::Permissions((mode & S_IROTH) == S_IROTH, (mode & S_IWOTH) == S_IWOTH, (mode & S_IXOTH) == S_IXOTH);
|
||||
@@ -544,7 +542,7 @@ PIFile::FileInfo PIFile::fileInfo(const PIString & path) {
|
||||
if ((mode & S_IFREG) == S_IFREG) ret.flags |= FileInfo::File;
|
||||
if ((mode & S_IFLNK) == S_IFLNK) ret.flags |= FileInfo::SymbolicLink;
|
||||
if ((mode & S_IFHDN) == S_IFHDN) ret.flags |= FileInfo::Hidden;
|
||||
#endif
|
||||
# endif
|
||||
#endif
|
||||
if (n == ".") ret.flags = FileInfo::Dir | FileInfo::Dot;
|
||||
if (n == "..") ret.flags = FileInfo::Dir | FileInfo::DotDot;
|
||||
@@ -567,7 +565,13 @@ bool PIFile::applyFileInfo(const PIString & path, const PIFile::FileInfo & info)
|
||||
}
|
||||
HANDLE hFile = 0;
|
||||
if ((attr & FILE_ATTRIBUTE_DIRECTORY) == FILE_ATTRIBUTE_DIRECTORY) {
|
||||
hFile = CreateFileA(path.data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, 0);
|
||||
hFile = CreateFileA(path.data(),
|
||||
GENERIC_READ | GENERIC_WRITE,
|
||||
FILE_SHARE_READ | FILE_SHARE_WRITE,
|
||||
0,
|
||||
OPEN_EXISTING,
|
||||
FILE_FLAG_BACKUP_SEMANTICS,
|
||||
0);
|
||||
} else {
|
||||
hFile = CreateFileA(path.data(), GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, 0, OPEN_EXISTING, 0, 0);
|
||||
}
|
||||
|
||||
@@ -34,11 +34,10 @@
|
||||
//! \~\brief
|
||||
//! \~english Local file.
|
||||
//! \~russian Локальный файл.
|
||||
class PIP_EXPORT PIFile: public PIIODevice
|
||||
{
|
||||
class PIP_EXPORT PIFile: public PIIODevice {
|
||||
PIIODEVICE(PIFile, "file");
|
||||
public:
|
||||
|
||||
public:
|
||||
//! \~english Constructs file with empty path
|
||||
//! \~russian Создает файл с пустым путём
|
||||
explicit PIFile();
|
||||
@@ -55,10 +54,13 @@ public:
|
||||
//! \~english Local file or directory information.
|
||||
//! \~russian Информация о локальном файле или директории.
|
||||
struct PIP_EXPORT FileInfo {
|
||||
|
||||
//! \~english Constructs %FileInfo with path "path_". No information gathered
|
||||
//! \~russian Создает %FileInfo с путём "path_". Информация не собирается
|
||||
FileInfo(const PIString & path_ = PIString()) {path = path_; size = 0; id_group = id_user = 0;}
|
||||
FileInfo(const PIString & path_ = PIString()) {
|
||||
path = path_;
|
||||
size = 0;
|
||||
id_group = id_user = 0;
|
||||
}
|
||||
|
||||
//! \~english Type flags
|
||||
//! \~russian Флаги типа
|
||||
@@ -78,16 +80,23 @@ public:
|
||||
//! \~russian Разрешения локального файла или директории.
|
||||
struct PIP_EXPORT Permissions {
|
||||
Permissions(uchar r = 0): raw(r) {}
|
||||
Permissions(bool r, bool w, bool e): raw(0) {read = r; write = w; exec = e;}
|
||||
Permissions(bool r, bool w, bool e): raw(0) {
|
||||
read = r;
|
||||
write = w;
|
||||
exec = e;
|
||||
}
|
||||
|
||||
//! \~english Returns as string (from "---" to "rwx")
|
||||
//! \~russian Возвращает как строку (от "---" до "rwx")
|
||||
PIString toString() const {return PIString(read ? "r" : "-") + PIString(write ? "w" : "-") + PIString(exec ? "x" : "-");}
|
||||
PIString toString() const { return PIString(read ? "r" : "-") + PIString(write ? "w" : "-") + PIString(exec ? "x" : "-"); }
|
||||
|
||||
//! \~english Convertion to \c int
|
||||
//! \~russian Преобразование в \c int
|
||||
operator int() const {return raw;}
|
||||
Permissions & operator =(int v) {raw = v; return *this;}
|
||||
operator int() const { return raw; }
|
||||
Permissions & operator=(int v) {
|
||||
raw = v;
|
||||
return *this;
|
||||
}
|
||||
union {
|
||||
uchar raw;
|
||||
struct {
|
||||
@@ -157,20 +166,19 @@ public:
|
||||
|
||||
//! \~english Returns if it`s directory
|
||||
//! \~russian Возвращает директория ли это
|
||||
bool isDir() const {return flags[Dir];}
|
||||
bool isDir() const { return flags[Dir]; }
|
||||
|
||||
//! \~english Returns if it`s file
|
||||
//! \~russian Возвращает файл ли это
|
||||
bool isFile() const {return flags[File];}
|
||||
bool isFile() const { return flags[File]; }
|
||||
|
||||
//! \~english Returns if it`s symbolic link
|
||||
//! \~russian Возвращает символическая ссылка ли это
|
||||
bool isSymbolicLink() const {return flags[SymbolicLink];}
|
||||
bool isSymbolicLink() const { return flags[SymbolicLink]; }
|
||||
|
||||
//! \~english Returns if Hidden flag set
|
||||
//! \~russian Возвращает установлен ли флаг Hidden
|
||||
bool isHidden() const {return flags[Hidden];}
|
||||
|
||||
bool isHidden() const { return flags[Hidden]; }
|
||||
};
|
||||
|
||||
|
||||
@@ -224,7 +232,7 @@ public:
|
||||
//! \~russian Возвращает размер файла в байтах
|
||||
llong size() const;
|
||||
|
||||
ssize_t bytesAvailable() const override {return size() - pos();}
|
||||
ssize_t bytesAvailable() const override { return size() - pos(); }
|
||||
|
||||
//! \~english Returns read/write position
|
||||
//! \~russian Возвращает позицию чтения/записи
|
||||
@@ -236,11 +244,11 @@ public:
|
||||
|
||||
//! \~english Returns if file is empty
|
||||
//! \~russian Возвращает пустой ли файл
|
||||
bool isEmpty() const {return (size() <= 0);}
|
||||
bool isEmpty() const { return (size() <= 0); }
|
||||
|
||||
//! \~english Returns \a PIFile::FileInfo of current file
|
||||
//! \~russian Возвращает \a PIFile::FileInfo текущего файла
|
||||
FileInfo fileInfo() const {return fileInfo(path());}
|
||||
FileInfo fileInfo() const { return fileInfo(path()); }
|
||||
|
||||
|
||||
//! \~english Write size and content of "v" (serialize)
|
||||
@@ -253,7 +261,7 @@ public:
|
||||
|
||||
EVENT_HANDLER(void, clear);
|
||||
EVENT_HANDLER(void, remove);
|
||||
EVENT_HANDLER1(void, resize, llong, new_size) {resize(new_size, 0);}
|
||||
EVENT_HANDLER1(void, resize, llong, new_size) { resize(new_size, 0); }
|
||||
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
||||
|
||||
|
||||
@@ -279,10 +287,10 @@ public:
|
||||
|
||||
//! \~english Apply "info" parameters to file or dir with path "info".path
|
||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "info".path
|
||||
static bool applyFileInfo(const FileInfo & info) {return applyFileInfo(info.path, info);}
|
||||
static bool applyFileInfo(const FileInfo & info) { return applyFileInfo(info.path, info); }
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn void clear()
|
||||
//! \~english Clear content of file
|
||||
@@ -305,7 +313,7 @@ public:
|
||||
//! \{
|
||||
#ifdef DOXYGEN
|
||||
#endif
|
||||
//! \}
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
PIString constructFullPathDevice() const override;
|
||||
@@ -316,7 +324,7 @@ protected:
|
||||
ssize_t writeDevice(const void * data, ssize_t max_size) override;
|
||||
bool openDevice() override;
|
||||
bool closeDevice() override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Sequential | PIIODevice::Reliable;}
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential | PIIODevice::Reliable; }
|
||||
|
||||
private:
|
||||
PIString strType(const PIIODevice::DeviceMode type);
|
||||
@@ -325,19 +333,17 @@ private:
|
||||
int fdi = -1;
|
||||
llong _size = -1;
|
||||
PIString prec_str;
|
||||
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Output operator to \a PICout
|
||||
//! \~russian Оператор вывода в \a PICout
|
||||
inline PICout operator <<(PICout s, const PIFile::FileInfo & v) {
|
||||
inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", "
|
||||
<< v.perm_user.toString() << " " << v.perm_group.toString() << " " << v.perm_other.toString() << ", "
|
||||
<< v.time_access.toString() << ", " << v.time_modification.toString()
|
||||
<< ", 0x" << PICoutManipulators::Hex << v.flags << ")";
|
||||
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " "
|
||||
<< v.perm_group.toString() << " " << v.perm_other.toString() << ", " << v.time_access.toString() << ", "
|
||||
<< v.time_modification.toString() << ", 0x" << PICoutManipulators::Hex << v.flags << ")";
|
||||
s.restoreControls();
|
||||
return s;
|
||||
}
|
||||
@@ -347,8 +353,8 @@ inline PICout operator <<(PICout s, const PIFile::FileInfo & v) {
|
||||
//! \~english Store operator.
|
||||
//! \~russian Оператор сохранения.
|
||||
BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
||||
s << v.path << v.size << v.time_access << v.time_modification <<
|
||||
v.flags << v.id_user << v.id_group << v.perm_user.raw << v.perm_group.raw << v.perm_other.raw;
|
||||
s << v.path << v.size << v.time_access << v.time_modification << v.flags << v.id_user << v.id_group << v.perm_user.raw
|
||||
<< v.perm_group.raw << v.perm_other.raw;
|
||||
return s;
|
||||
}
|
||||
|
||||
@@ -356,8 +362,8 @@ BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
||||
//! \~english Restore operator.
|
||||
//! \~russian Оператор извлечения.
|
||||
BINARY_STREAM_READ(PIFile::FileInfo) {
|
||||
s >> v.path >> v.size >> v.time_access >> v.time_modification >>
|
||||
v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >> v.perm_group.raw >> v.perm_other.raw;
|
||||
s >> v.path >> v.size >> v.time_access >> v.time_modification >> v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >>
|
||||
v.perm_group.raw >> v.perm_other.raw;
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
@@ -22,9 +22,9 @@
|
||||
# define GPIO_SYS_CLASS
|
||||
#endif
|
||||
#ifdef GPIO_SYS_CLASS
|
||||
# include <cstdlib>
|
||||
# include <fcntl.h>
|
||||
# include <unistd.h>
|
||||
# include <cstdlib>
|
||||
#endif
|
||||
|
||||
|
||||
@@ -64,8 +64,7 @@
|
||||
//!
|
||||
|
||||
|
||||
PIGPIO::PIGPIO(): PIThread() {
|
||||
}
|
||||
PIGPIO::PIGPIO(): PIThread() {}
|
||||
|
||||
|
||||
PIGPIO::~PIGPIO() {
|
||||
@@ -74,7 +73,7 @@ PIGPIO::~PIGPIO() {
|
||||
PIMutexLocker ml(mutex);
|
||||
#ifdef GPIO_SYS_CLASS
|
||||
PIVector<int> ids = gpio_.keys();
|
||||
for(int i = 0; i < ids.size_s(); i++) {
|
||||
for (int i = 0; i < ids.size_s(); i++) {
|
||||
GPIOData & g(gpio_[ids[i]]);
|
||||
if (g.fd != -1) {
|
||||
::close(g.fd);
|
||||
@@ -92,7 +91,6 @@ PIGPIO * PIGPIO::instance() {
|
||||
}
|
||||
|
||||
|
||||
|
||||
PIString PIGPIO::GPIOName(int gpio_num) {
|
||||
return PIStringAscii("gpio") + PIString::fromNumber(gpio_num);
|
||||
}
|
||||
@@ -131,7 +129,7 @@ void PIGPIO::openGPIO(GPIOData & g) {
|
||||
}
|
||||
PIString fp = "/sys/class/gpio/" + g.name + "/value";
|
||||
g.fd = ::open(fp.dataAscii(), O_RDWR);
|
||||
//piCoutObj << "initGPIO" << g.num << ":" << fp << g.fd << errorString();
|
||||
// piCoutObj << "initGPIO" << g.num << ":" << fp << g.fd << errorString();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -149,7 +147,7 @@ bool PIGPIO::getPinState(int gpio_num) {
|
||||
if (r == '0') return false;
|
||||
}
|
||||
}
|
||||
//piCoutObj << "pinState" << gpio_num << ":" << ret << (int)r << errorString();
|
||||
// piCoutObj << "pinState" << gpio_num << ":" << ret << (int)r << errorString();
|
||||
#endif
|
||||
return false;
|
||||
}
|
||||
@@ -159,7 +157,7 @@ void PIGPIO::begin() {
|
||||
PIMutexLocker ml(mutex);
|
||||
if (watch_state.isEmpty()) return;
|
||||
PIVector<int> ids = watch_state.keys();
|
||||
for(int i = 0; i < ids.size_s(); i++) {
|
||||
for (int i = 0; i < ids.size_s(); i++) {
|
||||
GPIOData & g(gpio_[ids[i]]);
|
||||
if (g.num != -1 && !g.name.isEmpty()) {
|
||||
openGPIO(g);
|
||||
@@ -181,7 +179,7 @@ void PIGPIO::run() {
|
||||
GPIOData & g(gpio_[it.key()]);
|
||||
if (g.num == -1 || g.name.isEmpty()) continue;
|
||||
bool v = getPinState(g.num);
|
||||
//piCoutObj << "*** pin state ***" << ids[i] << "=" << v;
|
||||
// piCoutObj << "*** pin state ***" << ids[i] << "=" << v;
|
||||
if (watch_state[g.num] != v) {
|
||||
watch_state[g.num] = v;
|
||||
changed.push_back({g.num, v});
|
||||
@@ -197,7 +195,7 @@ void PIGPIO::end() {
|
||||
PIMutexLocker ml(mutex);
|
||||
if (watch_state.isEmpty()) return;
|
||||
PIVector<int> ids = watch_state.keys();
|
||||
for(int i = 0; i < ids.size_s(); i++) {
|
||||
for (int i = 0; i < ids.size_s(); i++) {
|
||||
GPIOData & g(gpio_[ids[i]]);
|
||||
if (g.fd != -1) {
|
||||
#ifdef GPIO_SYS_CLASS
|
||||
@@ -221,13 +219,9 @@ void PIGPIO::initPin(int gpio_num, Direction dir) {
|
||||
g.dir = dir;
|
||||
int ret = 0;
|
||||
NO_UNUSED(ret);
|
||||
switch(dir) {
|
||||
case In:
|
||||
ret = system(("echo in >> /sys/class/gpio/" + g.name + "/direction").dataAscii());
|
||||
break;
|
||||
case Out:
|
||||
ret = system(("echo out >> /sys/class/gpio/" + g.name + "/direction").dataAscii());
|
||||
break;
|
||||
switch (dir) {
|
||||
case In: ret = system(("echo in >> /sys/class/gpio/" + g.name + "/direction").dataAscii()); break;
|
||||
case Out: ret = system(("echo out >> /sys/class/gpio/" + g.name + "/direction").dataAscii()); break;
|
||||
default: break;
|
||||
}
|
||||
openGPIO(g);
|
||||
@@ -242,10 +236,12 @@ void PIGPIO::pinSet(int gpio_num, bool value) {
|
||||
int ret = 0;
|
||||
NO_UNUSED(ret);
|
||||
if (g.fd != -1) {
|
||||
if (value) ret = ::write(g.fd, "1", 1);
|
||||
else ret = ::write(g.fd, "0", 1);
|
||||
if (value)
|
||||
ret = ::write(g.fd, "1", 1);
|
||||
else
|
||||
ret = ::write(g.fd, "0", 1);
|
||||
}
|
||||
//piCoutObj << "pinSet" << gpio_num << ":" << ret << errorString();
|
||||
// piCoutObj << "pinSet" << gpio_num << ":" << ret << errorString();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -306,5 +302,5 @@ void PIGPIO::clearWatch() {
|
||||
|
||||
|
||||
#ifdef __GNUC__
|
||||
//# pragma GCC diagnostic pop
|
||||
// # pragma GCC diagnostic pop
|
||||
#endif
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
* \~\brief
|
||||
* \~english GPIO
|
||||
* \~russian GPIO
|
||||
*/
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
GPIO
|
||||
@@ -33,11 +33,10 @@
|
||||
//! \~\brief
|
||||
//! \~english GPIO support.
|
||||
//! \~russian Поддержка GPIO.
|
||||
class PIP_EXPORT PIGPIO: public PIThread
|
||||
{
|
||||
class PIP_EXPORT PIGPIO: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PIGPIO, PIThread);
|
||||
public:
|
||||
|
||||
public:
|
||||
//! \~english Work mode for pin
|
||||
//! \~russian Режим работы пина
|
||||
enum Direction {
|
||||
@@ -55,15 +54,15 @@ public:
|
||||
|
||||
//! \~english Set pin "gpio_num" value to "value"
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в "value"
|
||||
void pinSet (int gpio_num, bool value);
|
||||
void pinSet(int gpio_num, bool value);
|
||||
|
||||
//! \~english Set pin "gpio_num" value to \b true
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b true
|
||||
void pinHigh (int gpio_num) {pinSet(gpio_num, true );}
|
||||
void pinHigh(int gpio_num) { pinSet(gpio_num, true); }
|
||||
|
||||
//! \~english Set pin "gpio_num" value to \b false
|
||||
//! \~russian Устанавливает значение пина "gpio_num" в \b false
|
||||
void pinLow (int gpio_num) {pinSet(gpio_num, false);}
|
||||
void pinLow(int gpio_num) { pinSet(gpio_num, false); }
|
||||
|
||||
//!
|
||||
//! \~english Returns pin "gpio_num" state
|
||||
@@ -76,7 +75,7 @@ public:
|
||||
|
||||
//! \~english End watch for pin "gpio_num"
|
||||
//! \~russian Заканчивает наблюдение за пином "gpio_num"
|
||||
void pinEndWatch (int gpio_num);
|
||||
void pinEndWatch(int gpio_num);
|
||||
|
||||
//! \~english End watch for all pins
|
||||
//! \~russian Заканчивает наблюдение за всеми пинами
|
||||
@@ -103,7 +102,10 @@ private:
|
||||
NO_COPY_CLASS(PIGPIO);
|
||||
|
||||
struct PIP_EXPORT GPIOData {
|
||||
GPIOData() {dir = PIGPIO::In; num = fd = -1;}
|
||||
GPIOData() {
|
||||
dir = PIGPIO::In;
|
||||
num = fd = -1;
|
||||
}
|
||||
PIString name;
|
||||
int dir;
|
||||
int num;
|
||||
@@ -121,7 +123,6 @@ private:
|
||||
PIMap<int, GPIOData> gpio_;
|
||||
PIMap<int, bool> watch_state;
|
||||
PIMutex mutex;
|
||||
|
||||
};
|
||||
|
||||
|
||||
|
||||
@@ -31,37 +31,37 @@
|
||||
//!
|
||||
|
||||
|
||||
PIIOByteArray::PIIOByteArray(PIByteArray *buffer, PIIODevice::DeviceMode mode) {
|
||||
PIIOByteArray::PIIOByteArray(PIByteArray * buffer, PIIODevice::DeviceMode mode) {
|
||||
open(buffer, mode);
|
||||
}
|
||||
|
||||
|
||||
PIIOByteArray::PIIOByteArray(const PIByteArray &buffer) {
|
||||
PIIOByteArray::PIIOByteArray(const PIByteArray & buffer) {
|
||||
open(buffer);
|
||||
}
|
||||
|
||||
|
||||
bool PIIOByteArray::open(PIByteArray *buffer, PIIODevice::DeviceMode mode) {
|
||||
bool PIIOByteArray::open(PIByteArray * buffer, PIIODevice::DeviceMode mode) {
|
||||
data_ = buffer;
|
||||
mode_ = mode;
|
||||
return PIIODevice::open(mode);
|
||||
}
|
||||
|
||||
|
||||
bool PIIOByteArray::open(const PIByteArray &buffer) {
|
||||
data_ = const_cast<PIByteArray*>(&buffer);
|
||||
bool PIIOByteArray::open(const PIByteArray & buffer) {
|
||||
data_ = const_cast<PIByteArray *>(&buffer);
|
||||
mode_ = PIIODevice::ReadOnly;
|
||||
return PIIODevice::open(PIIODevice::ReadOnly);
|
||||
}
|
||||
|
||||
|
||||
ssize_t PIIOByteArray::readDevice(void * read_to, ssize_t size) {
|
||||
// piCout << "PIIOByteArray::read" << data_ << size << canRead();
|
||||
// piCout << "PIIOByteArray::read" << data_ << size << canRead();
|
||||
if (!canRead() || !data_) return -1;
|
||||
int ret = piMini(size, data_->size_s() - pos);
|
||||
if (ret <= 0) return -1;
|
||||
memcpy(read_to, data_->data(pos), ret);
|
||||
// piCout << "readed" << ret;
|
||||
// piCout << "readed" << ret;
|
||||
pos += size;
|
||||
if (pos > data_->size_s()) pos = data_->size_s();
|
||||
return ret;
|
||||
@@ -69,19 +69,19 @@ ssize_t PIIOByteArray::readDevice(void * read_to, ssize_t size) {
|
||||
|
||||
|
||||
ssize_t PIIOByteArray::writeDevice(const void * data, ssize_t size) {
|
||||
// piCout << "PIIOByteArray::write" << data << size << canWrite();
|
||||
// piCout << "PIIOByteArray::write" << data << size << canWrite();
|
||||
if (!canWrite() || !data) return -1;
|
||||
//piCout << "write" << data;
|
||||
// piCout << "write" << data;
|
||||
if (pos > data_->size_s()) pos = data_->size_s();
|
||||
PIByteArray rs = PIByteArray(data, size);
|
||||
// piCoutObj << rs;
|
||||
// piCoutObj << rs;
|
||||
data_->insert(pos, rs);
|
||||
pos += rs.size_s();
|
||||
return rs.size_s();
|
||||
}
|
||||
|
||||
|
||||
int PIIOByteArray::writeByteArray(const PIByteArray &ba) {
|
||||
int PIIOByteArray::writeByteArray(const PIByteArray & ba) {
|
||||
if (!canWrite() || !data_) return -1;
|
||||
if (pos > data_->size_s()) pos = data_->size_s();
|
||||
data_->insert(pos, ba);
|
||||
|
||||
@@ -33,11 +33,10 @@
|
||||
//! \~\brief
|
||||
//! \~english PIIODevice wrapper around PIByteArray
|
||||
//! \~russian Обёртка PIIODevice вокруг PIByteArray
|
||||
class PIP_EXPORT PIIOByteArray: public PIIODevice
|
||||
{
|
||||
class PIP_EXPORT PIIOByteArray: public PIIODevice {
|
||||
PIIODEVICE(PIIOByteArray, "");
|
||||
public:
|
||||
|
||||
public:
|
||||
//! \~english Contructs %PIIOByteArray with "buffer" content and "mode" open mode
|
||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode"
|
||||
explicit PIIOByteArray(PIByteArray * buffer = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
@@ -48,11 +47,14 @@ public:
|
||||
|
||||
//! \~english Returns content
|
||||
//! \~russian Возвращает содержимое
|
||||
PIByteArray * byteArray() const {return data_;}
|
||||
PIByteArray * byteArray() const { return data_; }
|
||||
|
||||
//! \~english Clear content buffer
|
||||
//! \~russian Очищает содержимое буфера
|
||||
void clear() {if (data_) data_->clear(); pos = 0;}
|
||||
void clear() {
|
||||
if (data_) data_->clear();
|
||||
pos = 0;
|
||||
}
|
||||
|
||||
//! \~english Open "buffer" content with "mode" open mode
|
||||
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode"
|
||||
@@ -64,20 +66,27 @@ public:
|
||||
|
||||
//! \~english Returns if position is at the end of content
|
||||
//! \~russian Возвращает в конце содержимого ли позиция
|
||||
bool isEnd() const {if (!data_) return true; return pos >= data_->size_s();}
|
||||
bool isEnd() const {
|
||||
if (!data_) return true;
|
||||
return pos >= data_->size_s();
|
||||
}
|
||||
|
||||
|
||||
//! \~english Move read/write position to "position"
|
||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
||||
void seek(llong position) {pos = position;}
|
||||
void seek(llong position) { pos = position; }
|
||||
|
||||
//! \~english Move read/write position to the beginning of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на начало буфера
|
||||
void seekToBegin() {if (data_) pos = 0;}
|
||||
void seekToBegin() {
|
||||
if (data_) pos = 0;
|
||||
}
|
||||
|
||||
//! \~english Move read/write position to the end of the buffer
|
||||
//! \~russian Перемещает позицию чтения/записи на конец буфера
|
||||
void seekToEnd() {if (data_) pos = data_->size_s();}
|
||||
void seekToEnd() {
|
||||
if (data_) pos = data_->size_s();
|
||||
}
|
||||
|
||||
|
||||
//! \~english Insert data "ba" into content at current position
|
||||
@@ -85,19 +94,20 @@ public:
|
||||
int writeByteArray(const PIByteArray & ba);
|
||||
|
||||
ssize_t bytesAvailable() const override {
|
||||
if (data_) return data_->size();
|
||||
else return 0;
|
||||
if (data_)
|
||||
return data_->size();
|
||||
else
|
||||
return 0;
|
||||
}
|
||||
|
||||
protected:
|
||||
bool openDevice() override;
|
||||
ssize_t readDevice(void * read_to, ssize_t size) override;
|
||||
ssize_t writeDevice(const void * data_, ssize_t size) override;
|
||||
DeviceInfoFlags deviceInfoFlags() const override {return PIIODevice::Sequential | PIIODevice::Reliable;}
|
||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential | PIIODevice::Reliable; }
|
||||
|
||||
ssize_t pos;
|
||||
PIByteArray * data_;
|
||||
|
||||
};
|
||||
|
||||
#endif // PIIOBYTEARRAY_H
|
||||
|
||||
@@ -18,6 +18,7 @@
|
||||
*/
|
||||
|
||||
#include "piiodevice.h"
|
||||
|
||||
#include "piconfig.h"
|
||||
#include "piconnection.h"
|
||||
#include "pipropertystorage.h"
|
||||
@@ -235,8 +236,7 @@ bool PIIODevice::isThreadedWrite() const {
|
||||
|
||||
|
||||
void PIIODevice::startThreadedWrite() {
|
||||
if (!write_thread.isRunning())
|
||||
write_thread.startOnce();
|
||||
if (!write_thread.isRunning()) write_thread.startOnce();
|
||||
}
|
||||
|
||||
|
||||
@@ -313,11 +313,13 @@ void PIIODevice::_init() {
|
||||
#else
|
||||
threaded_read_buffer_size = 4096;
|
||||
#endif
|
||||
read_thread .setName("__S__.PIIODevice.read_thread" );
|
||||
read_thread.setName("__S__.PIIODevice.read_thread");
|
||||
write_thread.setName("__S__.PIIODevice.write_thread");
|
||||
CONNECT(void, &write_thread, started, this, write_func);
|
||||
CONNECTL(&read_thread, started, [this](){if (!isOpened()) open();});
|
||||
read_thread.setSlot([this](void*){read_func();});
|
||||
CONNECTL(&read_thread, started, [this]() {
|
||||
if (!isOpened()) open();
|
||||
});
|
||||
read_thread.setSlot([this](void *) { read_func(); });
|
||||
}
|
||||
|
||||
|
||||
@@ -339,8 +341,7 @@ void PIIODevice::write_func() {
|
||||
PIIODevice * PIIODevice::newDeviceByPrefix(const char * prefix) {
|
||||
if (!prefix) return nullptr;
|
||||
auto fi = fabrics().value(prefix);
|
||||
if (fi.fabricator)
|
||||
return fi.fabricator();
|
||||
if (fi.fabricator) return fi.fabricator();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -364,10 +365,10 @@ void PIIODevice::read_func() {
|
||||
ssize_t readed_ = read(buffer_tr.data(), buffer_tr.size_s());
|
||||
if (readed_ <= 0) {
|
||||
piMSleep(10);
|
||||
//cout << readed_ << ", " << errno << ", " << errorString() << endl;
|
||||
// cout << readed_ << ", " << errno << ", " << errorString() << endl;
|
||||
return;
|
||||
}
|
||||
//piCoutObj << "readed" << readed_;// << ", " << errno << ", " << errorString();
|
||||
// piCoutObj << "readed" << readed_;// << ", " << errno << ", " << errorString();
|
||||
threadedRead(buffer_tr.data(), readed_);
|
||||
threadedReadEvent(buffer_tr.data(), readed_);
|
||||
}
|
||||
@@ -381,8 +382,10 @@ PIByteArray PIIODevice::readForTime(double timeout_ms) {
|
||||
tm.reset();
|
||||
while (tm.elapsed_m() < timeout_ms) {
|
||||
ret = read(td, threaded_read_buffer_size);
|
||||
if (ret <= 0) piMinSleep();
|
||||
else str.append(td, ret);
|
||||
if (ret <= 0)
|
||||
piMinSleep();
|
||||
else
|
||||
str.append(td, ret);
|
||||
}
|
||||
delete[] td;
|
||||
return str;
|
||||
@@ -442,8 +445,10 @@ bool PIIODevice::configure(const PIString & config_file, const PIString & sectio
|
||||
if (!conf.isOpened()) return false;
|
||||
bool ex = true;
|
||||
PIConfig::Entry em;
|
||||
if (section.isEmpty()) em = conf.rootEntry();
|
||||
else em = conf.getValue(section, PIString(), &ex);
|
||||
if (section.isEmpty())
|
||||
em = conf.rootEntry();
|
||||
else
|
||||
em = conf.getValue(section, PIString(), &ex);
|
||||
if (!ex) return false;
|
||||
PIConfig::Entry * ep = 0;
|
||||
if (parent_section) ep = em.parent();
|
||||
@@ -502,17 +507,20 @@ void PIIODevice::splitFullPath(PIString fpwm, PIString * full_path, DeviceMode *
|
||||
if (fpwm.find('(') > 0 && fpwm.find(')') > 0) {
|
||||
PIString dms(fpwm.right(fpwm.length() - fpwm.findLast('(')).takeRange('(', ')').trim().toLowerCase().removeAll(' '));
|
||||
PIStringList opts(dms.split(","));
|
||||
piForeachC (PIString & o, opts) {
|
||||
//piCout << dms;
|
||||
piForeachC(PIString & o, opts) {
|
||||
// piCout << dms;
|
||||
if (o == PIStringAscii("r") || o == PIStringAscii("ro") || o == PIStringAscii("read") || o == PIStringAscii("readonly"))
|
||||
dm |= ReadOnly;
|
||||
if (o == PIStringAscii("w") || o == PIStringAscii("wo") || o == PIStringAscii("write") || o == PIStringAscii("writeonly"))
|
||||
dm |= WriteOnly;
|
||||
if (o == PIStringAscii("br") || o == PIStringAscii("blockr") || o == PIStringAscii("blockread") || o == PIStringAscii("blockingread"))
|
||||
if (o == PIStringAscii("br") || o == PIStringAscii("blockr") || o == PIStringAscii("blockread") ||
|
||||
o == PIStringAscii("blockingread"))
|
||||
op |= BlockingRead;
|
||||
if (o == PIStringAscii("bw") || o == PIStringAscii("blockw") || o == PIStringAscii("blockwrite") || o == PIStringAscii("blockingwrite"))
|
||||
if (o == PIStringAscii("bw") || o == PIStringAscii("blockw") || o == PIStringAscii("blockwrite") ||
|
||||
o == PIStringAscii("blockingwrite"))
|
||||
op |= BlockingWrite;
|
||||
if (o == PIStringAscii("brw") || o == PIStringAscii("bwr") || o == PIStringAscii("blockrw") || o == PIStringAscii("blockwr") || o == PIStringAscii("blockreadrite") || o == PIStringAscii("blockingreadwrite"))
|
||||
if (o == PIStringAscii("brw") || o == PIStringAscii("bwr") || o == PIStringAscii("blockrw") || o == PIStringAscii("blockwr") ||
|
||||
o == PIStringAscii("blockreadrite") || o == PIStringAscii("blockingreadwrite"))
|
||||
op |= BlockingRead | BlockingWrite;
|
||||
}
|
||||
fpwm.cutRight(fpwm.length() - fpwm.findLast('(')).trim();
|
||||
@@ -542,7 +550,7 @@ PIStringList PIIODevice::availableClasses() {
|
||||
|
||||
void PIIODevice::registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)()) {
|
||||
if (prefix.isEmpty()) return;
|
||||
//printf("registerDevice %s %d %d\n", prefix, p.isEmpty(), fabrics().size());
|
||||
// printf("registerDevice %s %d %d\n", prefix, p.isEmpty(), fabrics().size());
|
||||
if (!fabrics().contains(prefix)) {
|
||||
FabricInfo fi;
|
||||
fi.prefix = prefix;
|
||||
@@ -557,10 +565,26 @@ PIString PIIODevice::fullPathOptions() const {
|
||||
if (mode_ == ReadWrite && options_ == 0) return PIString();
|
||||
PIString ret(" (");
|
||||
bool f = true;
|
||||
if (mode_ == ReadOnly) {if (!f) ret += ","; f = false; ret += "ro";}
|
||||
if (mode_ == WriteOnly) {if (!f) ret += ","; f = false; ret += "wo";}
|
||||
if (options_[BlockingRead]) {if (!f) ret += ","; f = false; ret += "br";}
|
||||
if (options_[BlockingWrite]) {if (!f) ret += ","; f = false; ret += "bw";}
|
||||
if (mode_ == ReadOnly) {
|
||||
if (!f) ret += ",";
|
||||
f = false;
|
||||
ret += "ro";
|
||||
}
|
||||
if (mode_ == WriteOnly) {
|
||||
if (!f) ret += ",";
|
||||
f = false;
|
||||
ret += "wo";
|
||||
}
|
||||
if (options_[BlockingRead]) {
|
||||
if (!f) ret += ",";
|
||||
f = false;
|
||||
ret += "br";
|
||||
}
|
||||
if (options_[BlockingWrite]) {
|
||||
if (!f) ret += ",";
|
||||
f = false;
|
||||
ret += "bw";
|
||||
}
|
||||
return ret + ")";
|
||||
}
|
||||
|
||||
@@ -599,7 +623,7 @@ PIString PIIODevice::normalizeFullPath(const PIString & full_path) {
|
||||
}
|
||||
nfp_mutex.unlock();
|
||||
PIIODevice * d = createFromFullPath(full_path);
|
||||
//piCout << "normalizeFullPath" << d;
|
||||
// piCout << "normalizeFullPath" << d;
|
||||
if (d == 0) return PIString();
|
||||
ret = d->constructFullPath();
|
||||
delete d;
|
||||
@@ -619,8 +643,8 @@ PIMap<PIConstChars, PIIODevice::FabricInfo> & PIIODevice::fabrics() {
|
||||
}
|
||||
|
||||
|
||||
bool PIIODevice::threadedRead(const uchar *readed, ssize_t size) {
|
||||
// piCout << "iodevice threaded read";
|
||||
bool PIIODevice::threadedRead(const uchar * readed, ssize_t size) {
|
||||
// piCout << "iodevice threaded read";
|
||||
if (func_read) return func_read(readed, size, ret_data_);
|
||||
return true;
|
||||
}
|
||||
@@ -636,5 +660,3 @@ PIPropertyStorage PIIODevice::constructVariantDevice() const {
|
||||
void PIIODevice::configureFromVariantDevice(const PIPropertyStorage & d) {
|
||||
setPath(d.propertyValueByName("path").toString());
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -27,8 +27,8 @@
|
||||
#define PIIODEVICE_H
|
||||
|
||||
#include "piinit.h"
|
||||
#include "pitimer.h"
|
||||
#include "piqueue.h"
|
||||
#include "pitimer.h"
|
||||
|
||||
/// TODO: написать документацию, тут ничего не понятно
|
||||
// function executed from threaded read, pass readedData, sizeOfData, ThreadedReadData
|
||||
@@ -58,15 +58,23 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
|
||||
# define REGISTER_DEVICE(name) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIIODevice::registerDevice(name::fullPathPrefixS(), #name, []()->PIIODevice*{return new name();});\
|
||||
PIIODevice::registerDevice(name::fullPathPrefixS(), #name, []() -> PIIODevice * { return new name(); }); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
# define PIIODEVICE(name, prefix) \
|
||||
PIOBJECT_SUBCLASS(name, PIIODevice) \
|
||||
PIIODevice * copy() const override {return new name();} \
|
||||
PIIODevice * copy() const override { \
|
||||
return new name(); \
|
||||
} \
|
||||
\
|
||||
public: \
|
||||
PIConstChars fullPathPrefix() const override {return prefix;} \
|
||||
static PIConstChars fullPathPrefixS() {return prefix;} \
|
||||
PIConstChars fullPathPrefix() const override { \
|
||||
return prefix; \
|
||||
} \
|
||||
static PIConstChars fullPathPrefixS() { \
|
||||
return prefix; \
|
||||
} \
|
||||
\
|
||||
private:
|
||||
|
||||
|
||||
@@ -76,10 +84,10 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
//! \~\brief
|
||||
//! \~english Base class for input/output devices.
|
||||
//! \~russian Базовый класс утройств ввода/вывода.
|
||||
class PIP_EXPORT PIIODevice: public PIObject
|
||||
{
|
||||
class PIP_EXPORT PIIODevice: public PIObject {
|
||||
PIOBJECT_SUBCLASS(PIIODevice, PIObject);
|
||||
friend void __DevicePool_threadReadDP(void * ddp);
|
||||
|
||||
public:
|
||||
NO_COPY_CLASS(PIIODevice);
|
||||
|
||||
@@ -98,8 +106,12 @@ public:
|
||||
//! \~english Options for PIIODevice, works with some devices
|
||||
//! \~russian Опции для PIIODevice, работает для некоторых устройств
|
||||
enum DeviceOption {
|
||||
BlockingRead /*! \~english \a read() block until data is received, default off \~russian \a read() блокируется, пока данные не поступят, по умолчанию выключено */ = 0x01,
|
||||
BlockingWrite /*! \~english \a write() block until data is sent, default off \~russian \a write() блокируется, пока данные не запишутся, по умолчанию выключено */ = 0x02
|
||||
BlockingRead /*! \~english \a read() block until data is received, default off \~russian \a read() блокируется, пока данные не
|
||||
поступят, по умолчанию выключено */
|
||||
= 0x01,
|
||||
BlockingWrite /*! \~english \a write() block until data is sent, default off \~russian \a write() блокируется, пока данные не
|
||||
запишутся, по умолчанию выключено */
|
||||
= 0x02
|
||||
};
|
||||
|
||||
//! \~english Characteristics of PIIODevice channel
|
||||
@@ -112,7 +124,7 @@ public:
|
||||
struct FabricInfo {
|
||||
PIConstChars prefix;
|
||||
PIConstChars classname;
|
||||
PIIODevice*(*fabricator)() = nullptr;
|
||||
PIIODevice * (*fabricator)() = nullptr;
|
||||
};
|
||||
|
||||
typedef PIFlags<DeviceOption> DeviceOptions;
|
||||
@@ -126,19 +138,19 @@ public:
|
||||
|
||||
//! \~english Returns current open mode of device
|
||||
//! \~russian Возвращает текущий режим открытия устройства
|
||||
DeviceMode mode() const {return mode_;}
|
||||
DeviceMode mode() const { return mode_; }
|
||||
|
||||
//! \~english Set open mode of device. Don`t reopen device
|
||||
//! \~russian Устанавливает режим открытия устройства. Не переоткрывает устройство
|
||||
void setMode(DeviceMode m) {mode_ = m;}
|
||||
void setMode(DeviceMode m) { mode_ = m; }
|
||||
|
||||
//! \~english Returns current device options
|
||||
//! \~russian Возвращает текущие опции устройства
|
||||
DeviceOptions options() const {return options_;}
|
||||
DeviceOptions options() const { return options_; }
|
||||
|
||||
//! \~english Returns current device option "o" state
|
||||
//! \~russian Возвращает текущее состояние опции "o"
|
||||
bool isOptionSet(DeviceOption o) const {return options_[o];}
|
||||
bool isOptionSet(DeviceOption o) const { return options_[o]; }
|
||||
|
||||
//! \~english Set device options
|
||||
//! \~russian Устанавливает опции устройства
|
||||
@@ -150,39 +162,39 @@ public:
|
||||
|
||||
//! \~english Returns device characteristic flags
|
||||
//! \~russian Возвращает характеристики канала
|
||||
DeviceInfoFlags infoFlags() const {return deviceInfoFlags();}
|
||||
DeviceInfoFlags infoFlags() const { return deviceInfoFlags(); }
|
||||
|
||||
//! \~english Returns current path of device
|
||||
//! \~russian Возвращает текущий путь устройства
|
||||
PIString path() const {return property("path").toString();}
|
||||
PIString path() const { return property("path").toString(); }
|
||||
|
||||
//! \~english Set path of device. Don`t reopen device
|
||||
//! \~russian Устанавливает путь устройства. Не переоткрывает устройство
|
||||
void setPath(const PIString & path) {setProperty("path", path);}
|
||||
void setPath(const PIString & path) { setProperty("path", path); }
|
||||
|
||||
//! \~english Returns if mode is ReadOnly or ReadWrite
|
||||
//! \~russian Возвращает равен ли режим открытия ReadOnly или ReadWrite
|
||||
bool isReadable() const {return (mode_ & ReadOnly);}
|
||||
bool isReadable() const { return (mode_ & ReadOnly); }
|
||||
|
||||
//! \~english Returns if mode is WriteOnly or ReadWrite
|
||||
//! \~russian Возвращает равен ли режим открытия WriteOnly или ReadWrite
|
||||
bool isWriteable() const {return (mode_ & WriteOnly);}
|
||||
bool isWriteable() const { return (mode_ & WriteOnly); }
|
||||
|
||||
//! \~english Returns if device is successfully opened
|
||||
//! \~russian Возвращает успешно ли открыто устройство
|
||||
bool isOpened() const {return opened_;}
|
||||
bool isOpened() const { return opened_; }
|
||||
|
||||
//! \~english Returns if device is closed
|
||||
//! \~russian Возвращает закрыто ли устройство
|
||||
bool isClosed() const {return !opened_;}
|
||||
bool isClosed() const { return !opened_; }
|
||||
|
||||
//! \~english Returns if device can read \b now
|
||||
//! \~russian Возвращает может ли устройство читать \b сейчас
|
||||
virtual bool canRead() const {return opened_ && (mode_ & ReadOnly);}
|
||||
virtual bool canRead() const { return opened_ && (mode_ & ReadOnly); }
|
||||
|
||||
//! \~english Returns if device can write \b now
|
||||
//! \~russian Возвращает может ли устройство писать \b сейчас
|
||||
virtual bool canWrite() const {return opened_ && (mode_ & WriteOnly);}
|
||||
virtual bool canWrite() const { return opened_ && (mode_ & WriteOnly); }
|
||||
|
||||
|
||||
//! \~english Set calling of \a open() enabled while threaded read on closed device
|
||||
@@ -195,11 +207,11 @@ public:
|
||||
|
||||
//! \~english Returns reopen enable
|
||||
//! \~russian Возвращает активно ли переоткрытие
|
||||
bool isReopenEnabled() const {return property("reopenEnabled").toBool();}
|
||||
bool isReopenEnabled() const { return property("reopenEnabled").toBool(); }
|
||||
|
||||
//! \~english Returns reopen timeout in milliseconds
|
||||
//! \~russian Возвращает задержку переоткрытия в миллисекундах
|
||||
int reopenTimeout() {return property("reopenTimeout").toInt();}
|
||||
int reopenTimeout() { return property("reopenTimeout").toInt(); }
|
||||
|
||||
|
||||
//! \~english Set threaded read callback
|
||||
@@ -208,7 +220,7 @@ public:
|
||||
|
||||
//! \~english Set custom data that will be passed to threaded read callback
|
||||
//! \~russian Устанавливает произвольный указатель, который будет передан в callback потокового чтения
|
||||
void setThreadedReadData(void * d) {ret_data_ = d;}
|
||||
void setThreadedReadData(void * d) { ret_data_ = d; }
|
||||
|
||||
//! \~english Set size of threaded read buffer
|
||||
//! \~russian Устанавливает размер буфера потокового чтения
|
||||
@@ -216,15 +228,15 @@ public:
|
||||
|
||||
//! \~english Returns size of threaded read buffer
|
||||
//! \~russian Возвращает размер буфера потокового чтения
|
||||
int threadedReadBufferSize() const {return threaded_read_buffer_size;}
|
||||
int threadedReadBufferSize() const { return threaded_read_buffer_size; }
|
||||
|
||||
//! \~english Returns content of threaded read buffer
|
||||
//! \~russian Возвращает содержимое буфера потокового чтения
|
||||
const uchar * threadedReadBuffer() const {return buffer_tr.data();}
|
||||
const uchar * threadedReadBuffer() const { return buffer_tr.data(); }
|
||||
|
||||
//! \~english Returns custom data that will be passed to threaded read callback
|
||||
//! \~russian Возвращает произвольный указатель, который будет передан в callback потокового чтения
|
||||
void * threadedReadData() const {return ret_data_;}
|
||||
void * threadedReadData() const { return ret_data_; }
|
||||
|
||||
|
||||
//! \~english Returns if threaded read is started
|
||||
@@ -307,7 +319,7 @@ public:
|
||||
//! \~russian Эта функция как правило используется чтобы знать какой
|
||||
//! размер буфера нужен в памяти для чтения.
|
||||
//! Если функция возвращает -1 это значит что количество байт для чтения не известно.
|
||||
virtual ssize_t bytesAvailable() const {return -1;}
|
||||
virtual ssize_t bytesAvailable() const { return -1; }
|
||||
|
||||
//! \~english Write maximum "max_size" bytes of "data" to device
|
||||
//! \~russian Пишет в устройство не более "max_size" байт из "data"
|
||||
@@ -322,7 +334,7 @@ public:
|
||||
|
||||
//! \~english Add task to threaded write queue and return task ID
|
||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
||||
ullong writeThreaded(const void * data, ssize_t max_size) {return writeThreaded(PIByteArray(data, uint(max_size)));}
|
||||
ullong writeThreaded(const void * data, ssize_t max_size) { return writeThreaded(PIByteArray(data, uint(max_size))); }
|
||||
|
||||
//! \~english Add task to threaded write queue and return task ID
|
||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
||||
@@ -336,9 +348,9 @@ public:
|
||||
|
||||
//! \~english Returns full unambiguous string prefix. \ref PIIODevice_sec7
|
||||
//! \~russian Возвращает префикс устройства. \ref PIIODevice_sec7
|
||||
virtual PIConstChars fullPathPrefix() const {return "";}
|
||||
virtual PIConstChars fullPathPrefix() const { return ""; }
|
||||
|
||||
static PIConstChars fullPathPrefixS() {return "";}
|
||||
static PIConstChars fullPathPrefixS() { return ""; }
|
||||
|
||||
//! \~english Returns full unambiguous string, describes this device, \a fullPathPrefix() + "://" + ...
|
||||
//! \~russian Возвращает строку полного описания для этого устройства, \a fullPathPrefix() + "://" + ...
|
||||
@@ -376,7 +388,7 @@ public:
|
||||
//! \~russian Возвращает имена классов всех зарегистрированных устройств
|
||||
static PIStringList availableClasses();
|
||||
|
||||
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice*(*fabric)());
|
||||
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)());
|
||||
|
||||
|
||||
EVENT_HANDLER(bool, open);
|
||||
@@ -388,17 +400,17 @@ public:
|
||||
|
||||
//! \~english Write memory block "mb" to device
|
||||
//! \~russian Пишет в устройство блок памяти "mb"
|
||||
ssize_t write(const PIMemoryBlock & mb) {return write(mb.data(), mb.size());}
|
||||
ssize_t write(const PIMemoryBlock & mb) { return write(mb.data(), mb.size()); }
|
||||
|
||||
EVENT_VHANDLER(void, flush) {;}
|
||||
EVENT_VHANDLER(void, flush) { ; }
|
||||
|
||||
EVENT(opened);
|
||||
EVENT(closed);
|
||||
EVENT2(threadedReadEvent, const uchar * , readed, ssize_t, size);
|
||||
EVENT2(threadedReadEvent, const uchar *, readed, ssize_t, size);
|
||||
EVENT2(threadedWriteEvent, ullong, id, ssize_t, written_size);
|
||||
|
||||
//! \handlers
|
||||
//! \{
|
||||
//! \handlers
|
||||
//! \{
|
||||
|
||||
//! \fn bool open()
|
||||
//! \~english Open device
|
||||
@@ -424,17 +436,17 @@ public:
|
||||
//! \~english Write "data" to device
|
||||
//! \~russian Пишет "data" в устройство
|
||||
|
||||
//! \}
|
||||
//! \vhandlers
|
||||
//! \{
|
||||
//! \}
|
||||
//! \vhandlers
|
||||
//! \{
|
||||
|
||||
//! \fn void flush()
|
||||
//! \~english Immediate write all buffers
|
||||
//! \~russian Немедленно записать все буферизированные данные
|
||||
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
//! \}
|
||||
//! \events
|
||||
//! \{
|
||||
|
||||
//! \fn void opened()
|
||||
//! \~english Raise if succesfull open
|
||||
@@ -468,12 +480,12 @@ public:
|
||||
//! \~russian setThreadedReadBufferSize в байтах, по умолчанию 4096
|
||||
int threadedReadBufferSize;
|
||||
#endif
|
||||
//! \}
|
||||
//! \}
|
||||
|
||||
protected:
|
||||
//! \~english Reimplement to configure device from entries "e_main" and "e_parent", cast arguments to \a PIConfig::Entry*
|
||||
//! \~russian
|
||||
virtual bool configureDevice(const void * e_main, const void * e_parent = 0) {return true;}
|
||||
virtual bool configureDevice(const void * e_main, const void * e_parent = 0) { return true; }
|
||||
|
||||
//! \~english Reimplement to open device, return value will be set to "opened_" variable.
|
||||
//! Don't call this function in subclass, use \a open()!
|
||||
@@ -483,15 +495,21 @@ protected:
|
||||
|
||||
//! \~english Reimplement to close device, inverse return value will be set to "opened_" variable
|
||||
//! \~russian Переопределите для закрытия устройства, обратное возвращаемое значение будет установлено в переменную "opened_"
|
||||
virtual bool closeDevice() {return true;} // use path_, type_, opened_, init_ variables
|
||||
virtual bool closeDevice() { return true; } // use path_, type_, opened_, init_ variables
|
||||
|
||||
//! \~english Reimplement this function to read from your device
|
||||
//! \~russian Переопределите для чтения данных из устройства
|
||||
virtual ssize_t readDevice(void * read_to, ssize_t max_size) {piCoutObj << "\"read\" is not implemented!"; return -2;}
|
||||
virtual ssize_t readDevice(void * read_to, ssize_t max_size) {
|
||||
piCoutObj << "\"read\" is not implemented!";
|
||||
return -2;
|
||||
}
|
||||
|
||||
//! \~english Reimplement this function to write to your device
|
||||
//! \~russian Переопределите для записи данных в устройство
|
||||
virtual ssize_t writeDevice(const void * data, ssize_t max_size) {piCoutObj << "\"write\" is not implemented!"; return -2;}
|
||||
virtual ssize_t writeDevice(const void * data, ssize_t max_size) {
|
||||
piCoutObj << "\"write\" is not implemented!";
|
||||
return -2;
|
||||
}
|
||||
|
||||
//! \~english Function executed when thread read some data, default implementation execute external callback "ret_func_"
|
||||
//! \~russian Метод вызывается после каждого успешного потокового чтения, по умолчанию вызывает callback "ret_func_"
|
||||
@@ -501,13 +519,13 @@ protected:
|
||||
//! Default implementation returns \a path()
|
||||
//! \~russian Переопределите для создания строки полного описания устройства.
|
||||
//! По умолчанию возвращает \a path()
|
||||
virtual PIString constructFullPathDevice() const {return path();}
|
||||
virtual PIString constructFullPathDevice() const { return path(); }
|
||||
|
||||
//! \~english Reimplement to configure your device with parameters of full unambiguous string.
|
||||
//! Default implementation call \a setPath()
|
||||
//! \~russian Переопределите для настройки устройства из строки полного описания.
|
||||
//! По умолчанию вызывает \a setPath()
|
||||
virtual void configureFromFullPathDevice(const PIString & full_path) {setPath(full_path);}
|
||||
virtual void configureFromFullPathDevice(const PIString & full_path) { setPath(full_path); }
|
||||
|
||||
//! \~english Reimplement to construct device properties.
|
||||
//! Default implementation return PIPropertyStorage with \"path\" entry
|
||||
@@ -523,19 +541,19 @@ protected:
|
||||
|
||||
//! \~english Reimplement to apply new device options
|
||||
//! \~russian Переопределите для применения новых опций устройства
|
||||
virtual void optionsChanged() {;}
|
||||
virtual void optionsChanged() { ; }
|
||||
|
||||
//! \~english Reimplement to return correct \a DeviceInfoFlags. Default implementation returns 0
|
||||
//! \~russian Переопределите для возврата правильных \a DeviceInfoFlags. По умолчанию возвращает 0
|
||||
virtual DeviceInfoFlags deviceInfoFlags() const {return 0;}
|
||||
virtual DeviceInfoFlags deviceInfoFlags() const { return 0; }
|
||||
|
||||
//! \~english Reimplement to apply new \a threadedReadBufferSize()
|
||||
//! \~russian Переопределите для применения нового \a threadedReadBufferSize()
|
||||
virtual void threadedReadBufferSizeChanged() {;}
|
||||
virtual void threadedReadBufferSizeChanged() { ; }
|
||||
|
||||
static PIIODevice * newDeviceByPrefix(const char * prefix);
|
||||
|
||||
bool isThreadedReadStopping() const {return read_thread.isStopping();}
|
||||
bool isThreadedReadStopping() const { return read_thread.isStopping(); }
|
||||
|
||||
DeviceMode mode_;
|
||||
DeviceOptions options_;
|
||||
@@ -547,7 +565,7 @@ private:
|
||||
EVENT_HANDLER(void, read_func);
|
||||
EVENT_HANDLER(void, write_func);
|
||||
|
||||
virtual PIIODevice * copy() const {return nullptr;}
|
||||
virtual PIIODevice * copy() const { return nullptr; }
|
||||
PIString fullPathOptions() const;
|
||||
void _init();
|
||||
static void cacheFullPath(const PIString & full_path, const PIIODevice * d);
|
||||
@@ -556,14 +574,13 @@ private:
|
||||
PITimeMeasurer tm, reopen_tm;
|
||||
PIThread read_thread, write_thread;
|
||||
PIByteArray buffer_in, buffer_tr;
|
||||
PIQueue<PIPair<PIByteArray, ullong> > write_queue;
|
||||
PIQueue<PIPair<PIByteArray, ullong>> write_queue;
|
||||
ullong tri = 0;
|
||||
uint threaded_read_buffer_size, reopen_timeout = 1000;
|
||||
bool reopen_enabled = true, destroying = false;
|
||||
|
||||
static PIMutex nfp_mutex;
|
||||
static PIMap<PIString, PIString> nfp_cache;
|
||||
|
||||
};
|
||||
|
||||
#endif // PIIODEVICE_H
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user