more ai generated doc with human review
This commit is contained in:
@@ -64,13 +64,25 @@ public:
|
||||
//! \~english Returns unparsed command-line argument by index "index". Index 0 is program execute command.
|
||||
//! \~russian Возвращает исходный аргумент командной строки по индексу "index". Индекс 0 это команда вызова программы.
|
||||
PIString rawArgument(int index);
|
||||
|
||||
//! \~english Returns mandatory command-line argument by index "index".
|
||||
//! \~russian Возвращает обязательный аргумент командной строки по индексу "index".
|
||||
PIString mandatoryArgument(int index);
|
||||
|
||||
//! \~english Returns optional command-line argument by index "index".
|
||||
//! \~russian Возвращает опциональный аргумент командной строки по индексу "index".
|
||||
PIString optionalArgument(int index);
|
||||
|
||||
//! \~english Returns unparsed command-line arguments.
|
||||
//! \~russian Возвращает исходные аргументы командной строки.
|
||||
const PIStringList & rawArguments();
|
||||
|
||||
//! \~english Returns mandatory command-line arguments.
|
||||
//! \~russian Возвращает обязательные аргументы командной строки.
|
||||
const PIStringList & mandatoryArguments();
|
||||
|
||||
//! \~english Returns optional command-line arguments.
|
||||
//! \~russian Возвращает опциональные аргументы командной строки.
|
||||
const PIStringList & optionalArguments();
|
||||
|
||||
//! \~english Returns program execute command without arguments.
|
||||
@@ -93,18 +105,52 @@ public:
|
||||
//! \~russian Возвращает полный ключ аргумента "name" или пустую строку, если аргумента нет.
|
||||
PIString argumentFullKey(const PIString & name);
|
||||
|
||||
//! \~english Returns short key prefix.
|
||||
//! \~russian Возвращает префикс короткого ключа.
|
||||
const PIString & shortKeyPrefix() const { return _prefix_short; }
|
||||
|
||||
//! \~english Returns full key prefix.
|
||||
//! \~russian Возвращает префикс полного ключа.
|
||||
const PIString & fullKeyPrefix() const { return _prefix_full; }
|
||||
|
||||
//! \~english Returns mandatory arguments count.
|
||||
//! \~russian Возвращает количество обязательных аргументов.
|
||||
int mandatoryArgumentsCount() const { return _count_mand; }
|
||||
|
||||
//! \~english Returns optional arguments count.
|
||||
//! \~russian Возвращает количество опциональных аргументов.
|
||||
int optionalArgumentsCount() const { return _count_opt; }
|
||||
|
||||
//! \~english Sets short key prefix.
|
||||
//! \~russian Устанавливает префикс короткого ключа.
|
||||
void setShortKeyPrefix(const PIString & prefix);
|
||||
|
||||
//! \~english Sets full key prefix.
|
||||
//! \~russian Устанавливает префикс полного ключа.
|
||||
void setFullKeyPrefix(const PIString & prefix);
|
||||
|
||||
//! \~english Sets mandatory arguments count.
|
||||
//! \~russian Устанавливает количество обязательных аргументов.
|
||||
void setMandatoryArgumentsCount(const int count);
|
||||
|
||||
//! \~english Sets optional arguments count.
|
||||
//! \~russian Устанавливает количество опциональных аргументов.
|
||||
void setOptionalArgumentsCount(const int count);
|
||||
|
||||
//! \~english Returns debug mode state.
|
||||
//! \~russian Возвращает состояние режима отладки.
|
||||
bool debug() const { return debug_; }
|
||||
|
||||
//! \~english Sets debug mode state.
|
||||
//! \~russian Устанавливает состояние режима отладки.
|
||||
void setDebug(bool debug) { debug_ = debug; }
|
||||
|
||||
//! \~english Returns class name.
|
||||
//! \~russian Возвращает имя класса.
|
||||
PIConstChars className() const { return "PICLI"; }
|
||||
|
||||
//! \~english Returns object name.
|
||||
//! \~russian Возвращает имя объекта.
|
||||
PIString name() const { return PIStringAscii("CLI"); }
|
||||
|
||||
private:
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
High-level log
|
||||
High-level log
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -38,7 +38,12 @@ class PIP_EXPORT PILog: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PILog, PIThread)
|
||||
|
||||
public:
|
||||
//! \~english Constructs empty %PILog.
|
||||
//! \~russian Создает пустой %PILog.
|
||||
PILog();
|
||||
|
||||
//! \~english Destructor. Calls stop().
|
||||
//! \~russian Деструктор. Вызывает stop().
|
||||
~PILog();
|
||||
|
||||
//! \~english Message category
|
||||
|
||||
@@ -42,6 +42,8 @@ public:
|
||||
//! \~russian Создает %PISingleApplication с именем "app_name"
|
||||
PISingleApplication(const PIString & app_name = PIString());
|
||||
|
||||
//! \~english Destructor.
|
||||
//! \~russian Деструктор.
|
||||
~PISingleApplication();
|
||||
|
||||
|
||||
|
||||
@@ -227,23 +227,25 @@ public:
|
||||
//! \~russian Возвращает статистику потоков наблюдаемого процесса
|
||||
PIVector<ThreadStats> threadsStatistic() const;
|
||||
|
||||
//! \~english Sets process statistics.
|
||||
//! \~russian Устанавливает статистику процесса.
|
||||
void setStatistic(const ProcessStats & s);
|
||||
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns total RAM in bytes.
|
||||
//! \~russian Возвращает общий объем ОЗУ в байтах.
|
||||
static ullong totalRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns free RAM in bytes.
|
||||
//! \~russian Возвращает свободный объем ОЗУ в байтах.
|
||||
static ullong freeRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Returns used RAM in bytes.
|
||||
//! \~russian Возвращает используемый объем ОЗУ в байтах.
|
||||
static ullong usedRAM();
|
||||
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Event raised when new measurements are available.
|
||||
//! \~russian Событие вызывается когда доступны новые измерения.
|
||||
EVENT(measured);
|
||||
|
||||
private:
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Translation support
|
||||
Translation support
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -38,15 +38,40 @@
|
||||
//! \~russian Поддержка перевода
|
||||
class PIP_EXPORT PITranslator {
|
||||
public:
|
||||
//! \~english Translates string "in" with optional context.
|
||||
//! \~russian Переводит строку "in" с опциональным контекстом.
|
||||
static PIString tr(const PIString & in, const PIString & context = {});
|
||||
|
||||
//! \~english Translates string "in" with optional context.
|
||||
//! \~russian Переводит строку "in" с опциональным контекстом.
|
||||
static PIString tr(const char * in, const PIString & context = {}) { return tr(PIString::fromUTF8(in), context); }
|
||||
|
||||
//! \~english Returns original string without translation.
|
||||
//! \~russian Возвращает оригинальную строку без перевода.
|
||||
static PIString trNoOp(const PIString & in, const PIString & context = {}) { return in; }
|
||||
|
||||
//! \~english Returns original string without translation.
|
||||
//! \~russian Возвращает оригинальную строку без перевода.
|
||||
static PIString trNoOp(const char * in, const PIString & context = {}) { return trNoOp(PIString::fromUTF8(in), context); }
|
||||
|
||||
//! \~english Clears all loaded translations.
|
||||
//! \~russian Очищает все загруженные переводы.
|
||||
static void clear();
|
||||
|
||||
//! \~english Loads translation for language "short_lang" from directory "dir".
|
||||
//! \~russian Загружает перевод для языка "short_lang" из директории "dir".
|
||||
static void loadLang(const PIString & short_lang, PIString dir = {});
|
||||
|
||||
//! \~english Loads translation from config "content".
|
||||
//! \~russian Загружает перевод из конфигурации "content".
|
||||
static void loadConfig(const PIString & content);
|
||||
|
||||
//! \~english Loads translation from binary content.
|
||||
//! \~russian Загружает перевод из бинарного содержимого.
|
||||
static bool load(const PIByteArray & content);
|
||||
|
||||
//! \~english Loads translation from file.
|
||||
//! \~russian Загружает перевод из файла.
|
||||
static bool loadFile(const PIString & path);
|
||||
|
||||
private:
|
||||
@@ -59,10 +84,20 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Context-aware string wrapper for translation.
|
||||
//! \~russian Контекстно-зависимая обертка строки для перевода.
|
||||
class PIStringContextTr {
|
||||
public:
|
||||
//! \~english Constructs wrapper from string.
|
||||
//! \~russian Создает обертку из строки.
|
||||
PIStringContextTr(PIString && s): _s(s) {}
|
||||
|
||||
//! \~english Returns translated string.
|
||||
//! \~russian Возвращает переведенную строку.
|
||||
operator PIString() const { return PITranslator::tr(_s); }
|
||||
|
||||
//! \~english Returns translated string with context.
|
||||
//! \~russian Возвращает переведенную строку с контекстом.
|
||||
PIString operator()(const PIString & ctx = {}) const { return PITranslator::tr(_s, ctx); }
|
||||
|
||||
private:
|
||||
@@ -70,10 +105,20 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Context-aware string wrapper without translation (no-op).
|
||||
//! \~russian Контекстно-зависимая обертка строки без перевода (заглушка).
|
||||
class PIStringContextTrNoOp {
|
||||
public:
|
||||
//! \~english Constructs wrapper from string.
|
||||
//! \~russian Создает обертку из строки.
|
||||
PIStringContextTrNoOp(PIString && s): _s(s) {}
|
||||
|
||||
//! \~english Returns original string.
|
||||
//! \~russian Возвращает оригинальную строку.
|
||||
operator PIString() const { return _s; }
|
||||
|
||||
//! \~english Returns original string with context.
|
||||
//! \~russian Возвращает оригинальную строку с контекстом.
|
||||
PIString operator()(const PIString & ctx = {}) const { return _s; }
|
||||
|
||||
private:
|
||||
|
||||
@@ -35,13 +35,18 @@ namespace PIClientServer {
|
||||
|
||||
// ServerClient
|
||||
|
||||
//! ~english Server-side client implementation
|
||||
//! ~russian Серверная реализация клиента
|
||||
//! \details
|
||||
//! \~english Server-side client representation. Created and managed by Server. Used to communicate with remote clients connected to the
|
||||
//! server.
|
||||
//! \~russian Представление клиента на стороне сервера. Создаётся и управляется сервером. Используется для коммуникации с удалёнными
|
||||
//! клиентами, подключёнными к серверу.
|
||||
class PIP_CLIENT_SERVER_EXPORT ServerClient: public ClientBase {
|
||||
friend class Server;
|
||||
NO_COPY_CLASS(ServerClient);
|
||||
|
||||
public:
|
||||
//! \~english Creates empty ServerClient instance
|
||||
//! \~russian Создает пустой экземпляр ServerClient
|
||||
ServerClient() {}
|
||||
|
||||
protected:
|
||||
@@ -56,13 +61,20 @@ private:
|
||||
|
||||
// Client
|
||||
|
||||
//! ~english Client implementation for connecting to servers
|
||||
//! ~russian Клиентская реализация для подключения к серверам
|
||||
//! \details
|
||||
//! \~english Client implementation for connecting to servers. Provides TCP connection to remote server with diagnostics and packet
|
||||
//! streaming support.
|
||||
//! \~russian Реализация клиента для подключения к серверам. Обеспечивает TCP-соединение с удалённым сервером с поддержкой диагностики и
|
||||
//! потоковой передачи пакетов.
|
||||
class PIP_CLIENT_SERVER_EXPORT Client: public ClientBase {
|
||||
NO_COPY_CLASS(Client);
|
||||
|
||||
public:
|
||||
//! \~english Creates Client instance
|
||||
//! \~russian Создает экземпляр Client
|
||||
Client();
|
||||
//! \~english Destroys Client instance
|
||||
//! \~russian Уничтожает экземпляр Client
|
||||
~Client();
|
||||
|
||||
//! ~english Connects to specified server address
|
||||
|
||||
@@ -42,6 +42,11 @@ class ClientInterface {};
|
||||
//! \brief
|
||||
//! \~english Base class for client and server-side client
|
||||
//! \~russian Базовый класс для клиента и клиента на стороне сервера
|
||||
//! \details
|
||||
//! \~english Base class for client and server-side client communication. Provides TCP connection management, diagnostics, and packet
|
||||
//! streaming capabilities.
|
||||
//! \~russian Базовый класс для клиентской и серверной коммуникации. Обеспечивает управление TCP-соединением, диагностику и потоковую
|
||||
//! передачу пакетов.
|
||||
// template<bool EnableDiagnostics = false>
|
||||
class PIP_CLIENT_SERVER_EXPORT ClientBase {
|
||||
friend class Server;
|
||||
|
||||
@@ -40,14 +40,21 @@ namespace PIClientServer {
|
||||
|
||||
class ServerClient;
|
||||
|
||||
//! ~english TCP server for client-server communication
|
||||
//! ~russian TCP сервер для клиент-серверного взаимодействия
|
||||
//! \details
|
||||
//! \~english TCP server implementation for client-server communication. Accepts incoming connections and manages multiple clients with
|
||||
//! configurable factory for client instance creation.
|
||||
//! \~russian Реализация TCP сервера для клиент-серверного взаимодействия. Принимает входящие соединения и управляет несколькими клиентами с
|
||||
//! настраиваемой фабрикой для создания экземпляров клиентов.
|
||||
class PIP_CLIENT_SERVER_EXPORT Server: public PIStreamPackerConfig {
|
||||
friend class ServerClient;
|
||||
NO_COPY_CLASS(Server);
|
||||
|
||||
public:
|
||||
//! \~english Creates Server instance
|
||||
//! \~russian Создает экземпляр Server
|
||||
Server();
|
||||
//! \~english Destroys Server instance
|
||||
//! \~russian Уничтожает экземпляр Server
|
||||
virtual ~Server();
|
||||
|
||||
//! ~english Starts listening on specified address
|
||||
|
||||
@@ -32,6 +32,9 @@
|
||||
#include "piconditionvar.h"
|
||||
|
||||
|
||||
//! \brief PICloud server implementation
|
||||
//! \~english PICloud server for accepting client connections
|
||||
//! \~russian Сервер PICloud для приема подключений клиентов
|
||||
class PIP_CLOUD_EXPORT PICloudServer
|
||||
: public PIIODevice
|
||||
, public PICloudBase {
|
||||
|
||||
@@ -64,6 +64,8 @@ typedef int (*AccessOffsetFunction)(const char *);
|
||||
//! \~english Type information
|
||||
//! \~russian Информация о типе
|
||||
struct PIP_EXPORT TypeInfo {
|
||||
//! \~english Default constructor
|
||||
//! \~russian Конструктор по умолчанию
|
||||
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {
|
||||
name = n;
|
||||
type = t;
|
||||
@@ -121,6 +123,8 @@ struct PIP_EXPORT FunctionInfo {
|
||||
//! \~english Class or struct information
|
||||
//! \~russian Информация о классе или структуре
|
||||
struct PIP_EXPORT ClassInfo {
|
||||
//! \~english Default constructor
|
||||
//! \~russian Конструктор по умолчанию
|
||||
ClassInfo() { is_anonymous = false; }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
@@ -160,10 +164,14 @@ struct PIP_EXPORT ClassInfo {
|
||||
//! \~english Enumerator information
|
||||
//! \~russian Информация об элементе перечисления
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
//! \~english Default constructor
|
||||
//! \~russian Конструктор по умолчанию
|
||||
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {
|
||||
name = n;
|
||||
value = v;
|
||||
}
|
||||
//! \~english Converts to PIVariantTypes::Enumerator
|
||||
//! \~russian Конвертирует в PIVariantTypes::Enumerator
|
||||
PIVariantTypes::Enumerator toPIVariantEnumerator() { return PIVariantTypes::Enumerator(value, name.toString()); }
|
||||
|
||||
//! \~english Custom PIMETA content
|
||||
@@ -209,6 +217,8 @@ struct PIP_EXPORT EnumInfo {
|
||||
};
|
||||
|
||||
|
||||
//! \~english Output stream operator for TypeInfo
|
||||
//! \~russian Оператор вывода для TypeInfo
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
if (v.flags[Inline]) s << "inline ";
|
||||
if (v.flags[Virtual]) s << "virtual ";
|
||||
@@ -221,11 +231,15 @@ inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Output stream operator for EnumeratorInfo
|
||||
//! \~russian Оператор вывода для EnumeratorInfo
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumeratorInfo & v) {
|
||||
s << v.name << " = " << v.value << " Meta" << v.meta;
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Output stream operator for ClassInfo
|
||||
//! \~russian Оператор вывода для ClassInfo
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "class " << v.name;
|
||||
@@ -262,6 +276,8 @@ inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Output stream operator for EnumInfo
|
||||
//! \~russian Оператор вывода для EnumInfo
|
||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
s.saveAndSetControls(0);
|
||||
s << "enum " << v.name << " Meta" << v.meta << " {\n";
|
||||
@@ -279,11 +295,19 @@ inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Storage singleton for PICodeInfo
|
||||
//! \~russian Синглтон хранилища для PICodeInfo
|
||||
class PIP_EXPORT __Storage__ {
|
||||
//! \~english Default constructor
|
||||
//! \~russian Конструктор по умолчанию
|
||||
__Storage__();
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~__Storage__();
|
||||
|
||||
public:
|
||||
//! \~english Returns singleton instance
|
||||
//! \~russian Возвращает экземпляр синглтона
|
||||
static __Storage__ * instance();
|
||||
|
||||
PIMap<PIConstChars, PICodeInfo::ClassInfo *> * classesInfo;
|
||||
@@ -296,71 +320,83 @@ private:
|
||||
NO_COPY_CLASS(__Storage__)
|
||||
};
|
||||
|
||||
class PIP_EXPORT
|
||||
__StorageAccess__{public:
|
||||
//! \~english Getter for single storage of PICodeInfo::ClassInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу PICodeInfo::ClassInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes(){return *(__Storage__::instance()->classesInfo);
|
||||
} // namespace PICodeInfo
|
||||
//! \~english Access to singleton storage of PICodeInfo
|
||||
//! \~russian Доступ к синглтону хранилища PICodeInfo
|
||||
class PIP_EXPORT __StorageAccess__ {
|
||||
public:
|
||||
//! \~english Getter for single storage of PICodeInfo::ClassInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу PICodeInfo::ClassInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes() {
|
||||
return *(__Storage__::instance()->classesInfo);
|
||||
} // namespace PICodeInfo
|
||||
|
||||
//! \~english Getter for single storage of PICodeInfo::EnumInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу хранилище PICodeInfo::EnumInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() {
|
||||
return *(__Storage__::instance()->enumsInfo);
|
||||
}
|
||||
//! \~english Getter for single storage of PICodeInfo::EnumInfo, access by name
|
||||
//! \~russian Доступ к единому хранилищу хранилище PICodeInfo::EnumInfo, доступ по имени
|
||||
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() { return *(__Storage__::instance()->enumsInfo); }
|
||||
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> & accessValueFunctions() {
|
||||
return *(__Storage__::instance()->accessValueFunctions);
|
||||
}
|
||||
//! \~english Access to value functions map
|
||||
//! \~russian Доступ к карте функций значений
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> & accessValueFunctions() {
|
||||
return *(__Storage__::instance()->accessValueFunctions);
|
||||
}
|
||||
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFunctions() {
|
||||
return *(__Storage__::instance()->accessTypeFunctions);
|
||||
}
|
||||
//! \~english Access to type functions map
|
||||
//! \~russian Доступ к карте функций типов
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFunctions() {
|
||||
return *(__Storage__::instance()->accessTypeFunctions);
|
||||
}
|
||||
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
|
||||
return *(__Storage__::instance()->accessOffsetFunctions);
|
||||
}
|
||||
}
|
||||
;
|
||||
//! \~english Access to offset functions map
|
||||
//! \~russian Доступ к карте функций смещений
|
||||
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
|
||||
return *(__Storage__::instance()->accessOffsetFunctions);
|
||||
}
|
||||
};
|
||||
|
||||
#define PICODEINFO PICodeInfo::__StorageAccess__
|
||||
|
||||
|
||||
class PIP_EXPORT
|
||||
ClassInfoInterface{public: const PIMap<PIConstChars, PICodeInfo::ClassInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::classes()"){
|
||||
return __Storage__::instance() -> classesInfo;
|
||||
}
|
||||
}
|
||||
;
|
||||
//! \~english Deprecated interface for accessing classes info
|
||||
//! \~russian Устаревший интерфейс для доступа к информации о классах
|
||||
class PIP_EXPORT ClassInfoInterface {
|
||||
public:
|
||||
const PIMap<PIConstChars, PICodeInfo::ClassInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::classes()") {
|
||||
return __Storage__::instance()->classesInfo;
|
||||
}
|
||||
};
|
||||
static ClassInfoInterface classesInfo;
|
||||
|
||||
|
||||
class PIP_EXPORT
|
||||
EnumsInfoInterface{public: const PIMap<PIConstChars, PICodeInfo::EnumInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::enums()"){
|
||||
return __Storage__::instance() -> enumsInfo;
|
||||
}
|
||||
}
|
||||
;
|
||||
//! \~english Deprecated interface for accessing enums info
|
||||
//! \~russian Устаревший интерфейс для доступа к информации о перечислениях
|
||||
class PIP_EXPORT EnumsInfoInterface {
|
||||
public:
|
||||
const PIMap<PIConstChars, PICodeInfo::EnumInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::enums()") {
|
||||
return __Storage__::instance()->enumsInfo;
|
||||
}
|
||||
};
|
||||
static EnumsInfoInterface enumsInfo;
|
||||
|
||||
|
||||
class PIP_EXPORT AccessValueFunctionInterface{
|
||||
public: const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * operator->()
|
||||
const DEPRECATEDM("use PICODEINFO::accessValueFunctions()"){
|
||||
return __Storage__::instance() -> accessValueFunctions;
|
||||
}
|
||||
}
|
||||
;
|
||||
//! \~english Deprecated interface for accessing value functions
|
||||
//! \~russian Устаревший интерфейс для доступа к функциям значений
|
||||
class PIP_EXPORT AccessValueFunctionInterface {
|
||||
public:
|
||||
const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * operator->() const DEPRECATEDM("use PICODEINFO::accessValueFunctions()") {
|
||||
return __Storage__::instance()->accessValueFunctions;
|
||||
}
|
||||
};
|
||||
static AccessValueFunctionInterface accessValueFunctions;
|
||||
|
||||
|
||||
class PIP_EXPORT AccessTypeFunctionInterface{
|
||||
public: const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * operator->()
|
||||
const DEPRECATEDM("use PICODEINFO::accessTypeFunctions()"){
|
||||
return __Storage__::instance() -> accessTypeFunctions;
|
||||
}
|
||||
}
|
||||
;
|
||||
//! \~english Deprecated interface for accessing type functions
|
||||
//! \~russian Устаревший интерфейс для доступа к функциям типов
|
||||
class PIP_EXPORT AccessTypeFunctionInterface {
|
||||
public:
|
||||
const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * operator->() const DEPRECATEDM("use PICODEINFO::accessTypeFunctions()") {
|
||||
return __Storage__::instance()->accessTypeFunctions;
|
||||
}
|
||||
};
|
||||
static AccessTypeFunctionInterface accessTypeFunctions;
|
||||
|
||||
|
||||
@@ -372,6 +408,8 @@ STATIC_INITIALIZER_BEGIN
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
|
||||
//! \~english Gets member value as PIByteArray
|
||||
//! \~russian Получает значение члена как PIByteArray
|
||||
inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) {
|
||||
if (!p || !class_name || !member_name) return PIByteArray();
|
||||
AccessValueFunction af = PICODEINFO::accessValueFunctions().value(class_name, (AccessValueFunction)0);
|
||||
@@ -379,6 +417,8 @@ inline PIByteArray getMemberValue(const void * p, const char * class_name, const
|
||||
return af(p, member_name);
|
||||
}
|
||||
|
||||
//! \~english Gets member type as string
|
||||
//! \~russian Получает тип члена как строку
|
||||
inline const char * getMemberType(const char * class_name, const char * member_name) {
|
||||
if (!class_name || !member_name) return "";
|
||||
AccessTypeFunction af = PICODEINFO::accessTypeFunctions().value(class_name, (AccessTypeFunction)0);
|
||||
@@ -386,14 +426,20 @@ inline const char * getMemberType(const char * class_name, const char * member_n
|
||||
return af(member_name);
|
||||
}
|
||||
|
||||
//! \~english Gets member value as PIVariant
|
||||
//! \~russian Получает значение члена как PIVariant
|
||||
PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
|
||||
|
||||
|
||||
//! \~english Serializes value to PIByteArray (for assignable types)
|
||||
//! \~russian Сериализует значение в PIByteArray (для назначаемых типов)
|
||||
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;
|
||||
}
|
||||
|
||||
//! \~english Empty serialization (for non-assignable types)
|
||||
//! \~russian Пустая сериализация (для неназначаемых типов)
|
||||
template<typename T, typename std::enable_if<!std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||
void serialize(PIByteArray & ret, const T & v) {}
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/*! \file picodeparser.h
|
||||
* \ingroup Code
|
||||
* \~\brief
|
||||
* \addtogroup Code
|
||||
* \{
|
||||
* \~
|
||||
* \brief
|
||||
* \~english C++ code parser
|
||||
* \~russian Разбор C++ кода
|
||||
* \details
|
||||
* \~english Parser for analyzing C++ source files. Extracts information about classes, structures, enums, macros, functions, and members.
|
||||
* \~russian Парсер для анализа C++ исходных файлов. Извлекает информацию о классах, структурах, перечислениях, макросах, функциях и членах.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -39,6 +44,8 @@ inline bool _isCChar(const PIString & c) {
|
||||
|
||||
class PIP_EXPORT PICodeParser {
|
||||
public:
|
||||
//! \~english Default constructor.
|
||||
//! \~russian Конструктор по умолчанию.
|
||||
PICodeParser();
|
||||
|
||||
enum Visibility {
|
||||
@@ -63,18 +70,27 @@ public:
|
||||
typedef PIPair<PIString, PIString> Typedef;
|
||||
typedef PIMap<PIString, PIString> MetaMap;
|
||||
|
||||
//! \~english Represents a preprocessor macro.
|
||||
//! \~russian Представляет препроцессорный макрос.
|
||||
struct PIP_EXPORT Macro {
|
||||
Macro(const PIString & n = PIString(), const PIString & v = PIString(), const PIStringList & a = PIStringList()) {
|
||||
name = n;
|
||||
value = v;
|
||||
args = a;
|
||||
}
|
||||
//! \~english Expand macro with given arguments.
|
||||
//! \~russian Раскрыть макрос с заданными аргументами.
|
||||
//! \param args_ Arguments string
|
||||
//! \param ok Output flag indicating success
|
||||
//! \return Expanded macro value
|
||||
PIString expand(PIString args_, bool * ok = 0) const;
|
||||
PIString name;
|
||||
PIString value;
|
||||
PIStringList args;
|
||||
};
|
||||
|
||||
//! \~english Represents a class/struct member variable or function.
|
||||
//! \~russian Представляет переменную-член или функцию класса/структуры.
|
||||
struct PIP_EXPORT Member {
|
||||
Member() {
|
||||
visibility = Global;
|
||||
@@ -83,6 +99,8 @@ public:
|
||||
is_type_ptr = false;
|
||||
attributes = NoAttributes;
|
||||
}
|
||||
//! \~english Check if member is a bitfield.
|
||||
//! \~russian Проверить, является ли член битовым полем.
|
||||
bool isBitfield() const { return bits > 0; }
|
||||
MetaMap meta;
|
||||
PIString type;
|
||||
@@ -97,6 +115,8 @@ public:
|
||||
int bits;
|
||||
};
|
||||
|
||||
//! \~english Represents a parsed entity (class, struct, namespace, etc.).
|
||||
//! \~russian Представляет разобранную сущность (класс, структуру, пространство имен и т.д.).
|
||||
struct PIP_EXPORT Entity {
|
||||
Entity() {
|
||||
visibility = Global;
|
||||
@@ -118,6 +138,8 @@ public:
|
||||
PIVector<Typedef> typedefs;
|
||||
};
|
||||
|
||||
//! \~english Represents an enumerator value.
|
||||
//! \~russian Представляет значение перечисления.
|
||||
struct PIP_EXPORT EnumeratorInfo {
|
||||
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {
|
||||
name = n;
|
||||
@@ -129,6 +151,8 @@ public:
|
||||
int value;
|
||||
};
|
||||
|
||||
//! \~english Represents a parsed enum type.
|
||||
//! \~russian Представляет разобранный тип перечисления.
|
||||
struct PIP_EXPORT Enum {
|
||||
Enum(const PIString & n = PIString()) { name = n; }
|
||||
MetaMap meta;
|
||||
@@ -136,25 +160,89 @@ public:
|
||||
PIVector<EnumeratorInfo> members;
|
||||
};
|
||||
|
||||
//! \~english Parse C++ source file.
|
||||
//! \~russian Разбор C++ исходного файла.
|
||||
//! \param file Path to source file
|
||||
//! \param follow_includes Whether to follow include directives
|
||||
void parseFile(const PIString & file, bool follow_includes = true);
|
||||
|
||||
//! \~english Parse multiple C++ source files.
|
||||
//! \~russian Разбор нескольких C++ исходных файлов.
|
||||
//! \param files List of file paths
|
||||
//! \param follow_includes Whether to follow include directives
|
||||
void parseFiles(const PIStringList & files, bool follow_includes = true);
|
||||
|
||||
//! \~english Parse C++ source from string content.
|
||||
//! \~russian Разбор C++ исходного кода из строки.
|
||||
//! \param fc Source code content
|
||||
void parseFileContent(PIString fc);
|
||||
|
||||
//! \~english Add directory to search for include files.
|
||||
//! \~russian Добавить директорию для поиска включаемых файлов.
|
||||
//! \param dir Directory path
|
||||
void includeDirectory(const PIString & dir) { includes << dir; }
|
||||
|
||||
//! \~english Add custom macro definition.
|
||||
//! \~russian Добавить пользовательское определение макроса.
|
||||
//! \param def_name Macro name
|
||||
//! \param def_value Macro value
|
||||
void addDefine(const PIString & def_name, const PIString & def_value) { custom_defines << Define(def_name, def_value); }
|
||||
|
||||
//! \~english Check if name refers to an enum type.
|
||||
//! \~russian Проверить, является ли имя типом перечисления.
|
||||
//! \param name Name to check
|
||||
//! \return true if name is an enum
|
||||
bool isEnum(const PIString & name);
|
||||
|
||||
//! \~english Find entity by name.
|
||||
//! \~russian Найти сущность по имени.
|
||||
//! \param en Entity name
|
||||
//! \return Pointer to entity or nullptr
|
||||
Entity * findEntityByName(const PIString & en);
|
||||
|
||||
//! \~english Get list of parsed files.
|
||||
//! \~russian Получить список разобранных файлов.
|
||||
//! \return List of file paths
|
||||
PIStringList parsedFiles() const { return PIStringList(proc_files.toVector()); }
|
||||
|
||||
//! \~english Get main file path.
|
||||
//! \~russian Получить путь к главному файлу.
|
||||
//! \return Main file path
|
||||
PIString mainFile() const { return main_file; }
|
||||
|
||||
//! \~english Get global scope entity.
|
||||
//! \~russian Получить сущность глобальной области видимости.
|
||||
//! \return Pointer to global entity
|
||||
const PICodeParser::Entity * global() const { return &root_; }
|
||||
|
||||
//! \~english Get maximum iterations for macros substitution.
|
||||
//! \~russian Получить максимальное количество итераций для подстановки макросов.
|
||||
//! \return Maximum iterations count
|
||||
int macrosSubstitutionMaxIterations() const { return macros_iter; }
|
||||
|
||||
//! \~english Set maximum iterations for macros substitution.
|
||||
//! \~russian Установить максимальное количество итераций для подстановки макросов.
|
||||
//! \param value Maximum iterations count
|
||||
void setMacrosSubstitutionMaxIterations(int value) { macros_iter = value; }
|
||||
|
||||
//! \~english List of defined macros.
|
||||
//! \~russian Список определенных макросов.
|
||||
PIVector<Define> defines, custom_defines;
|
||||
|
||||
//! \~english List of macro definitions with expansion.
|
||||
//! \~russian Список определений макросов с подстановкой.
|
||||
PIVector<Macro> macros;
|
||||
|
||||
//! \~english List of enumerated types.
|
||||
//! \~russian Список типов перечислений.
|
||||
PIVector<Enum> enums;
|
||||
|
||||
//! \~english List of type definitions.
|
||||
//! \~russian Список определений типов.
|
||||
PIVector<Typedef> typedefs;
|
||||
|
||||
//! \~english List of parsed entities (classes, structs, etc.).
|
||||
//! \~russian Список разобранных сущностей (классов, структур и т.д.).
|
||||
PIVector<Entity *> entities;
|
||||
|
||||
private:
|
||||
@@ -195,4 +283,7 @@ private:
|
||||
PIMap<PIString, MetaMap> tmp_meta;
|
||||
};
|
||||
|
||||
/*! \}
|
||||
*/
|
||||
|
||||
#endif // PICODEPARSER_H
|
||||
|
||||
@@ -177,13 +177,29 @@ public:
|
||||
//! Returns exit key, default 'Q'
|
||||
int exitKey() const { return exit_key; }
|
||||
|
||||
//! \brief
|
||||
//! \~english Returns double click interval in seconds
|
||||
//! \~russian Возвращает интервал двойного клика в секундах
|
||||
double doubleClickInterval() const { return dbl_interval; }
|
||||
|
||||
//! \brief
|
||||
//! \~english Sets double click interval
|
||||
//! \~russian Устанавливает интервал двойного клика
|
||||
void setDoubleClickInterval(double v) { dbl_interval = v; }
|
||||
|
||||
//! \brief
|
||||
//! \~english Reads keyboard input
|
||||
//! \~russian Читает ввод с клавиатуры
|
||||
void readKeyboard();
|
||||
|
||||
//! \brief
|
||||
//! \~english Stops keyboard listening
|
||||
//! \~russian Останавливает прослушивание клавиатуры
|
||||
void stop();
|
||||
|
||||
//! \brief
|
||||
//! \~english Stops and waits for completion
|
||||
//! \~russian Останавливает и ожидает завершения
|
||||
bool stopAndWait(PISystemTime timeout = {});
|
||||
|
||||
//! Returns if keyboard listening is active (not running!)
|
||||
|
||||
@@ -33,6 +33,9 @@
|
||||
#include "piscreentile.h"
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Console tiling manager
|
||||
//! \~russian Консольный тайловый менеджер
|
||||
class PIP_CONSOLE_EXPORT PIScreen
|
||||
: public PIThread
|
||||
, public PIScreenTypes::PIScreenBase {
|
||||
|
||||
@@ -38,13 +38,19 @@
|
||||
//! \~english Tile for displaying variable data
|
||||
//! \~russian Тайл для отображения данных переменных
|
||||
|
||||
//! \addtogroup Console
|
||||
//! \{
|
||||
|
||||
//! \brief
|
||||
//! \~english Tile for displaying variable data
|
||||
//! \~russian Тайл для отображения данных переменных
|
||||
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
|
||||
public:
|
||||
//! \brief
|
||||
//! \~english Constructs TileVars
|
||||
//! \~russian Создает TileVars
|
||||
//! \param n Tile name / Имя тайла
|
||||
TileVars(const PIString & n = PIString());
|
||||
explicit TileVars(const PIString & n = PIString());
|
||||
|
||||
protected:
|
||||
//! \brief Variable data structure
|
||||
@@ -105,12 +111,15 @@ protected:
|
||||
//! \~english Console-style tile for PIScreen
|
||||
//! \~russian Консольный тайл для PIScreen
|
||||
|
||||
//! \brief
|
||||
//! \~english Console-style tile for PIScreen
|
||||
//! \~russian Консольный тайл для PIScreen
|
||||
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
|
||||
public:
|
||||
//! \brief
|
||||
//! \~english Constructs PIScreenConsoleTile
|
||||
//! \~russian Создает PIScreenConsoleTile
|
||||
PIScreenConsoleTile();
|
||||
explicit PIScreenConsoleTile();
|
||||
};
|
||||
|
||||
#endif // PISCREENCONSOLE_H
|
||||
|
||||
@@ -36,6 +36,9 @@
|
||||
//! \~english Console screen drawer for rendering graphics
|
||||
//! \~russian Отрисовщик консольного экрана для рендеринга графики
|
||||
|
||||
//! \brief
|
||||
//! \~english Console screen drawer for rendering graphics
|
||||
//! \~russian Отрисовщик консольного экрана для рендеринга графики
|
||||
class PIP_CONSOLE_EXPORT PIScreenDrawer {
|
||||
friend class PIScreen;
|
||||
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
|
||||
|
||||
@@ -38,6 +38,9 @@ class PIScreenDrawer;
|
||||
//! \~english Base tile class for console screen
|
||||
//! \~russian Базовый класс тайла для консольного экрана
|
||||
|
||||
//! \brief
|
||||
//! \~english Base tile class for console screen
|
||||
//! \~russian Базовый класс тайла для консольного экрана
|
||||
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
|
||||
friend class PIScreen;
|
||||
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
|
||||
|
||||
@@ -465,6 +465,9 @@ protected:
|
||||
//! \~english Tile for displaying console output
|
||||
//! \~russian Тайл для отображения консольного вывода
|
||||
|
||||
//! \brief
|
||||
//! \~english Tile for displaying console output
|
||||
//! \~russian Тайл для отображения консольного вывода
|
||||
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
|
||||
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
|
||||
|
||||
@@ -503,6 +506,9 @@ protected:
|
||||
//! \~english Text input tile
|
||||
//! \~russian Тайл текстового ввода
|
||||
|
||||
//! \brief
|
||||
//! \~english Text input tile
|
||||
//! \~russian Тайл текстового ввода
|
||||
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
|
||||
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
|
||||
|
||||
|
||||
@@ -33,6 +33,9 @@
|
||||
#include "piscreentypes.h"
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Virtual terminal
|
||||
//! \~russian Виртуальный терминал
|
||||
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
|
||||
PIOBJECT_SUBCLASS(PITerminal, PIThread);
|
||||
|
||||
|
||||
@@ -49,14 +49,28 @@
|
||||
#include <type_traits>
|
||||
|
||||
|
||||
//! \~english Reverse wrapper template class for iterating containers in reverse order.
|
||||
//! \~russian Класс-обертка для обратного обхода контейнера через итераторы.
|
||||
template<typename C>
|
||||
class _PIReverseWrapper {
|
||||
public:
|
||||
//! \~english Constructor from non-const container reference.
|
||||
//! \~russian Конструктор из неконстантной ссылки на контейнер.
|
||||
_PIReverseWrapper(C & c): c_(c) {}
|
||||
//! \~english Constructor from const container reference.
|
||||
//! \~russian Конструктор из константной ссылки на контейнер.
|
||||
_PIReverseWrapper(const C & c): c_(const_cast<C &>(c)) {}
|
||||
//! \~english Returns reverse iterator to the first element.
|
||||
//! \~russian Возвращает обратный итератор на первый элемент.
|
||||
typename C::reverse_iterator begin() { return c_.rbegin(); }
|
||||
//! \~english Returns reverse iterator past the last element.
|
||||
//! \~russian Возвращает обратный итератор за последний элемент.
|
||||
typename C::reverse_iterator end() { return c_.rend(); }
|
||||
//! \~english Returns const reverse iterator to the first element.
|
||||
//! \~russian Возвращает константный обратный итератор на первый элемент.
|
||||
typename C::const_reverse_iterator begin() const { return c_.rbegin(); }
|
||||
//! \~english Returns const reverse iterator past the last element.
|
||||
//! \~russian Возвращает константный обратный итератор за последний элемент.
|
||||
typename C::const_reverse_iterator end() const { return c_.rend(); }
|
||||
|
||||
private:
|
||||
@@ -64,32 +78,47 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Base class for container constants calculation.
|
||||
//! \~russian Базовый класс для вычисления констант контейнера.
|
||||
class PIP_EXPORT _PIContainerConstantsBase {
|
||||
public:
|
||||
//! \~english Calculate minimum elements count for power of two growth.
|
||||
//! \~russian Вычисляет минимальное количество элементов для роста кратного двум.
|
||||
static size_t calcMinCountPoT(size_t szof);
|
||||
//! \~english Calculate maximum elements count for power of two growth.
|
||||
//! \~russian Вычисляет максимальное количество элементов для роста кратного двум.
|
||||
static size_t calcMaxCountForPoT(size_t szof);
|
||||
//! \~english Calculate step size after power of two growth.
|
||||
//! \~russian Вычисляет размер шага после роста кратного двум.
|
||||
static size_t calcStepAfterPoT(size_t szof);
|
||||
};
|
||||
|
||||
//! \~english Template class for container constants based on element type size.
|
||||
//! \~russian Шаблонный класс для констант контейнера на основе размера типа элемента.
|
||||
template<typename T>
|
||||
class _PIContainerConstants {
|
||||
public:
|
||||
// minimum elements for container
|
||||
//! \~english Get minimum elements count for power of two growth.
|
||||
//! \~russian Возвращает минимальное количество элементов для роста кратного двум.
|
||||
static size_t minCountPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
// maximum elements for 2^n growth
|
||||
//! \~english Get maximum elements count for power of two growth.
|
||||
//! \~russian Возвращает максимальное количество элементов для роста кратного двум.
|
||||
static size_t maxCountForPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcMaxCountForPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
// add elements after 2^n growth
|
||||
//! \~english Get step size after power of two growth.
|
||||
//! \~russian Возвращает размер шага после роста кратного двум.
|
||||
static size_t stepAfterPoT() {
|
||||
static const size_t ret = _PIContainerConstantsBase::calcStepAfterPoT(sizeof(T));
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Calculate new container size based on old and requested size.
|
||||
//! \~russian Вычисляет новый размер контейнера на основе старого и запрошенного размера.
|
||||
static size_t calcNewSize(size_t old_size, size_t new_size) {
|
||||
if (new_size == 0) return 0;
|
||||
if (new_size < maxCountForPoT()) {
|
||||
|
||||
@@ -87,27 +87,27 @@
|
||||
#else
|
||||
|
||||
# define ADD_TO_COLLECTION(group, object) \
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, object, "", false);
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, object, "", false);
|
||||
|
||||
# define ADD_TO_COLLECTION_WITH_NAME(group, object, name) \
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, object, #name, false);
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, object, #name, false);
|
||||
|
||||
# define ADD_NEW_TO_COLLECTION(group, class) \
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, new class(), "", true);
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, new class(), "", true);
|
||||
|
||||
# define ADD_NEW_TO_COLLECTION_WITH_NAME(group, class, name) \
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, new class(), #name, true);
|
||||
static PICollection::CollectionAdder _PIP_ADD_COUNTER(_collection_adder_)(#group, new class(), #name, true);
|
||||
|
||||
#endif
|
||||
|
||||
//! \ingroup Core
|
||||
//! \~\brief
|
||||
//! \~english Helper to collect and retrieve classes to groups.
|
||||
//! \~russian Помощник для создания и получения классов в группы.
|
||||
/// \~english Helper to collect and retrieve classes to groups.
|
||||
/// \~russian Помощник для создания и получения классов в группы.
|
||||
class PIP_EXPORT PICollection {
|
||||
friend class __PICollectionInitializer;
|
||||
|
||||
public:
|
||||
//! \~english Default constructor
|
||||
//! \~russian Конструктор по умолчанию
|
||||
PICollection() { ; }
|
||||
|
||||
//! \~english Returns all existing groups by their names
|
||||
@@ -118,10 +118,14 @@ public:
|
||||
//! \~russian Возвращает все элементы группы "group"
|
||||
static PIVector<const PIObject *> groupElements(const PIString & group);
|
||||
|
||||
//! \~english Add element "element" to group "group"
|
||||
//! \~russian Добавляет элемент "element" в группу "group"
|
||||
static bool addToGroup(const PIString & group, const PIObject * element);
|
||||
|
||||
class PIP_EXPORT CollectionAdder {
|
||||
public:
|
||||
//! \~english Constructor that adds element to group
|
||||
//! \~russian Конструктор, который добавляет элемент в группу
|
||||
CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false);
|
||||
};
|
||||
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
/*! \file piinit.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Library initialization
|
||||
* \~russian Инициализация библиотеки
|
||||
*/
|
||||
/*
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \file piinit.h
|
||||
//! \brief
|
||||
//! \~english Library initialization
|
||||
//! \~russian Инициализация библиотеки
|
||||
//! \details
|
||||
//! \~english This file provides initialization and build information for the PIP library.
|
||||
//! \~russian Этот файл предоставляет инициализацию и информацию о сборке для библиотеки PIP.
|
||||
/*!
|
||||
PIP - Platform Independent Primitives
|
||||
Initialization
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
@@ -37,6 +40,8 @@ class PIFile;
|
||||
class PIStringList;
|
||||
|
||||
|
||||
//! \~english Internal initializer class for automatic library initialization
|
||||
//! \~russian Внутренний класс инициализации для автоматической инициализации библиотеки
|
||||
class PIP_EXPORT __PIInit_Initializer__ {
|
||||
public:
|
||||
__PIInit_Initializer__();
|
||||
@@ -48,6 +53,8 @@ public:
|
||||
static __PIInit_Initializer__ __piinit_initializer__;
|
||||
|
||||
|
||||
//! \~english Provides library initialization and build information
|
||||
//! \~russian Предоставляет инициализацию библиотеки и информацию о сборке
|
||||
class PIP_EXPORT PIInit {
|
||||
friend class __PIInit_Initializer__;
|
||||
friend class PIFile;
|
||||
@@ -69,6 +76,8 @@ public:
|
||||
boCloud /*! \~english PICloud transport support \~russian Поддержка облачного транспорта PICloud */ = 0x200,
|
||||
boConsole /*! \~english Console graphics support \~russian Поддержка графики в консоли */ = 0x400,
|
||||
};
|
||||
//! \~english Returns singleton instance of PIInit
|
||||
//! \~russian Возвращает синглтон экземпляр PIInit
|
||||
static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
|
||||
|
||||
//! \ingroup Core
|
||||
@@ -89,4 +98,5 @@ private:
|
||||
|
||||
|
||||
#endif // MICRO_PIP
|
||||
//! \}
|
||||
#endif // PIINIT_H
|
||||
|
||||
@@ -175,6 +175,8 @@ public:
|
||||
bool isPropertyExists(const char * name) const { return properties_.contains(piHashData((const uchar *)name, strlen(name))); }
|
||||
|
||||
void setThreadSafe(bool yes) { thread_safe_ = yes; }
|
||||
//! \~english Returns if object is thread safe
|
||||
//! \~russian Возвращает является ли объект потокобезопасным
|
||||
bool isThreadSafe() const { return thread_safe_; }
|
||||
|
||||
bool execute(const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||
@@ -279,10 +281,20 @@ public:
|
||||
//! \~russian Возвращает цепочку наследования объекта (вместе с классом самого объекта)
|
||||
PIStringList scopeList() const;
|
||||
|
||||
//! \~english Returns list of all event-handler methods
|
||||
//! \~russian Возвращает список всех методов-обработчиков событий
|
||||
PIStringList methodsEH() const;
|
||||
//! \~english Returns if method "name" is event-handler
|
||||
//! \~russian Возвращает является ли метод "name" обработчиком событий
|
||||
bool isMethodEHContains(const PIString & name) const;
|
||||
//! \~english Returns arguments of event-handler method "name"
|
||||
//! \~russian Возвращает аргументы метода-обработчика событий "name"
|
||||
PIString methodEHArguments(const PIString & name) const;
|
||||
//! \~english Returns full format of event-handler method "name"
|
||||
//! \~russian Возвращает полный формат метода-обработчика событий "name"
|
||||
PIString methodEHFullFormat(const PIString & name) const;
|
||||
//! \~english Returns event-handler method name from address "addr"
|
||||
//! \~russian Возвращает имя метода-обработчика событий по адресу "addr"
|
||||
PIString methodEHFromAddr(const void * addr) const;
|
||||
|
||||
// / Direct connect
|
||||
@@ -542,6 +554,8 @@ public:
|
||||
//! \~english Returns if "o" is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли "o" %PIObject (проверяет подпись)
|
||||
static bool isPIObject(const PIObject * o);
|
||||
//! \~english Returns if "o" is valid %PIObject (check signature)
|
||||
//! \~russian Возвращает действительный ли "o" %PIObject (проверяет подпись)
|
||||
static bool isPIObject(const void * o) { return isPIObject((PIObject *)o); }
|
||||
|
||||
//! \~english Returns if "o" is valid %PIObject subclass "T" (check signature and classname)
|
||||
@@ -554,6 +568,8 @@ public:
|
||||
static bool isTypeOf(const void * o) {
|
||||
return isTypeOf<T>((PIObject *)o);
|
||||
}
|
||||
//! \~english Simplifies type name "a" to readable format
|
||||
//! \~russian Упрощает имя типа "a" в читаемый формат
|
||||
static PIString simplifyType(const char * a, bool readable = true);
|
||||
|
||||
struct PIP_EXPORT __MetaFunc {
|
||||
|
||||
@@ -1,8 +1,12 @@
|
||||
/*! \file piauth.h
|
||||
* \ingroup Crypt
|
||||
* \~\brief
|
||||
* \~english Authentication API
|
||||
* \~russian API аутентификации
|
||||
* \addtogroup Crypt
|
||||
* \{
|
||||
* \brief Authentication API
|
||||
* \~english Authentication API for client-server key exchange and authentication
|
||||
* \~russian API аутентификации для обмена ключами и аутентификации клиент-сервер
|
||||
* \details
|
||||
* \~english Provides classes for secure client-server authentication with digital signatures, password verification, and key exchange
|
||||
* \~russian Предоставляет классы для безопасной клиент-серверной аутентификации с цифровыми подписями, проверкой пароля и обменом ключами
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -31,70 +35,106 @@
|
||||
#include "pip_crypt_export.h"
|
||||
|
||||
|
||||
//! \~english Authentication and key exchange class
|
||||
//! \~russian Класс аутентификации и обмена ключами
|
||||
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
|
||||
PIOBJECT(PIAuth)
|
||||
|
||||
public:
|
||||
//! \~english Authentication state
|
||||
//! \~russian Состояние аутентификации
|
||||
enum State {
|
||||
NotConnected,
|
||||
AuthProbe,
|
||||
PassRequest,
|
||||
AuthReply,
|
||||
KeyExchange,
|
||||
Connected
|
||||
NotConnected, //!< \~english Not connected \~russian Не подключен
|
||||
AuthProbe, //!< \~english Authentication probe \~russian Зондирование аутентификации
|
||||
PassRequest, //!< \~english Password request \~russian Запрос пароля
|
||||
AuthReply, //!< \~english Authentication reply \~russian Ответ аутентификации
|
||||
KeyExchange, //!< \~english Key exchange \~russian Обмен ключами
|
||||
Connected //!< \~english Connected, authenticated \~russian Подключено, аутентифицировано
|
||||
};
|
||||
|
||||
//! Create PIAuth with your digital sign
|
||||
//! \~english Create PIAuth with your digital sign
|
||||
//! \~russian Создать PIAuth с вашей цифровой подписью
|
||||
//! \param sign \~english Digital sign private key \~russian Приватный ключ цифровой подписи
|
||||
PIAuth(const PIByteArray & sign);
|
||||
|
||||
//! Set server info data for client authorize event
|
||||
//! \~english Set server info data for client authorize event
|
||||
//! \~russian Установить информационные данные сервера для события авторизации клиента
|
||||
//! \param info \~english Info data \~russian Информационные данные
|
||||
void setInfoData(const PIByteArray & info) { custom_info = info; }
|
||||
|
||||
//! Set server password for check
|
||||
//! \~english Set server password for check
|
||||
//! \~russian Установить пароль сервера для проверки
|
||||
//! \param ps \~english Server password \~russian Пароль сервера
|
||||
void setServerPassword(const PIString & ps);
|
||||
|
||||
//! Set list of trusted clients/servers public digital sign keys
|
||||
//! \~english Set list of trusted clients/servers public digital sign keys
|
||||
//! \~russian Установить список доверенных публичных ключей цифровой подписи клиентов/серверов
|
||||
//! \param pkeys \~english List of public keys \~russian Список публичных ключей
|
||||
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
|
||||
|
||||
//! Get list of trusted clients/servers public digital sign keys
|
||||
//! \~english Get list of trusted clients/servers public digital sign keys
|
||||
//! \~russian Получить список доверенных публичных ключей цифровой подписи клиентов/серверов
|
||||
//! \return \~english List of public keys \~russian Список публичных ключей
|
||||
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
|
||||
|
||||
//! Get your digital sign public key
|
||||
//! \~english Get your digital sign public key
|
||||
//! \~russian Получить ваш публичный ключ цифровой подписи
|
||||
//! \return Public sign key \~english Публичный ключ подписи
|
||||
PIByteArray getSignPublicKey() { return sign_pk; }
|
||||
|
||||
|
||||
//! Stop authorization
|
||||
//! \~english Stop authorization
|
||||
//! \~russian Остановить авторизацию
|
||||
void stop();
|
||||
|
||||
//! Start authorization as client
|
||||
//! \~english Start authorization as client
|
||||
//! \~russian Начать авторизацию как клиент
|
||||
void startClient();
|
||||
|
||||
//! Start authorization as server, return first server message for client
|
||||
//! \~english Start authorization as server, return first server message for client
|
||||
//! \~russian Начать авторизацию как сервер, вернуть первое сообщение сервера для клиента
|
||||
//! \return \~english First server message \~russian Первое сообщение сервера
|
||||
PIByteArray startServer();
|
||||
|
||||
//! Process reseived message both for client and server, return current state and new message writed in "ba"
|
||||
//! \~english Process received message both for client and server, return current state and new message written in "ba"
|
||||
//! \~russian Обработать полученное сообщение как для клиента, так и для сервера, вернуть текущее состояние и новое сообщение в "ba"
|
||||
//! \param ba \~english Message to process, output message \~russian Сообщение для обработки, выходное сообщение
|
||||
//! \return \~english Current authentication state \~russian Текущее состояние аутентификации
|
||||
State receive(PIByteArray & ba);
|
||||
|
||||
//! Get session secret key, return key only when Connected state
|
||||
//! \~english Get session secret key, return key only when Connected state
|
||||
//! \~russian Получить секретный ключ сессии, вернуть ключ только в состоянии Connected
|
||||
//! \return \~english Session secret key \~russian Секретный ключ сессии
|
||||
//! \note
|
||||
//! \~english Returns empty array if not connected
|
||||
//! \~russian Возвращает пустой массив если не подключен
|
||||
PIByteArray getSecretKey();
|
||||
|
||||
//! Generate digital sign from seed
|
||||
//! \~english Generate digital sign from seed
|
||||
//! \~russian Сгенерировать цифровую подпись из зерна
|
||||
//! \param seed \~english Seed for key generation \~russian Зерно для генерации ключа
|
||||
//! \return \~english Generated digital sign key \~russian Сгенерированный ключ цифровой подписи
|
||||
static PIByteArray generateSign(const PIByteArray & seed);
|
||||
|
||||
|
||||
//! Disconneted event
|
||||
//! \~english Disconnected event
|
||||
//! \~russian Событие отключения
|
||||
EVENT1(disconnected, PIString, reason);
|
||||
|
||||
//! Conneted event
|
||||
//! \~english Connected event
|
||||
//! \~russian Событие подключения
|
||||
EVENT1(connected, PIString, info);
|
||||
|
||||
//! Client event for authorize new server
|
||||
//! \~english Client event for authorize new server
|
||||
//! \~russian Событие клиента для авторизации нового сервера
|
||||
EVENT2(authorize, PIByteArray, info, bool *, ok);
|
||||
|
||||
//! Client event for input server password
|
||||
//! \~english Client event for input server password
|
||||
//! \~russian Событие клиента для ввода пароля сервера
|
||||
EVENT1(passwordRequest, PIString *, pass);
|
||||
|
||||
//! Server event on check client password
|
||||
//! \~english Server event on check client password
|
||||
//! \~russian Событие сервера при проверке пароля клиента
|
||||
EVENT1(passwordCheck, bool, result);
|
||||
|
||||
private:
|
||||
|
||||
@@ -40,6 +40,9 @@ public:
|
||||
//! \~russian Конструктор, генерирующий случайный ключ
|
||||
PICrypt();
|
||||
|
||||
//! \~\brief
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PICrypt();
|
||||
|
||||
//! \~\brief
|
||||
|
||||
@@ -1,32 +1,33 @@
|
||||
/*! \file pidigest.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Digest algorithms
|
||||
* \~russian Алгоритмы хэш-сумм
|
||||
*
|
||||
* \~\details
|
||||
* \~english
|
||||
* This file implements several common-usage hash algorithms
|
||||
* \~russian
|
||||
* Этот файл реализует несколько распространенных алгоритмов хэширования
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{
|
||||
//! \file pidigest.h
|
||||
//! \brief
|
||||
//! \~english Digest algorithms
|
||||
//! \~russian Алгоритмы хэш-сумм
|
||||
//!
|
||||
//! \details
|
||||
//! \~english
|
||||
//! This file implements several common-usage hash algorithms
|
||||
//! \~russian
|
||||
//! Этот файл реализует несколько распространенных алгоритмов хэширования
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Digest algorithms
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
PIP - Platform Independent Primitives
|
||||
Digest algorithms
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
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/>.
|
||||
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/>.
|
||||
*/
|
||||
|
||||
#ifndef pidigest_h
|
||||
@@ -37,6 +38,15 @@
|
||||
|
||||
class PIP_EXPORT PIDigest {
|
||||
public:
|
||||
//! \~english Hash algorithm type
|
||||
//! \~russian Тип алгоритма хэширования
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Supported algorithms: SHA1, SHA2 family (224, 256, 384, 512, 512_224, 512_256),
|
||||
//! MD2, MD4, MD5, BLAKE2s, BLAKE2b, SipHash
|
||||
//! \~russian
|
||||
//! Поддерживаемые алгоритмы: SHA1, семейство SHA2 (224, 256, 384, 512, 512_224, 512_256),
|
||||
//! MD2, MD4, MD5, BLAKE2s, BLAKE2b, SipHash
|
||||
enum class Type {
|
||||
SHA1,
|
||||
|
||||
@@ -70,13 +80,45 @@ public:
|
||||
Count,
|
||||
};
|
||||
|
||||
//! \~english Get hash output length in bytes
|
||||
//! \~russian Получить длину хэша в байтах
|
||||
static int hashLength(Type type);
|
||||
//! \~english Get hash block length in bytes
|
||||
//! \~russian Получить длину блока хэширования в байтах
|
||||
static int blockLength(Type type);
|
||||
//! \~english Get algorithm name as string
|
||||
//! \~russian Получить название алгоритма в виде строки
|
||||
//! \return Algorithm name
|
||||
//! \sa Type
|
||||
static PIConstChars typeName(Type type);
|
||||
|
||||
//! \~english Calculate hash of message
|
||||
//! \~russian Вычислить хэш сообщения
|
||||
//! \param msg Input message
|
||||
//! \param type Hash algorithm type
|
||||
//! \return Hash bytes
|
||||
//! \sa calculateWithKey, HMAC
|
||||
static PIByteArray calculate(const PIByteArray & msg, Type type);
|
||||
//! \~english Calculate keyed hash of message
|
||||
//! \~russian Вычислить ключевой хэш сообщения
|
||||
//! \param msg Input message
|
||||
//! \param key Secret key
|
||||
//! \param type Hash algorithm type (SipHash or BLAKE2)
|
||||
//! \return Hash bytes
|
||||
//! \note Only SipHash and BLAKE2 algorithms support keyed hashing
|
||||
//! \sa calculate, HMAC
|
||||
static PIByteArray calculateWithKey(const PIByteArray & msg, const PIByteArray & key, Type type);
|
||||
//! \~english Calculate HMAC (Keyed-Hash Message Authentication Code)
|
||||
//! \~russian Вычислить HMAC (код аутентификации сообщений на основе ключа)
|
||||
//! \param msg Input message
|
||||
//! \param key Secret key
|
||||
//! \param type Hash algorithm type
|
||||
//! \return HMAC bytes
|
||||
//! \note Supports SHA1, SHA2 and MD5 algorithms
|
||||
//! \sa calculate, calculateWithKey
|
||||
static PIByteArray HMAC(const PIByteArray & msg, const PIByteArray & key, PIDigest::Type type);
|
||||
};
|
||||
|
||||
//! \}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -372,6 +372,8 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Subtraction
|
||||
//! \~russian Вычитание
|
||||
inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||
PIGeoPosition l(left), r(right);
|
||||
l.transformTo(PIGeoPosition::Cartesian);
|
||||
@@ -379,6 +381,8 @@ inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition &
|
||||
l -= r;
|
||||
return l;
|
||||
}
|
||||
//! \~english Addition
|
||||
//! \~russian Сложение
|
||||
inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||
PIGeoPosition l(left), r(right);
|
||||
l.transformTo(PIGeoPosition::Cartesian);
|
||||
@@ -386,17 +390,25 @@ inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition &
|
||||
l += r;
|
||||
return l;
|
||||
}
|
||||
//! \~english Scalar multiplication (double)
|
||||
//! \~russian Умножение на скаляр (double)
|
||||
inline PIGeoPosition operator*(const double & scale, const PIGeoPosition & right) {
|
||||
PIMathVectorT3d tmp(right);
|
||||
tmp *= scale;
|
||||
return PIGeoPosition(tmp);
|
||||
}
|
||||
//! \~english Scalar multiplication (double)
|
||||
//! \~russian Умножение на скаляр (double)
|
||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const double & scale) {
|
||||
return operator*(scale, left);
|
||||
}
|
||||
//! \~english Scalar multiplication (int)
|
||||
//! \~russian Умножение на скаляр (int)
|
||||
inline PIGeoPosition operator*(const int & scale, const PIGeoPosition & right) {
|
||||
return operator*(double(scale), right);
|
||||
}
|
||||
//! \~english Scalar multiplication (int)
|
||||
//! \~russian Умножение на скаляр (int)
|
||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const int & scale) {
|
||||
return operator*(double(scale), left);
|
||||
}
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \{
|
||||
//! \file pihttpclient.h
|
||||
//! \brief HTTP client implementation
|
||||
//! \~english HTTP client for performing asynchronous HTTP requests with callbacks
|
||||
//! \~russian HTTP клиент для выполнения асинхронных HTTP запросов с колбэками
|
||||
//! \details
|
||||
//! \~english Provides async HTTP client functionality using libcurl
|
||||
//! \~russian Обеспечивает функциональность асинхронного HTTP клиента с использованием libcurl
|
||||
//! \}
|
||||
|
||||
#ifndef pihttpclient_h
|
||||
#define pihttpclient_h
|
||||
|
||||
@@ -6,6 +17,8 @@
|
||||
#include "pistringlist.h"
|
||||
|
||||
|
||||
//! \~english Base class for HTTP client internal functionality
|
||||
//! \~russian Базовый класс для внутренней функциональности HTTP клиента
|
||||
class PIHTTPClientBase {
|
||||
public:
|
||||
int __infoFunc(ssize_t dltotal, ssize_t dlnow, ssize_t ultotal, ssize_t ulnow);
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \{
|
||||
//! \file pihttpconstants.h
|
||||
//! \brief HTTP constants and enumerations
|
||||
//! \~english Definitions for HTTP methods, status codes and header names
|
||||
//! \~russian Определения HTTP методов, кодов состояния и имен заголовков
|
||||
//! \details
|
||||
//! \~english Provides enum classes for HTTP methods and status codes, and a namespace with HTTP header name constants
|
||||
//! \~russian Предоставляет классы перечислений для HTTP методов и кодов состояния, а также пространство имён с константами имён HTTP
|
||||
//! заголовков
|
||||
//! \}
|
||||
|
||||
#ifndef pihttpconstants_h
|
||||
#define pihttpconstants_h
|
||||
|
||||
|
||||
namespace PIHTTP {
|
||||
|
||||
//! \~english HTTP request methods
|
||||
//! \~russian HTTP методы запросов
|
||||
enum class Method {
|
||||
Unknown,
|
||||
Get,
|
||||
@@ -17,6 +31,8 @@ enum class Method {
|
||||
Patch
|
||||
};
|
||||
|
||||
//! \~english HTTP response status codes
|
||||
//! \~russian Коды состояния HTTP ответа
|
||||
enum class Code {
|
||||
Unknown = -1,
|
||||
Continue = 100,
|
||||
@@ -90,6 +106,8 @@ enum class Code {
|
||||
NetworkAuthenticationRequired = 511,
|
||||
};
|
||||
|
||||
//! \~english HTTP header field names
|
||||
//! \~russian Имена полей заголовков HTTP
|
||||
namespace Header {
|
||||
constexpr static char Accept[] = "Accept";
|
||||
constexpr static char AcceptCharset[] = "Accept-Charset";
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \{
|
||||
//! \file pihttptypes.h
|
||||
//! \brief HTTP types and message classes
|
||||
//! \~english HTTP message types and containers for requests and responses
|
||||
//! \~russian Типы HTTP и классы сообщений для запросов и ответов
|
||||
//! \details
|
||||
//! \~english Provides MessageConst and MessageMutable classes for HTTP communication
|
||||
//! \~russian Предоставляет классы MessageConst и MessageMutable для HTTP коммуникации
|
||||
//! \}
|
||||
|
||||
#ifndef pihttptypes_h
|
||||
#define pihttptypes_h
|
||||
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \{
|
||||
//! \file microhttpd_server.h
|
||||
//! \brief Base HTTP server class
|
||||
//! \~english Base HTTP server class using libmicrohttpd
|
||||
//! \~russian Базовый класс HTTP сервера с использованием libmicrohttpd
|
||||
//! \details
|
||||
//! \~english Provides core HTTP server functionality with connection handling
|
||||
//! \~russian Обеспечивает базовую функциональность HTTP сервера с обработкой соединений
|
||||
//! \}
|
||||
|
||||
#ifndef MICROHTTPD_SERVER_P_H
|
||||
#define MICROHTTPD_SERVER_P_H
|
||||
|
||||
@@ -14,24 +25,28 @@ class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
|
||||
friend struct MicrohttpdServerConnection;
|
||||
|
||||
public:
|
||||
//! \~english Constructs a new MicroHTTP server
|
||||
//! \~russian Создает новый MicroHTTP сервер
|
||||
MicrohttpdServer();
|
||||
//! \~english Destroys the MicroHTTP server
|
||||
//! \~russian Уничтожает MicroHTTP сервер
|
||||
virtual ~MicrohttpdServer();
|
||||
|
||||
//! \~english Server configuration options
|
||||
//! \~russian Опции конфигурации сервера
|
||||
enum class Option {
|
||||
ConnectionLimit, //!< \~english Maximum concurrent connections
|
||||
//!< \~russian Максимальное количество соединений
|
||||
//!< \~russian Максимальное количество соединений
|
||||
ConnectionTimeout, //!< \~english Connection timeout in seconds
|
||||
//!< \~russian Таймаут соединения в секундах
|
||||
//!< \~russian Таймаут соединения в секундах
|
||||
HTTPSEnabled, //!< \~english Enable HTTPS support
|
||||
//!< \~russian Включить поддержку HTTPS
|
||||
//!< \~russian Включить поддержку HTTPS
|
||||
HTTPSMemKey, //!< \~english SSL key in memory (PIByteArray)
|
||||
//!< \~russian SSL ключ в памяти (PIByteArray)
|
||||
//!< \~russian SSL ключ в памяти (PIByteArray)
|
||||
HTTPSMemCert, //!< \~english SSL certificate in memory (PIByteArray)
|
||||
//!< \~russian SSL сертификат в памяти (PIByteArray)
|
||||
//!< \~russian SSL сертификат в памяти (PIByteArray)
|
||||
HTTPSKeyPassword //!< \~english SSL key password (PIByteArray)
|
||||
//!< \~russian Пароль SSL ключа (PIByteArray)
|
||||
//!< \~russian Пароль SSL ключа (PIByteArray)
|
||||
};
|
||||
|
||||
//! \~english Sets server option
|
||||
|
||||
@@ -1,3 +1,14 @@
|
||||
//! \addtogroup HTTP
|
||||
//! \{
|
||||
//! \file pihttpserver.h
|
||||
//! \brief High-level HTTP server implementation
|
||||
//! \~english High-level HTTP server with path-based routing and handler registration
|
||||
//! \~russian Высокоуровневый HTTP сервер с маршрутизацией по путям и регистрацией обработчиков
|
||||
//! \details
|
||||
//! \~english Provides path-based request routing and handler management
|
||||
//! \~russian Обеспечивает маршрутизацию запросов по путям и управление обработчиками
|
||||
//! \}
|
||||
|
||||
#ifndef PIHTTPSERVER_H
|
||||
#define PIHTTPSERVER_H
|
||||
|
||||
@@ -9,7 +20,11 @@ class PIP_HTTP_SERVER_EXPORT PIHTTPServer: public MicrohttpdServer {
|
||||
PIOBJECT_SUBCLASS(PIHTTPServer, MicrohttpdServer)
|
||||
|
||||
public:
|
||||
//! \~english Constructs a new HTTP server
|
||||
//! \~russian Создает новый HTTP сервер
|
||||
PIHTTPServer();
|
||||
//! \~english Destroys the HTTP server
|
||||
//! \~russian Уничтожает HTTP сервер
|
||||
virtual ~PIHTTPServer();
|
||||
|
||||
using RequestFunction = std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)>;
|
||||
|
||||
@@ -61,12 +61,17 @@ class PIIntrospection;
|
||||
class PIIntrospectionServer;
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
//! \~english Declare singleton interface for introspection module T
|
||||
//! \~russian Объявить интерфейс-синглтон для интроспекции модуля T
|
||||
# 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; \
|
||||
}
|
||||
//! \~english Implement singleton interface for introspection module T
|
||||
//! \~russian Реализовать интерфейс-синглтон для интроспекции модуля T
|
||||
# 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
|
||||
|
||||
@@ -3,44 +3,67 @@
|
||||
Introspection module - interface for containers
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU Lesser General Public License for more details.
|
||||
|
||||
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/>.
|
||||
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/>.
|
||||
*/
|
||||
//! \addtogroup Introspection
|
||||
//! \{
|
||||
//! \file piintrospection_containers.h
|
||||
//! \brief Container introspection
|
||||
//! \~english Interface for container introspection and memory tracking
|
||||
//! \~russian Интерфейс для интроспекции контейнеров и отслеживания памяти
|
||||
//! \details
|
||||
//! \~english Provides interface for tracking container memory allocations and usage
|
||||
//! \~russian Предоставляет интерфейс для отслеживания выделения и использования памяти контейнерами
|
||||
|
||||
#ifndef PIINTROSPECTION_CONTAINERS_H
|
||||
#define PIINTROSPECTION_CONTAINERS_H
|
||||
# define PIINTROSPECTION_CONTAINERS_H
|
||||
|
||||
#include "pibase.h"
|
||||
# include "pibase.h"
|
||||
|
||||
//! \~english Container type information structure
|
||||
//! \~russian Структура информации о типе контейнера
|
||||
struct PIP_EXPORT PIIntrospectionContainersType {
|
||||
~PIIntrospectionContainersType();
|
||||
void finish();
|
||||
//! \~english Type identifier
|
||||
//! \~russian Идентификатор типа
|
||||
uint id = 0;
|
||||
//! \~english Type name
|
||||
//! \~russian Имя типа
|
||||
const char * name = nullptr;
|
||||
//! \~english Demangled type name
|
||||
//! \~russian Демангл-имя типа
|
||||
const char * demangled = "?";
|
||||
//! \~english Initialization flag
|
||||
//! \~russian Флаг инициализации
|
||||
bool inited = false;
|
||||
//! \~english Has demangled name flag
|
||||
//! \~russian Флаг наличия demangled имени
|
||||
bool has_demangled = false;
|
||||
};
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
# if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
# include "piintrospection_base.h"
|
||||
|
||||
class PIIntrospectionContainers;
|
||||
# include "piintrospection_base.h"
|
||||
|
||||
//! \~english Container type information template
|
||||
//! \~russian Шаблон информации о типе контейнера
|
||||
template<typename T>
|
||||
class PIIntrospectionContainersTypeInfo {
|
||||
public:
|
||||
//! \~english Get container type information
|
||||
//! \~russian Получить информацию о типе контейнера
|
||||
static const PIIntrospectionContainersType & get() {
|
||||
static PIIntrospectionContainersType ret = create();
|
||||
return ret;
|
||||
@@ -55,7 +78,7 @@ private:
|
||||
}
|
||||
};
|
||||
|
||||
# define PIINTROSPECTION_CONTAINERS (PIIntrospectionContainersInterface::instance())
|
||||
# define PIINTROSPECTION_CONTAINERS (PIIntrospectionContainersInterface::instance())
|
||||
|
||||
// clang-format off
|
||||
# define PIINTROSPECTION_CONTAINER_NEW(t, isz) PIINTROSPECTION_CONTAINERS->containerNew (PIIntrospectionContainersTypeInfo<t>::get(), isz);
|
||||
@@ -67,6 +90,8 @@ private:
|
||||
// clang-format on
|
||||
|
||||
|
||||
//! \~english Container introspection interface
|
||||
//! \~russian Интерфейс интроспекции контейнеров
|
||||
class PIP_EXPORT PIIntrospectionContainersInterface {
|
||||
friend class PIIntrospection;
|
||||
friend class PIIntrospectionServer;
|
||||
@@ -75,11 +100,23 @@ public:
|
||||
__PIINTROSPECTION_SINGLETON_H__(Containers)
|
||||
|
||||
// clang-format off
|
||||
//! \~english Notify about new container allocation
|
||||
//! \~russian Уведомить о новом выделении контейнера
|
||||
void containerNew (const PIIntrospectionContainersType & ti, uint isz);
|
||||
//! \~english Notify about container deletion
|
||||
//! \~russian Уведомить об удалении контейнера
|
||||
void containerDelete(const PIIntrospectionContainersType & ti);
|
||||
//! \~english Notify about container memory allocation
|
||||
//! \~russian Уведомить о выделении памяти контейнером
|
||||
void containerAlloc (const PIIntrospectionContainersType & ti, ullong cnt);
|
||||
//! \~english Notify about container memory freeing
|
||||
//! \~russian Уведомить об освобождении памяти контейнером
|
||||
void containerFree (const PIIntrospectionContainersType & ti, ullong cnt);
|
||||
//! \~english Notify about container memory usage
|
||||
//! \~russian Уведомить об использовании памяти контейнером
|
||||
void containerUsed (const PIIntrospectionContainersType & ti, ullong cnt);
|
||||
//! \~english Notify about container unused memory
|
||||
//! \~russian Уведомить о неиспользуемой памяти контейнера
|
||||
void containerUnused(const PIIntrospectionContainersType & ti, ullong cnt);
|
||||
// clang-format on
|
||||
|
||||
@@ -91,14 +128,15 @@ private:
|
||||
};
|
||||
|
||||
|
||||
#else
|
||||
# define PIINTROSPECTION_CONTAINER_NEW(t, isz)
|
||||
# define PIINTROSPECTION_CONTAINER_DELETE(t)
|
||||
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_USED(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt)
|
||||
#endif
|
||||
# else
|
||||
# define PIINTROSPECTION_CONTAINER_NEW(t, isz)
|
||||
# define PIINTROSPECTION_CONTAINER_DELETE(t)
|
||||
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_USED(t, cnt)
|
||||
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt)
|
||||
# endif // defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
|
||||
#endif // PIINTROSPECTION_CONTAINERS_H
|
||||
//! \}
|
||||
|
||||
@@ -51,13 +51,23 @@ class PISystemMonitor;
|
||||
# define PIINTROSPECTION_START(name) PIINTROSPECTION_SERVER->start(#name);
|
||||
# define PIINTROSPECTION_STOP PIINTROSPECTION_SERVER->stop();
|
||||
|
||||
//! \~english Introspection server class for collecting and broadcasting PIP internal statistics
|
||||
//! \~russian Класс сервера интроспекции для сбора и распространения внутренних статистик PIP
|
||||
class PIP_EXPORT PIIntrospectionServer: public PIPeer {
|
||||
PIOBJECT_SUBCLASS(PIIntrospectionServer, PIPeer);
|
||||
|
||||
public:
|
||||
//! \~english Get singleton instance of introspection server
|
||||
//! \~russian Получить синглтон-экземпляр сервера интроспекции
|
||||
static PIIntrospectionServer * instance();
|
||||
|
||||
//! \~english Start introspection server with specified name
|
||||
//! \~russian Запустить сервер интроспекции с указанным именем
|
||||
//! \param server_name \~english Name of the server to start \~russian Имя сервера для запуска
|
||||
void start(const PIString & server_name);
|
||||
|
||||
//! \~english Stop introspection server
|
||||
//! \~russian Остановить сервер интроспекции
|
||||
void stop();
|
||||
|
||||
private:
|
||||
|
||||
@@ -17,25 +17,39 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
//! \addtogroup Introspection
|
||||
//! \{
|
||||
//! \file piintrospection_threads.h
|
||||
//! \brief Thread introspection interface
|
||||
//! \~english Interface for thread introspection and monitoring
|
||||
//! \~russian Интерфейс для интроспекции и мониторинга потоков
|
||||
//! \details
|
||||
//! \~english Provides callbacks for thread lifecycle events such as creation, deletion, start, run, wait, stop and completion
|
||||
//! \~russian Предоставляет обратные вызовы для событий жизненного цикла потоков: создание, удаление, запуск, выполнение, ожидание,
|
||||
//! остановка и завершение
|
||||
//! \}
|
||||
|
||||
#ifndef PIINTROSPECTION_THREADS_H
|
||||
#define PIINTROSPECTION_THREADS_H
|
||||
# define PIINTROSPECTION_THREADS_H
|
||||
|
||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
# if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||
|
||||
# include "piintrospection_base.h"
|
||||
# include "piintrospection_base.h"
|
||||
|
||||
class PIIntrospectionThreads;
|
||||
|
||||
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
|
||||
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
|
||||
|
||||
# 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);
|
||||
# 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);
|
||||
|
||||
//! \~english Thread introspection interface class
|
||||
//! \~russian Класс интерфейса интроспекции потоков
|
||||
class PIP_EXPORT PIIntrospectionThreadsInterface {
|
||||
friend class PIIntrospection;
|
||||
|
||||
@@ -43,12 +57,26 @@ public:
|
||||
__PIINTROSPECTION_SINGLETON_H__(Threads)
|
||||
|
||||
// clang-format off
|
||||
//! \~english Called when new thread is created
|
||||
//! \~russian Вызывается при создании нового потока
|
||||
void threadNew (PIThread * t);
|
||||
//! \~english Called when thread is deleted
|
||||
//! \~russian Вызывается при удалении потока
|
||||
void threadDelete (PIThread * t);
|
||||
//! \~english Called when thread is starting
|
||||
//! \~russian Вызывается при запуске потока
|
||||
void threadStart (PIThread * t);
|
||||
//! \~english Called when thread starts execution
|
||||
//! \~russian Вызывается при начале выполнения потока
|
||||
void threadRun (PIThread * t);
|
||||
//! \~english Called when thread is waiting
|
||||
//! \~russian Вызывается при ожидании потока
|
||||
void threadWait (PIThread * t);
|
||||
//! \~english Called when thread is stopped
|
||||
//! \~russian Вызывается при остановке потока
|
||||
void threadStop (PIThread * t);
|
||||
//! \~english Called when thread execution is done
|
||||
//! \~russian Вызывается при завершении выполнения потока
|
||||
void threadRunDone(PIThread * t, ullong us);
|
||||
// clang-format on
|
||||
|
||||
@@ -59,14 +87,15 @@ private:
|
||||
PIIntrospectionThreads * p;
|
||||
};
|
||||
|
||||
#else
|
||||
# define PIINTROSPECTION_THREAD_NEW(t)
|
||||
# define PIINTROSPECTION_THREAD_DELETE(t)
|
||||
# define PIINTROSPECTION_THREAD_START(t)
|
||||
# define PIINTROSPECTION_THREAD_RUN(t)
|
||||
# define PIINTROSPECTION_THREAD_WAIT(t)
|
||||
# define PIINTROSPECTION_THREAD_STOP(t)
|
||||
# define PIINTROSPECTION_THREAD_RUN_DONE(t, us)
|
||||
#endif
|
||||
# else
|
||||
# define PIINTROSPECTION_THREAD_NEW(t)
|
||||
# define PIINTROSPECTION_THREAD_DELETE(t)
|
||||
# define PIINTROSPECTION_THREAD_START(t)
|
||||
# define PIINTROSPECTION_THREAD_RUN(t)
|
||||
# define PIINTROSPECTION_THREAD_WAIT(t)
|
||||
# define PIINTROSPECTION_THREAD_STOP(t)
|
||||
# define PIINTROSPECTION_THREAD_RUN_DONE(t, us)
|
||||
# endif
|
||||
|
||||
#endif // PIINTROSPECTION_THREADS_H
|
||||
//! \}
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file piconfig.h
|
||||
* \ingroup IO
|
||||
* \~\brief
|
||||
* \~english Configuration files parser and writer
|
||||
* \~russian Разбор и запись конфигурационных файлов
|
||||
*/
|
||||
//! \addtogroup IO
|
||||
//! \{
|
||||
//! \file piconfig.h
|
||||
//! \brief Configuration files parser and writer
|
||||
//! \~english Parser and writer for configuration files with tree structure support
|
||||
//! \~russian Разбор и запись конфигурационных файлов с поддержкой древовидной структуры
|
||||
//! \details
|
||||
//! \~english PIConfig provides functionality to read, write and manipulate configuration files in a tree-like structure.
|
||||
//! \~russian PIConfig предоставляет функциональность для чтения, записи и управления конфигурационными файлами в древовидной структуре.
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Configuration parser and writer
|
||||
@@ -58,6 +62,8 @@
|
||||
Entry & getValue(const PIString & vname, const double def, bool * exists = 0) const {return getValue(vname, PIString::fromNumber(def), exists);}
|
||||
// clang-format on
|
||||
|
||||
//! \~english Main configuration parser and writer class
|
||||
//! \~russian Главный класс для разбора и записи конфигурационных файлов
|
||||
class PIP_EXPORT PIConfig {
|
||||
friend class Entry;
|
||||
friend class Branch;
|
||||
@@ -79,6 +85,8 @@ public:
|
||||
class Entry;
|
||||
|
||||
|
||||
//! \~english Branch class - container for Entry objects
|
||||
//! \~russian Класс Branch - контейнер для объектов Entry
|
||||
class PIP_EXPORT Branch: public PIVector<Entry *> {
|
||||
friend class PIConfig;
|
||||
friend class Entry;
|
||||
@@ -90,22 +98,44 @@ public:
|
||||
public:
|
||||
Branch() { ; }
|
||||
|
||||
//! \~english Get value from branch by name with default value
|
||||
//! \~russian Получить значение из ветки по имени со значением по умолчанию
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||
return const_cast<Branch *>(this)->getValue(vname, def, exists);
|
||||
}
|
||||
PICONFIG_GET_VALUE
|
||||
|
||||
//! \~english Get all leaf entries from the entire tree
|
||||
//! \~russian Получить все листовые записи из всего дерева
|
||||
Branch allLeaves();
|
||||
|
||||
//! \~english Get all entries with name containing specified substring
|
||||
//! \~russian Получить все записи с именем, содержащим указанную подстроку
|
||||
Branch getValues(const PIString & name);
|
||||
|
||||
//! \~english Get all leaf entries (entries without children)
|
||||
//! \~russian Получить все листовые записи (записи без детей)
|
||||
Branch getLeaves();
|
||||
|
||||
//! \~english Get all branch entries (entries with children)
|
||||
//! \~russian Получить все ветвящиеся записи (записи с детьми)
|
||||
Branch getBranches();
|
||||
|
||||
//! \~english Filter branch by filter string
|
||||
//! \~russian Фильтровать ветку по строке фильтра
|
||||
Branch & filter(const PIString & f);
|
||||
|
||||
//! \~english Check if entry with specified name exists
|
||||
//! \~russian Проверить, существует ли запись с указанным именем
|
||||
bool isEntryExists(const PIString & name) const {
|
||||
for (const auto * i: *this)
|
||||
if (entryExists(i, name)) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Get index of entry in branch
|
||||
//! \~russian Получить индекс записи в ветке
|
||||
int indexOf(const Entry * e) {
|
||||
for (int i = 0; i < size_s(); ++i)
|
||||
if (at(i) == e) return i;
|
||||
@@ -138,6 +168,8 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Entry class - represents a single configuration entry
|
||||
//! \~russian Класс Entry - представляет отдельную запись конфигурации
|
||||
class PIP_EXPORT Entry {
|
||||
friend class PIConfig;
|
||||
friend class Branch;
|
||||
@@ -446,18 +478,24 @@ public:
|
||||
};
|
||||
|
||||
|
||||
//! Read configuration from file at path "path" in mode "mode"
|
||||
//! \~english Open configuration from file at path in specified mode
|
||||
//! \~russian Открыть конфигурацию из файла по указанному пути в указанном режиме
|
||||
bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Read configuration from string "string" in mode "mode"
|
||||
//! \~english Open configuration from string in specified mode
|
||||
//! \~russian Открыть конфигурацию из строки в указанном режиме
|
||||
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! Read configuration from custom device "device" in mode "mode"
|
||||
//! \~english Open configuration from custom I/O device in specified mode
|
||||
//! \~russian Открыть конфигурацию из пользовательского устройства ввода-вывода в указанном режиме
|
||||
bool open(PIIODevice * device, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||
|
||||
//! \~english Check if configuration is opened
|
||||
//! \~russian Проверить, открыта ли конфигурация
|
||||
bool isOpened() const;
|
||||
|
||||
//! Returns top-level entry with name "vname", if doesn`t exists return entry with value "def" and set *exist to false
|
||||
//! \~english Get top-level entry by name with default value
|
||||
//! \~russian Получить запись верхнего уровня по имени со значением по умолчанию
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||
return const_cast<PIConfig *>(this)->getValue(vname, def, exists);
|
||||
@@ -504,13 +542,16 @@ public:
|
||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
||||
|
||||
|
||||
//! Returns top-level entries with names with substrings "vname"
|
||||
//! \~english Get all top-level entries with name containing substring
|
||||
//! \~russian Получить все записи верхнего уровня с именем, содержащим подстроку
|
||||
Branch getValues(const PIString & vname);
|
||||
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file. Add new entry if there
|
||||
//! is no suitable exists
|
||||
//! \~english Set value for top-level entry with name
|
||||
//! \~russian Установить значение для записи верхнего уровня с именем
|
||||
//! \details
|
||||
//! \~english Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file.
|
||||
//! Add new entry if there is no suitable exists
|
||||
void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||
|
||||
//! Set top-level entry with name "name" value to "value", type to "l" and if "write" immediate write to file. Add new entry if there is
|
||||
@@ -561,16 +602,20 @@ public:
|
||||
//! no suitable exists
|
||||
void setValue(const PIString & name, const double value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
||||
|
||||
//! Returns root entry
|
||||
//! \~english Get root entry of configuration tree
|
||||
//! \~russian Получить корневую запись дерева конфигурации
|
||||
Entry & rootEntry() { return root; }
|
||||
|
||||
//! Returns top-level entries count
|
||||
//! \~english Get count of top-level entries
|
||||
//! \~russian Получить количество записей верхнего уровня
|
||||
int entriesCount() const { return childCount(&root); }
|
||||
|
||||
//! Returns if top-level entry with name "name" exists
|
||||
//! \~english Check if top-level entry with name exists
|
||||
//! \~russian Проверить, существует ли запись верхнего уровня с указанным именем
|
||||
bool isEntryExists(const PIString & name) const { return entryExists(&root, name); }
|
||||
|
||||
//! Returns all top-level entries
|
||||
//! \~english Get all top-level entries
|
||||
//! \~russian Получить все записи верхнего уровня
|
||||
Branch allTree() {
|
||||
Branch b;
|
||||
for (auto * i: root._children)
|
||||
@@ -579,7 +624,8 @@ public:
|
||||
return b;
|
||||
}
|
||||
|
||||
//! Returns all entries without children
|
||||
//! \~english Get all entries without children (leaves)
|
||||
//! \~russian Получить все записи без детей (листья)
|
||||
Branch allLeaves() {
|
||||
Branch b;
|
||||
allLeaves(b, &root);
|
||||
@@ -588,35 +634,71 @@ public:
|
||||
return b;
|
||||
}
|
||||
|
||||
//! \~english Get index of entry by name
|
||||
//! \~russian Получить индекс записи по имени
|
||||
int entryIndex(const PIString & name);
|
||||
|
||||
//! \~english Get entry name by index
|
||||
//! \~russian Получить имя записи по индексу
|
||||
PIString getName(uint number) { return entryByIndex(number)._name; }
|
||||
|
||||
//! \~english Get entry value by index
|
||||
//! \~russian Получить значение записи по индексу
|
||||
PIString getValueByIndex(uint number) { return entryByIndex(number)._value; }
|
||||
|
||||
//! \~english Get entry type by index
|
||||
//! \~russian Получить тип записи по индексу
|
||||
PIChar getType(uint number) { return entryByIndex(number)._type[0]; }
|
||||
|
||||
//! \~english Get entry comment by index
|
||||
//! \~russian Получить комментарий записи по индексу
|
||||
PIString getComment(uint number) { return entryByIndex(number)._comment; }
|
||||
|
||||
//! \~english Add new entry with name, value and type
|
||||
//! \~russian Добавить новую запись с именем, значением и типом
|
||||
void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||
|
||||
//! \~english Set name of entry by index
|
||||
//! \~russian Установить имя записи по индексу
|
||||
void setName(uint number, const PIString & name, bool write = true);
|
||||
|
||||
//! \~english Set value of entry by index
|
||||
//! \~russian Установить значение записи по индексу
|
||||
void setValue(uint number, const PIString & value, bool write = true);
|
||||
|
||||
//! \~english Set type of entry by index
|
||||
//! \~russian Установить тип записи по индексу
|
||||
void setType(uint number, const PIString & type, bool write = true);
|
||||
|
||||
//! \~english Set comment of entry by index
|
||||
//! \~russian Установить комментарий записи по индексу
|
||||
void setComment(uint number, const PIString & comment, bool write = true);
|
||||
|
||||
//! \~english Remove entry by name
|
||||
//! \~russian Удалить запись по имени
|
||||
void removeEntry(const PIString & name, bool write = true);
|
||||
|
||||
//! \~english Remove entry by index
|
||||
//! \~russian Удалить запись по индексу
|
||||
void removeEntry(uint number, bool write = true);
|
||||
|
||||
//! Remove all tree and device content
|
||||
void clear();
|
||||
|
||||
//! Parse device and build internal tree
|
||||
//! \~english Parse device and build internal tree
|
||||
//! \~russian Прочитать устройство и построить внутреннее дерево
|
||||
void readAll();
|
||||
|
||||
//! Write all internal tree to device
|
||||
//! \~english Write all internal tree to device
|
||||
//! \~russian Записать всё внутреннее дерево в устройство
|
||||
void writeAll();
|
||||
|
||||
//! Returns current tree delimiter, default "."
|
||||
//! \~english Get current tree delimiter
|
||||
//! \~russian Получить текущий разделитель дерева
|
||||
const PIString & delimiter() const { return delim; }
|
||||
|
||||
//! Set current tree delimiter
|
||||
//! \~english Set tree delimiter
|
||||
//! \~russian Установить разделитель дерева
|
||||
void setDelimiter(const PIString & d) {
|
||||
delim = d;
|
||||
setEntryDelim(&root, d);
|
||||
@@ -708,14 +790,18 @@ inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
|
||||
}
|
||||
|
||||
|
||||
/** \relatesalso PIConfig \relatesalso PIIODevice
|
||||
* \brief Service function. useful for configuring devices
|
||||
* \details Function takes entry name "name", default value "def" and two
|
||||
* \a PIConfig::Entry sections: "em" and their parent "ep". If there is no
|
||||
* parent ep = 0. If "ep" is not null and entry "name" exists in "ep" function
|
||||
* returns this value. Else returns value of entry "name" in section "em" or
|
||||
* "def" if entry doesn`t exists. \n This function useful to read settings
|
||||
* from configuration file in implementation \a PIIODevice::configureDevice() function */
|
||||
//! \~english Service function for reading device settings from configuration
|
||||
//! \~russian Сервисная функция для чтения настроек устройства из конфигурации
|
||||
//! \note
|
||||
//! \~english Useful for implementing PIIODevice::configureDevice()
|
||||
//! \~russian Полезно для реализации PIIODevice::configureDevice()
|
||||
//! \~\details Function takes entry name "name", default value "def" and two
|
||||
//! \a PIConfig::Entry sections: "em" and their parent "ep". If there is no
|
||||
//! parent ep = 0. If "ep" is not null and entry "name" exists in "ep" function
|
||||
//! returns this value. Else returns value of entry "name" in section "em" or
|
||||
//! "def" if entry doesn`t exists. \n This function useful to read settings
|
||||
//! from configuration file in implementation \a PIIODevice::configureDevice() function
|
||||
//! \relatesalso PIConfig \relatesalso PIIODevice
|
||||
template<typename T>
|
||||
T readDeviceSetting(const PIString & name, const T & def, const PIConfig::Entry * em, const PIConfig::Entry * ep) {
|
||||
PIVariant v = PIVariant::fromValue<T>(def);
|
||||
|
||||
@@ -76,30 +76,40 @@ public:
|
||||
|
||||
|
||||
//! Set read address
|
||||
//! \~english Set read address
|
||||
//! \~russian Устанавливает адрес для чтения
|
||||
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"
|
||||
//! \~english Set read address in format "i.i.i.i:p"
|
||||
//! \~russian Устанавливает адрес для чтения в формате "i.i.i.i:p"
|
||||
void setReadAddress(const PIString & ip_port) {
|
||||
addr_r.set(ip_port);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read address
|
||||
//! \~english Set read address
|
||||
//! \~russian Устанавливает адрес для чтения
|
||||
void setReadAddress(const PINetworkAddress & addr) {
|
||||
addr_r = addr;
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read IP
|
||||
//! \~english Set read IP
|
||||
//! \~russian Устанавливает IP для чтения
|
||||
void setReadIP(const PIString & ip) {
|
||||
addr_r.setIP(ip);
|
||||
setPath(addr_r.toString());
|
||||
}
|
||||
|
||||
//! Set read port
|
||||
//! \~english Set read port
|
||||
//! \~russian Устанавливает порт для чтения
|
||||
void setReadPort(int port) {
|
||||
addr_r.setPort(port);
|
||||
setPath(addr_r.toString());
|
||||
@@ -153,12 +163,16 @@ public:
|
||||
|
||||
|
||||
//! Set parameters to "parameters_". You should to reopen %PIEthernet to apply them
|
||||
//! \~english Set parameters to "parameters_". You should to reopen %PIEthernet to apply them
|
||||
//! \~russian Устанавливает параметры "parameters_". Необходимо переоткрыть %PIEthernet для применения
|
||||
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) {
|
||||
params = parameters_;
|
||||
applyParameters();
|
||||
}
|
||||
|
||||
//! Set parameter "parameter" to state "on". You should to reopen %PIEthernet to apply this
|
||||
//! \~english Set parameter "parameter" to state "on". You should to reopen %PIEthernet to apply this
|
||||
//! \~russian Устанавливает параметр "parameter" в состояние "on". Необходимо переоткрыть %PIEthernet для применения
|
||||
void setParameter(PIEthernet::Parameters parameter, bool on = true) {
|
||||
params.setFlag(parameter, on);
|
||||
applyParameters();
|
||||
@@ -222,18 +236,24 @@ public:
|
||||
bool connect(bool threaded = true);
|
||||
|
||||
//! Connect to TCP server with address "ip":"port". Use only for TCP_Client
|
||||
//! \~english Connect to TCP server with address "ip":"port". Use only for TCP_Client
|
||||
//! \~russian Подключается к TCP серверу по адресу "ip":"port". Только для TCP_Client
|
||||
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
|
||||
//! \~english Connect to TCP server with address "ip_port". Use only for TCP_Client
|
||||
//! \~russian Подключается к TCP серверу по адресу "ip_port". Только для TCP_Client
|
||||
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
|
||||
//! \~english Connect to TCP server with address "addr". Use only for TCP_Client
|
||||
//! \~russian Подключается к TCP серверу по адресу "addr". Только для TCP_Client
|
||||
bool connect(const PINetworkAddress & addr, bool threaded = true) {
|
||||
setPath(addr.toString());
|
||||
return connect(threaded);
|
||||
@@ -269,11 +289,15 @@ public:
|
||||
bool send(const void * data, int size, bool threaded = false);
|
||||
|
||||
//! Send data "data" with size "size" to address "ip":"port"
|
||||
//! \~english Send data "data" with size "size" to address "ip":"port"
|
||||
//! \~russian Отправляет данные "data" размером "size" на адрес "ip":"port"
|
||||
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip, port), data, size, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" with size "size" to address "ip_port"
|
||||
//! \~english Send data "data" with size "size" to address "ip_port"
|
||||
//! \~russian Отправляет данные "data" размером "size" на адрес "ip_port"
|
||||
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip_port), data, size, threaded);
|
||||
}
|
||||
@@ -285,11 +309,15 @@ public:
|
||||
bool send(const PIByteArray & data, bool threaded = false);
|
||||
|
||||
//! Send data "data" to address "ip":"port" for UDP
|
||||
//! \~english Send data "data" to address "ip":"port" for UDP
|
||||
//! \~russian Отправляет данные "data" на адрес "ip":"port" для UDP
|
||||
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip, port), data, threaded);
|
||||
}
|
||||
|
||||
//! Send data "data" to address "ip_port" for UDP
|
||||
//! \~english Send data "data" to address "ip_port" for UDP
|
||||
//! \~russian Отправляет данные "data" на адрес "ip_port" для UDP
|
||||
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {
|
||||
return send(PINetworkAddress(ip_port), data, threaded);
|
||||
}
|
||||
|
||||
@@ -56,26 +56,20 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||
|
||||
#else
|
||||
|
||||
# define REGISTER_DEVICE(name) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIIODevice::registerDevice(name::fullPathPrefixS(), #name, []() -> PIIODevice * { return new name(); }); \
|
||||
STATIC_INITIALIZER_END
|
||||
# define REGISTER_DEVICE(name) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
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(); \
|
||||
} \
|
||||
\
|
||||
public: \
|
||||
PIConstChars fullPathPrefix() const override { \
|
||||
return prefix; \
|
||||
} \
|
||||
static PIConstChars fullPathPrefixS() { \
|
||||
return prefix; \
|
||||
} \
|
||||
\
|
||||
private:
|
||||
# define PIIODEVICE(name, prefix) \
|
||||
PIOBJECT_SUBCLASS(name, PIIODevice) \
|
||||
PIIODevice * copy() const override { return new name(); } \
|
||||
\
|
||||
public: \
|
||||
PIConstChars fullPathPrefix() const override { return prefix; } \
|
||||
static PIConstChars fullPathPrefixS() { return prefix; } \
|
||||
\
|
||||
private:
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -49,11 +49,15 @@ public:
|
||||
resetReadError();
|
||||
}
|
||||
|
||||
//! \~english Append data to stream
|
||||
//! \~russian Добавляет данные в поток
|
||||
bool binaryStreamAppendImp(const void * d, size_t s) {
|
||||
if (!dev) return false;
|
||||
return (dev->write(d, s) == (int)s);
|
||||
}
|
||||
|
||||
//! \~english Take data from stream
|
||||
//! \~russian Извлекает данные из потока
|
||||
bool binaryStreamTakeImp(void * d, size_t s) {
|
||||
if (!dev) return false;
|
||||
return (dev->read(d, s) == (int)s);
|
||||
@@ -90,6 +94,8 @@ public:
|
||||
if (io_string) delete io_string;
|
||||
}
|
||||
|
||||
//! \~english Assign "device" device
|
||||
//! \~russian Назначает устройство "device"
|
||||
void setDevice(PIIODevice * device) {
|
||||
bin_stream = PIIOBinaryStream(device);
|
||||
setStream(&bin_stream);
|
||||
|
||||
@@ -216,6 +216,8 @@ public:
|
||||
//! \~russian Переключает состояние передачи в break
|
||||
bool setBreak(bool enabled);
|
||||
|
||||
//! \~english Set VTime parameter
|
||||
//! \~russian Устанавливает параметр VTime
|
||||
void setVTime(int t) {
|
||||
vtime = t;
|
||||
applySettings();
|
||||
|
||||
@@ -29,24 +29,39 @@
|
||||
#include "picrc.h"
|
||||
#include "pidiagnostics.h"
|
||||
|
||||
//! \~english Base class for reliable send and receive data in fixed packets with error correction, pause and resume
|
||||
//! \~russian Базовый класс для надежного обмена данными с помощью фиксированных пакетов с коррекцией ошибок и паузой
|
||||
class PIP_EXPORT PIBaseTransfer: public PIObject {
|
||||
PIOBJECT_SUBCLASS(PIBaseTransfer, PIObject);
|
||||
|
||||
public:
|
||||
//! \~english Constructs empty transfer
|
||||
//! \~russian Создает пустой transfer
|
||||
PIBaseTransfer();
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PIBaseTransfer();
|
||||
|
||||
#pragma pack(push, 1)
|
||||
//! \~english Packet header structure
|
||||
//! \~russian Структура заголовка пакета
|
||||
struct PIP_EXPORT PacketHeader {
|
||||
uint sig;
|
||||
int type; // PacketType
|
||||
int session_id;
|
||||
uint id;
|
||||
uint crc;
|
||||
//! \~english Check if signature is valid
|
||||
//! \~russian Проверка валидности подписи
|
||||
bool check_sig() { return (sig == signature); }
|
||||
};
|
||||
|
||||
//! \~english Part information structure
|
||||
//! \~russian Структура информации о части
|
||||
struct PIP_EXPORT Part {
|
||||
//! \~english Constructor
|
||||
//! \~russian Конструктор
|
||||
Part(uint id_ = 0, ullong size_ = 0, ullong start_ = 0): id(id_), size(size_), start(start_) {}
|
||||
uint id;
|
||||
ullong size;
|
||||
@@ -54,29 +69,76 @@ public:
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
//! \~english Stop sending data
|
||||
//! \~russian Остановить отправку данных
|
||||
void stopSend();
|
||||
|
||||
//! \~english Stop receiving data
|
||||
//! \~russian Остановить прием данных
|
||||
void stopReceive();
|
||||
|
||||
//! \~english Check if currently sending
|
||||
//! \~russian Проверка, идет ли отправка
|
||||
bool isSending() const { return is_sending; }
|
||||
|
||||
//! \~english Check if currently receiving
|
||||
//! \~russian Проверка, идет ли прием
|
||||
bool isReceiving() const { return is_receiving; }
|
||||
|
||||
//! \~english Check if paused
|
||||
//! \~russian Проверка, на паузе ли
|
||||
bool isPause() const { return is_pause; }
|
||||
|
||||
//! \~english Set pause state
|
||||
//! \~russian Установить состояние паузы
|
||||
void setPause(bool pause_);
|
||||
|
||||
//! \~english Set packet size
|
||||
//! \~russian Установить размер пакета
|
||||
void setPacketSize(int size) { packet_size = size; }
|
||||
|
||||
//! \~english Get packet size
|
||||
//! \~russian Получить размер пакета
|
||||
int packetSize() const { return packet_size; }
|
||||
|
||||
//! \~english Set timeout in seconds
|
||||
//! \~russian Установить таймаут в секундах
|
||||
void setTimeout(double sec);
|
||||
|
||||
//! \~english Get timeout in seconds
|
||||
//! \~russian Получить таймаут в секундах
|
||||
double timeout() const { return timeout_; }
|
||||
|
||||
//! \~english Enable/disable CRC check
|
||||
//! \~russian Включить/выключить проверку CRC
|
||||
void setCRCEnabled(bool en = true) { crc_enabled = en; }
|
||||
|
||||
//! \~english Check if CRC is enabled
|
||||
//! \~russian Проверка, включен ли CRC
|
||||
bool isCRCEnabled() const { return crc_enabled; }
|
||||
|
||||
//! \~english Get state as string
|
||||
//! \~russian Получить состояние в виде строки
|
||||
PIString stateString() const { return state_string; }
|
||||
|
||||
//! \~english Get packet map as string
|
||||
//! \~russian Получить карту пакетов в виде строки
|
||||
PIString packetMap() const { return pm_string; }
|
||||
|
||||
//! \~english Get total bytes count
|
||||
//! \~russian Получить общее количество байт
|
||||
llong bytesAll() const { return bytes_all; }
|
||||
|
||||
//! \~english Get current bytes count
|
||||
//! \~russian Получить текущее количество байт
|
||||
llong bytesCur() const { return bytes_cur; }
|
||||
|
||||
//! \~english Get diagnostics object
|
||||
//! \~russian Получить объект диагностики
|
||||
const PIDiagnostics & diagnostic() { return diag; }
|
||||
|
||||
//! \~english Get packet signature
|
||||
//! \~russian Получить подпись пакета
|
||||
static uint packetSignature() { return signature; }
|
||||
|
||||
EVENT_HANDLER1(void, received, PIByteArray, data);
|
||||
|
||||
@@ -31,13 +31,16 @@
|
||||
#include "pip_io_utils_export.h"
|
||||
|
||||
|
||||
//! \~english Broadcast for all interfaces, including loopback
|
||||
//! \~russian Широкое вещание на все интерфейсы, включая loopback
|
||||
class PIP_IO_UTILS_EXPORT PIBroadcast
|
||||
: public PIThread
|
||||
, public PIEthUtilBase {
|
||||
PIOBJECT_SUBCLASS(PIBroadcast, PIThread);
|
||||
|
||||
public:
|
||||
//! %PIBroadcast channels, can be used independently
|
||||
//! \~english %PIBroadcast channels, can be used independently
|
||||
//! \~russian Каналы %PIBroadcast, могут использоваться независимо
|
||||
enum Channel {
|
||||
Multicast /** Use multicast addresses */ = 0x01,
|
||||
Broadcast /** Use broadcast addresses */ = 0x02,
|
||||
@@ -45,75 +48,97 @@ public:
|
||||
All /** Use all channels */ = 0xFFFF,
|
||||
};
|
||||
|
||||
//! \~english Channels flags type
|
||||
//! \~russian Тип флагов каналов
|
||||
typedef PIFlags<Channel> Channels;
|
||||
|
||||
/** Contructs %PIBroadcast, if \"send_only\" not set
|
||||
* all PIEthernets will be binded to receive data
|
||||
* */
|
||||
//! \~english Constructs %PIBroadcast. If "send_only" not set, all PIEthernets will be binded to receive data
|
||||
//! \~russian Создает %PIBroadcast. Если "send_only" не установлен, все PIEthernets будут привязаны для приема данных
|
||||
PIBroadcast(bool send_only = false);
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PIBroadcast();
|
||||
|
||||
//! Set channels to \"ch\" and queue to reinit
|
||||
//! \~english Set channels to "ch" and queue to reinit
|
||||
//! \~russian Установить каналы в "ch" и очередь на реинициализацию
|
||||
void setChannels(Channels ch);
|
||||
|
||||
//! Returns channels
|
||||
//! \~english Returns channels
|
||||
//! \~russian Возвращает каналы
|
||||
Channels channels() const { return _channels; }
|
||||
|
||||
//! Returns if is send_only
|
||||
//! \~english Returns if is send_only
|
||||
//! \~russian Возвращает, является ли отправка только
|
||||
bool isSendOnly() const { return _send_only; }
|
||||
|
||||
|
||||
//! Set multicast IP to \"mg\" and queue to reinit
|
||||
//! \~english Set multicast IP to "mg" and queue to reinit
|
||||
//! \~russian Установить multicast IP в "mg" и очередь на реинициализацию
|
||||
void setMulticastGroup(const PIString & mg);
|
||||
|
||||
//! Returns multicast IP
|
||||
//! \~english Returns multicast IP
|
||||
//! \~russian Возвращает multicast IP
|
||||
PIString multicastGroup() const { return mcast_address.ipString(); }
|
||||
|
||||
//! Set multicast port to \"port\" and queue to reinit
|
||||
//! \~english Set multicast port to "port" and queue to reinit
|
||||
//! \~russian Установить multicast порт в "port" и очередь на реинициализацию
|
||||
void setMulticastPort(ushort port);
|
||||
|
||||
//! Returns multicast port
|
||||
//! \~english Returns multicast port
|
||||
//! \~russian Возвращает multicast порт
|
||||
ushort multicastPort() const { return mcast_address.port(); }
|
||||
|
||||
//! Set multicast address to \"addr\" and queue to reinit
|
||||
//! \~english Set multicast address to "addr" and queue to reinit
|
||||
//! \~russian Установить multicast адрес в "addr" и очередь на реинициализацию
|
||||
void setMulticastAddress(const PINetworkAddress & addr);
|
||||
|
||||
//! Returns multicast address
|
||||
//! \~english Returns multicast address
|
||||
//! \~russian Возвращает multicast адрес
|
||||
PINetworkAddress multicastAddress() const { return mcast_address; }
|
||||
|
||||
|
||||
//! Set broadcast port to \"port\" and queue to reinit
|
||||
//! \~english Set broadcast port to "port" and queue to reinit
|
||||
//! \~russian Установить broadcast порт в "port" и очередь на реинициализацию
|
||||
void setBroadcastPort(ushort port);
|
||||
|
||||
//! Returns broadcast port
|
||||
//! \~english Returns broadcast port
|
||||
//! \~russian Возвращает broadcast порт
|
||||
ushort broadcastPort() { return bcast_port; }
|
||||
|
||||
|
||||
//! Set loopback start port to \"port\" and queue to reinit
|
||||
//! \~english Set loopback start port to "port" and queue to reinit
|
||||
//! \~russian Установить начальный loopback порт в "port" и очередь на реинициализацию
|
||||
void setLoopbackPort(ushort port);
|
||||
|
||||
//! Returns loopback start port
|
||||
//! \~english Returns loopback start port
|
||||
//! \~russian Возвращает начальный loopback порт
|
||||
ushort loopbackPort() { return lo_port; }
|
||||
|
||||
//! Set loopback ports count to \"count\" and queue to reinit
|
||||
//! \~english Set loopback ports count to "count" and queue to reinit
|
||||
//! \~russian Установить количество loopback портов в "count" и очередь на реинициализацию
|
||||
void setLoopbackPortsCount(int count);
|
||||
|
||||
//! Returns loopback ports count
|
||||
//! \~english Returns loopback ports count
|
||||
//! \~russian Возвращает количество loopback портов
|
||||
int loopbackPortsCount() const { return lo_pcnt; }
|
||||
|
||||
|
||||
//! If not send_only starts all threaded reads
|
||||
//! \~english If not send_only starts all threaded reads
|
||||
//! \~russian Если не send_only запускает все потоковые чтения
|
||||
void startRead();
|
||||
|
||||
//! Stop all threaded reads
|
||||
//! \~english Stop all threaded reads
|
||||
//! \~russian Остановить все потоковые чтения
|
||||
void stopRead();
|
||||
|
||||
//! Reinit all PIEthernets with current \a PIEthernet::allAddresses()
|
||||
//! \~english Reinit all PIEthernets with current \a PIEthernet::allAddresses()
|
||||
//! \~russian Реинициализировать все PIEthernets с текущими \a PIEthernet::allAddresses()
|
||||
void reinit();
|
||||
|
||||
|
||||
//! Send packet
|
||||
//! \~english Send packet
|
||||
//! \~russian Отправить пакет
|
||||
void send(const PIByteArray & data);
|
||||
|
||||
EVENT1(receiveEvent, PIByteArray, data);
|
||||
|
||||
@@ -32,6 +32,8 @@
|
||||
|
||||
class PIConfig;
|
||||
|
||||
//! \~english Complex I/O point
|
||||
//! \~russian Составное устройство ввода/вывода
|
||||
class PIP_EXPORT PIConnection: public PIObject {
|
||||
PIOBJECT_SUBCLASS(PIConnection, PIObject);
|
||||
|
||||
|
||||
@@ -29,14 +29,26 @@
|
||||
#include "pibasetransfer.h"
|
||||
|
||||
|
||||
//! \~english Class for send and receive PIByteArray via \a PIBaseTransfer
|
||||
//! \~russian Класс для отправки и приема PIByteArray с помощью \a PIBaseTransfer
|
||||
class PIP_EXPORT PIDataTransfer: public PIBaseTransfer {
|
||||
PIOBJECT_SUBCLASS(PIDataTransfer, PIBaseTransfer);
|
||||
|
||||
public:
|
||||
//! \~english Constructs empty data transfer
|
||||
//! \~russian Создает пустой transfer данных
|
||||
PIDataTransfer() { ; }
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PIDataTransfer() { ; }
|
||||
|
||||
//! \~english Send data
|
||||
//! \~russian Отправить данные
|
||||
bool send(const PIByteArray & ba);
|
||||
|
||||
//! \~english Get received data
|
||||
//! \~russian Получить принятые данные
|
||||
const PIByteArray & data() { return data_; }
|
||||
|
||||
private:
|
||||
|
||||
@@ -29,45 +29,61 @@
|
||||
#include "pibytearray.h"
|
||||
#include "pip_io_utils_export.h"
|
||||
|
||||
|
||||
//! \~english Base class for ethernet utils
|
||||
//! \~russian Базовый класс для утилит ethernet
|
||||
class PIP_IO_UTILS_EXPORT PIEthUtilBase {
|
||||
public:
|
||||
//! \~english Constructs PIEthUtilBase
|
||||
//! \~russian Создает PIEthUtilBase
|
||||
PIEthUtilBase();
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PIEthUtilBase();
|
||||
|
||||
//! Set crypt layer enabled
|
||||
//! \~english Set crypt layer enabled
|
||||
//! \~russian Включить слой шифрования
|
||||
void setCryptEnabled(bool on);
|
||||
|
||||
//! Enable crypt layer
|
||||
//! \~english Enable crypt layer
|
||||
//! \~russian Включить слой шифрования
|
||||
void cryptEnable();
|
||||
|
||||
//! Disable crypt layer
|
||||
//! \~english Disable crypt layer
|
||||
//! \~russian Выключить слой шифрования
|
||||
void cryptDisable();
|
||||
|
||||
//! Returns if crypt layer enabled
|
||||
//! \~english Returns if crypt layer enabled
|
||||
//! \~russian Возвращает, включен ли слой шифрования
|
||||
bool isCryptEnabled() const;
|
||||
|
||||
|
||||
//! Set crypt layer key to \"k\"
|
||||
//! \~english Set crypt layer key to "k"
|
||||
//! \~russian Установить ключ шифрования в "k"
|
||||
void setCryptKey(const PIByteArray & k);
|
||||
|
||||
//! Generate crypt layer key by \a PICrypt::hash and
|
||||
//! set crypt layer enabled
|
||||
//! \~english Generate crypt layer key by \a PICrypt::hash and set crypt layer enabled
|
||||
//! \~russian Сгенерировать ключ шифрования с помощью \a PICrypt::hash и включить шифрование
|
||||
void createCryptKey(const PIString & k);
|
||||
|
||||
//! Returns crypt layer key
|
||||
//! \~english Returns crypt layer key
|
||||
//! \~russian Возвращает ключ шифрования
|
||||
PIByteArray cryptKey() const;
|
||||
|
||||
//! \brief Returns addition size for crypted data.
|
||||
//! \~english Returns addition size for crypted data
|
||||
//! \~russian Возвращает дополнительный размер для зашифрованных данных
|
||||
static size_t cryptSizeAddition();
|
||||
|
||||
protected:
|
||||
/*! \brief Returns encrypted data if layer enabled,
|
||||
* otherwise returns unchanged \"data\" */
|
||||
//! \~english Returns encrypted data if layer enabled, otherwise returns unchanged "data"
|
||||
//! \~russian Возвращает зашифрованные данные, если слой включен, иначе возвращает неизмененные "data"
|
||||
PIByteArray cryptData(const PIByteArray & data);
|
||||
|
||||
/*! \brief Returns decrypted data if layer enabled,
|
||||
* otherwise returns unchanged \"data\". If decryption
|
||||
* was unsuccessfull returns empty %PIByteArray. */
|
||||
//! \~english Returns decrypted data if layer enabled, otherwise returns unchanged "data". If decryption was unsuccessful returns empty
|
||||
//! %PIByteArray
|
||||
//! \~russian Возвращает расшифрованные данные, если слой включен, иначе возвращает неизмененные "data". Если расшифровка неуспешна,
|
||||
//! возвращает пустой %PIByteArray
|
||||
PIByteArray decryptData(const PIByteArray & data);
|
||||
|
||||
private:
|
||||
|
||||
@@ -31,25 +31,40 @@
|
||||
|
||||
#define __PIFILETRANSFER_VERSION 2
|
||||
|
||||
//! \~english Class for send and receive files and directories via \a PIBaseTransfer
|
||||
//! \~russian Класс для отправки и приема файлов и папок с помощью \a PIBaseTransfer
|
||||
class PIP_EXPORT PIFileTransfer: public PIBaseTransfer {
|
||||
PIOBJECT_SUBCLASS(PIFileTransfer, PIBaseTransfer);
|
||||
|
||||
public:
|
||||
//! \~english Constructs empty file transfer
|
||||
//! \~russian Создает пустой transfer файлов
|
||||
PIFileTransfer();
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PIFileTransfer();
|
||||
|
||||
//! \~english Step type for file transfer
|
||||
//! \~russian Тип шага для передачи файлов
|
||||
enum StepType {
|
||||
pft_None,
|
||||
pft_Description,
|
||||
pft_Data
|
||||
};
|
||||
|
||||
//! \~english File information structure
|
||||
//! \~russian Структура информации о файле
|
||||
struct PIP_EXPORT PFTFileInfo: public PIFile::FileInfo {
|
||||
//! \~english Constructor
|
||||
//! \~russian Конструктор
|
||||
PFTFileInfo(const PIFile::FileInfo & fi = PIFile::FileInfo()): PIFile::FileInfo(fi) {}
|
||||
PIString dest_path;
|
||||
};
|
||||
|
||||
#pragma pack(push, 1)
|
||||
//! \~english File transfer header structure
|
||||
//! \~russian Структура заголовка передачи файлов
|
||||
struct PIP_EXPORT PFTHeader {
|
||||
union {
|
||||
struct {
|
||||
@@ -60,6 +75,8 @@ public:
|
||||
};
|
||||
int step; // PacketType
|
||||
int session_id;
|
||||
//! \~english Check if signature is valid
|
||||
//! \~russian Проверка валидности подписи
|
||||
bool check_sig() {
|
||||
if (sig[0] != sign[0] || sig[1] != sign[1] || sig[2] != sign[2] || version != __PIFILETRANSFER_VERSION) return false;
|
||||
return true;
|
||||
@@ -67,23 +84,64 @@ public:
|
||||
};
|
||||
#pragma pack(pop)
|
||||
|
||||
//! \~english Send file
|
||||
//! \~russian Отправить файл
|
||||
bool send(const PIFile & file);
|
||||
|
||||
//! \~english Send file by path
|
||||
//! \~russian Отправить файл по пути
|
||||
bool send(const PIString & file);
|
||||
|
||||
//! \~english Send files list
|
||||
//! \~russian Отправить список файлов
|
||||
bool send(const PIStringList & files);
|
||||
|
||||
//! \~english Send file info
|
||||
//! \~russian Отправить информацию о файле
|
||||
bool send(PIFile::FileInfo entry) { return send(PIVector<PIFile::FileInfo>() << entry); }
|
||||
|
||||
//! \~english Send file info vector
|
||||
//! \~russian Отправить вектор информации о файлах
|
||||
bool send(PIVector<PIFile::FileInfo> entries);
|
||||
|
||||
//! \~english Set directory
|
||||
//! \~russian Установить директорию
|
||||
void setDirectory(const PIDir & d) { dir = d; }
|
||||
|
||||
//! \~english Set directory by path
|
||||
//! \~russian Установить директорию по пути
|
||||
void setDirectory(const PIString & path) { dir.setDir(path); }
|
||||
|
||||
//! \~english Get directory
|
||||
//! \~russian Получить директорию
|
||||
PIDir directory() const { return dir; }
|
||||
|
||||
//! \~english Check if transfer is started
|
||||
//! \~russian Проверить, начата ли передача
|
||||
bool isStarted() const { return started_; }
|
||||
|
||||
//! \~english Get current file name
|
||||
//! \~russian Получить имя текущего файла
|
||||
PIString curFile() const;
|
||||
|
||||
//! \~english Get total bytes of current file
|
||||
//! \~russian Получить общее количество байт текущего файла
|
||||
llong bytesFileAll() const { return bytes_file_all; }
|
||||
|
||||
//! \~english Get current bytes of current file
|
||||
//! \~russian Получить текущие байты текущего файла
|
||||
llong bytesFileCur() const { return bytes_file_cur; }
|
||||
|
||||
//! \~english Get pointer to current file name
|
||||
//! \~russian Получить указатель на имя текущего файла
|
||||
const PIString * curFile_ptr() const { return &cur_file_string; }
|
||||
|
||||
//! \~english Get pointer to total bytes of current file
|
||||
//! \~russian Получить указатель на общее количество байт текущего файла
|
||||
const llong * bytesFileAll_ptr() const { return &bytes_file_all; }
|
||||
|
||||
//! \~english Get pointer to current bytes of current file
|
||||
//! \~russian Получить указатель на текущие байты текущего файла
|
||||
const llong * bytesFileCur_ptr() const { return &bytes_file_cur; }
|
||||
|
||||
EVENT(receiveFilesStarted);
|
||||
|
||||
@@ -34,31 +34,45 @@
|
||||
class PIEthernet;
|
||||
|
||||
|
||||
//! \~english Ethernet device
|
||||
//! \~russian Устройство Ethernet
|
||||
class PIP_IO_UTILS_EXPORT PIPackedTCP: public PIIODevice {
|
||||
PIIODEVICE(PIPackedTCP, "ptcp");
|
||||
|
||||
public:
|
||||
//! \brief Role of %PIPackedTCP
|
||||
//! \~english Role of %PIPackedTCP
|
||||
//! \~russian Роль %PIPackedTCP
|
||||
enum Role {
|
||||
Client /** TCP client */,
|
||||
Server /** TCP server for one client */
|
||||
};
|
||||
|
||||
//! Contructs %PIPackedTCP with "role" and "addr" address
|
||||
//! \~english Constructs %PIPackedTCP with "role" and "addr" address
|
||||
//! \~russian Создает %PIPackedTCP с ролью "role" и адресом "addr"
|
||||
explicit PIPackedTCP(Role role = Client, const PINetworkAddress & addr = {});
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
virtual ~PIPackedTCP();
|
||||
|
||||
//! Set server address for Server role or connect address for Client
|
||||
//! \~english Set server address for Server role or connect address for Client
|
||||
//! \~russian Установить адрес сервера для роли Server или адрес подключения для Client
|
||||
void setAddress(const PINetworkAddress & addr);
|
||||
|
||||
//! \~english Check if connected
|
||||
//! \~russian Проверить подключение
|
||||
bool isConnected() const;
|
||||
|
||||
//! \~english Check if connecting
|
||||
//! \~russian Проверить подключение
|
||||
bool isConnecting() const;
|
||||
|
||||
//! Returns read address in format "i.i.i.i:p"
|
||||
//! \~english Returns read address in format "i.i.i.i:p"
|
||||
//! \~russian Возвращает адрес чтения в формате "i.i.i.i:p"
|
||||
PINetworkAddress address() const { return m_addr; }
|
||||
|
||||
//! Returns %PIEthernet type
|
||||
//! \~english Returns %PIEthernet type
|
||||
//! \~russian Возвращает тип %PIEthernet
|
||||
Role role() const { return m_role; }
|
||||
|
||||
EVENT0(connected);
|
||||
|
||||
@@ -41,12 +41,15 @@ typedef std::function<bool(const uchar *, int)> PacketExtractorPayloadFunc;
|
||||
/// Return true if packet is correct, false otherwise.
|
||||
typedef std::function<bool(const uchar *, const uchar *, int)> PacketExtractorFooterFunc;
|
||||
|
||||
//! \~english Packets extractor
|
||||
//! \~russian Извлекатель пакетов
|
||||
class PIP_EXPORT PIPacketExtractor: public PIIODevice {
|
||||
PIIODEVICE(PIPacketExtractor, "pckext");
|
||||
friend class PIConnection;
|
||||
|
||||
public:
|
||||
//! Extract algorithms
|
||||
//! \~english Extract algorithms
|
||||
//! \~russian Алгоритмы извлечения
|
||||
enum SplitMode {
|
||||
None /** No data processing */,
|
||||
Header /** Detect packets with \a header() and following \a payloadSize() */,
|
||||
@@ -56,64 +59,91 @@ public:
|
||||
Timeout /** Wait for first read, then read for \a timeout() */
|
||||
};
|
||||
|
||||
//! Contructs extractor with child device "device_" and extract algorithm "mode"
|
||||
//! \~english Constructs extractor with child device "device_" and extract algorithm "mode"
|
||||
//! \~russian Создает экстрактор с дочерним устройством "device_" и алгоритмом извлечения "mode"
|
||||
explicit PIPacketExtractor(PIIODevice * device_ = nullptr, SplitMode mode = None);
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
virtual ~PIPacketExtractor() { stop(); }
|
||||
|
||||
|
||||
//! Returns child %device
|
||||
//! \~english Returns child %device
|
||||
//! \~russian Возвращает дочернее устройство
|
||||
PIIODevice * device() { return dev; }
|
||||
|
||||
//! Set child %device to "device_"
|
||||
//! \~english Set child %device to "device_"
|
||||
//! \~russian Установить дочернее устройство в "device_"
|
||||
void setDevice(PIIODevice * device_);
|
||||
|
||||
//! \~english Get bytes available
|
||||
//! \~russian Получить доступные байты
|
||||
ssize_t bytesAvailable() const override;
|
||||
|
||||
//! \~english Set header check function
|
||||
//! \~russian Установить функцию проверки заголовка
|
||||
void setHeaderCheckSlot(PacketExtractorHeaderFunc f) { func_header = f; }
|
||||
|
||||
//! \~english Set payload check function
|
||||
//! \~russian Установить функцию проверки полезной нагрузки
|
||||
void setPayloadCheckSlot(PacketExtractorPayloadFunc f) { func_payload = f; }
|
||||
|
||||
//! \~english Set footer check function
|
||||
//! \~russian Установить функцию проверки окончания
|
||||
void setFooterCheckSlot(PacketExtractorFooterFunc f) { func_footer = f; }
|
||||
|
||||
|
||||
//! Set extract algorithm
|
||||
//! \~english Set extract algorithm
|
||||
//! \~russian Установить алгоритм извлечения
|
||||
void setSplitMode(SplitMode mode) { setProperty("splitMode", int(mode)); }
|
||||
|
||||
//! Set payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms
|
||||
//! \~english Set payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer algorithms
|
||||
//! \~russian Установить размер полезной нагрузки
|
||||
void setPayloadSize(int size);
|
||||
|
||||
//! Set header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~english Set header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~russian Установить данные заголовка
|
||||
void setHeader(const PIByteArray & data);
|
||||
|
||||
//! Set footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~english Set footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~russian Установить данные окончания
|
||||
void setFooter(const PIByteArray & data);
|
||||
|
||||
//! Set timeout, used for PIPacketExtractor::Timeout algorithm
|
||||
//! \~english Set timeout, used for PIPacketExtractor::Timeout algorithm
|
||||
//! \~russian Установить таймаут
|
||||
void setTimeout(PISystemTime tm) { setProperty("timeout", tm); }
|
||||
|
||||
|
||||
//! Returns current extract algorithm
|
||||
//! \~english Returns current extract algorithm
|
||||
//! \~russian Возвращает текущий алгоритм извлечения
|
||||
SplitMode splitMode() const { return mode_; }
|
||||
|
||||
//! Returns current payload size, used for PIPacketExtractor::Header and PIPacketExtractor::Footer and PIPacketExtractor::Size
|
||||
//! algorithms
|
||||
//! \~english Returns current payload size
|
||||
//! \~russian Возвращает текущий размер полезной нагрузки
|
||||
int payloadSize() const { return dataSize; }
|
||||
|
||||
//! Returns current header data, used for PIPacketExtractor::Header and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~english Returns current header data
|
||||
//! \~russian Возвращает текущие данные заголовка
|
||||
PIByteArray header() const { return src_header; }
|
||||
|
||||
//! Returns current footer data, used for PIPacketExtractor::Footer and PIPacketExtractor::HeaderAndFooter algorithms
|
||||
//! \~english Returns current footer data
|
||||
//! \~russian Возвращает текущие данные окончания
|
||||
PIByteArray footer() const { return src_footer; }
|
||||
|
||||
//! Returns current timeout in milliseconds, used for PIPacketExtractor::Timeout algorithm
|
||||
//! \~english Returns current timeout in milliseconds
|
||||
//! \~russian Возвращает текущий таймаут в миллисекундах
|
||||
PISystemTime timeout() const { return time_; }
|
||||
|
||||
//! Returns missed by validating functions bytes count
|
||||
//! \~english Returns missed by validating functions bytes count
|
||||
//! \~russian Возвращает количество байт, пропущенных функциями проверки
|
||||
ullong missedBytes() const { return missed; }
|
||||
|
||||
//! Add data to extractor, raise \a packetReceived() if packet is ready
|
||||
//! \~english Add data to extractor, raise \a packetReceived() if packet is ready
|
||||
//! \~russian Добавить данные в экстрактор, вызвать \a packetReceived() если пакет готов
|
||||
void appendData(const uchar * d, int s) { threadedRead(d, s); }
|
||||
|
||||
//! Add data to extractor, raise \a packetReceived() if packet is ready
|
||||
//! \~english Add data to extractor, raise \a packetReceived() if packet is ready
|
||||
//! \~russian Добавить данные в экстрактор, вызвать \a packetReceived() если пакет готов
|
||||
void appendData(const PIByteArray & data) { threadedRead(data.data(), data.size_s()); }
|
||||
|
||||
EVENT2(packetReceived, const uchar *, data, int, size);
|
||||
|
||||
@@ -69,6 +69,8 @@
|
||||
*
|
||||
**/
|
||||
|
||||
//! \~english Template helper class to automate structs receive
|
||||
//! \~russian Шаблонный класс для автоматизации приема структур
|
||||
template<typename Key>
|
||||
class PIParseHelper {
|
||||
public:
|
||||
|
||||
@@ -33,45 +33,65 @@
|
||||
|
||||
class PIIODevice;
|
||||
|
||||
//! \~english Stream packer configuration
|
||||
//! \~russian Конфигурация упаковщика потока
|
||||
class PIStreamPackerConfig: public PIEthUtilBase {
|
||||
friend class PIStreamPacker;
|
||||
|
||||
public:
|
||||
//! \~english Constructs default configuration
|
||||
//! \~russian Создает конфигурацию по умолчанию
|
||||
PIStreamPackerConfig() {
|
||||
crypt_size = false;
|
||||
crypt_size = false;
|
||||
aggressive_optimization = true;
|
||||
max_packet_size = 1400;
|
||||
packet_sign = 0xAFBE;
|
||||
}
|
||||
|
||||
//! Set maximum size of single packet
|
||||
//! \~english Set maximum size of single packet
|
||||
//! \~russian Установить максимальный размер одного пакета
|
||||
void setMaxPacketSize(int max_size) { max_packet_size = max_size; }
|
||||
|
||||
//! Returns maximum size of single packet, default 1400 bytes
|
||||
//! \~english Returns maximum size of single packet, default 1400 bytes
|
||||
//! \~russian Возвращает максимальный размер одного пакета, по умолчанию 1400 байт
|
||||
int maxPacketSize() const { return max_packet_size; }
|
||||
|
||||
//! Set packet sinature
|
||||
//! \~english Set packet signature
|
||||
//! \~russian Установить подпись пакета
|
||||
void setPacketSign(ushort sign_) { packet_sign = sign_; }
|
||||
|
||||
//! Returns packet sinature, default 0xAFBE
|
||||
//! \~english Returns packet signature, default 0xAFBE
|
||||
//! \~russian Возвращает подпись пакета, по умолчанию 0xAFBE
|
||||
ushort packetSign() const { return packet_sign; }
|
||||
|
||||
//! Set receive aggressive optimization. If yes then %PIStreamPacker doesn`t
|
||||
//! check every byte in incoming stream but check only begin of each read()
|
||||
//! result. Default is \b true.
|
||||
//! \~english Set receive aggressive optimization. If yes then %PIStreamPacker doesn`t check every byte in incoming stream but check
|
||||
//! only begin of each read() result. Default is \b true.
|
||||
//! \~russian Установить агрессивную оптимизацию приема. Если да, то %PIStreamPacker не проверяет каждый байт во входящем потоке, а
|
||||
//! только начало каждого результата read(). По умолчанию \b true.
|
||||
void setaAggressiveOptimization(bool yes) { aggressive_optimization = yes; }
|
||||
|
||||
//! Returns aggressive optimization
|
||||
//! \~english Returns aggressive optimization
|
||||
//! \~russian Возвращает агрессивную оптимизацию
|
||||
bool aggressiveOptimization() const { return aggressive_optimization; }
|
||||
|
||||
//! \~english Check if crypt size enabled
|
||||
//! \~russian Проверить, включен ли размер шифрования
|
||||
bool cryptSizeEnabled() const { return crypt_size; }
|
||||
|
||||
//! \~english Set crypt size enabled
|
||||
//! \~russian Установить включенный размер шифрования
|
||||
void setCryptSizeEnabled(bool on) { crypt_size = on; }
|
||||
|
||||
//! Get configuration
|
||||
//! \~english Get configuration
|
||||
//! \~russian Получить конфигурацию
|
||||
const PIStreamPackerConfig & configuration() const { return *this; }
|
||||
|
||||
//! \~english Get configuration
|
||||
//! \~russian Получить конфигурацию
|
||||
PIStreamPackerConfig & configuration() { return *this; }
|
||||
|
||||
//! Apply configuration
|
||||
//! \~english Apply configuration
|
||||
//! \~russian Применить конфигурацию
|
||||
void setConfiguration(const PIStreamPackerConfig & config) { *this = config; }
|
||||
|
||||
private:
|
||||
@@ -81,31 +101,40 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Simple packet wrap around any PIIODevice
|
||||
//! \~russian Простая фрагментация пакетов, использует любой PIIODevice
|
||||
class PIP_IO_UTILS_EXPORT PIStreamPacker
|
||||
: public PIObject
|
||||
, public PIStreamPackerConfig {
|
||||
PIOBJECT(PIStreamPacker)
|
||||
|
||||
public:
|
||||
//! Contructs packer and try to assign \"dev\"
|
||||
//! \~english Constructs packer and try to assign "dev"
|
||||
//! \~russian Создает упаковщик и пытается присвоить "dev"
|
||||
PIStreamPacker(PIIODevice * dev = nullptr);
|
||||
|
||||
//! Returns progress of current packet receive in bytes
|
||||
//! \~english Returns progress of current packet receive in bytes
|
||||
//! \~russian Возвращает прогресс приема текущего пакета в байтах
|
||||
int receivePacketProgress() const { return packet.size_s(); }
|
||||
|
||||
//! \~english Clear all buffers
|
||||
//! \~russian Очистить все буферы
|
||||
void clear();
|
||||
|
||||
//! Prepare data for send and raise \a sendRequest() events
|
||||
//! \~english Prepare data for send and raise \a sendRequest() events
|
||||
//! \~russian Подготовить данные для отправки и вызвать события \a sendRequest()
|
||||
void send(const PIByteArray & data);
|
||||
|
||||
//! Receive data part. If packet is ready, raise \a packetReceiveEvent() event
|
||||
//! and \a packetReceived() virtual method
|
||||
//! \~english Receive data part. If packet is ready, raise \a packetReceiveEvent() event and \a packetReceived() virtual method
|
||||
//! \~russian Принять часть данных. Если пакет готов, вызвать событие \a packetReceiveEvent() и виртуальный метод \a packetReceived()
|
||||
void received(const PIByteArray & data);
|
||||
|
||||
EVENT_HANDLER2(void, received, const uchar *, readed, ssize_t, size);
|
||||
|
||||
//! Connect \"dev\" \a PIIODevice::threadedReadEvent() event to \a received() handler
|
||||
//! and \a sendRequest() event to \"dev\" \a PIIODevice::write() handler
|
||||
//! \~english Connect "dev" \a PIIODevice::threadedReadEvent() event to \a received() handler and \a sendRequest() event to "dev" \a
|
||||
//! PIIODevice::write() handler
|
||||
//! \~russian Подключить событие \a PIIODevice::threadedReadEvent() устройства "dev" к обработчику \a received() и событие \a
|
||||
//! sendRequest() к обработчику \a PIIODevice::write()
|
||||
void assignDevice(PIIODevice * dev);
|
||||
|
||||
EVENT1(packetReceiveEvent, PIByteArray &, data);
|
||||
|
||||
@@ -1,15 +1,25 @@
|
||||
/*! \file piliterals.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english C++11 literals
|
||||
* \~russian C++11 суффиксы
|
||||
*
|
||||
* \~\details
|
||||
* \~english
|
||||
* Include all literals_*.h files
|
||||
* \~russian
|
||||
* Включает все файлы literals_*.h
|
||||
*/
|
||||
//! \addtogroup Core
|
||||
//! \{}
|
||||
//! \file piliterals.h
|
||||
//! \brief C++11 user-defined literals
|
||||
//! \~english C++11 user-defined literals for PIP library types
|
||||
//! \~russian C++11 пользовательские литералы для типов библиотеки PIP
|
||||
//! \details
|
||||
//! \~english
|
||||
//! Includes all literals_*.h files providing user-defined literals (UDL) for:
|
||||
//! * PIByteArray (hex, base64)
|
||||
//! * Bytes (KB, MB, GB, TB, PB, KiB, MiB, GiB, TiB, PiB)
|
||||
//! * PIString (ASCII, UTF-8)
|
||||
//! * PIRegularExpression (regex, glob)
|
||||
//! * PISystemTime (d, h, m, s, ms, us, ns, Hz, KHz, MHz, GHz)
|
||||
//! \~russian
|
||||
//! Включает все файлы literals_*.h с пользовательскими литералами (UDL) для:
|
||||
//! * PIByteArray (hex, base64)
|
||||
//! * Bytes (KB, MB, GB, TB, PB, KiB, MiB, GiB, TiB, PiB)
|
||||
//! * PIString (ASCII, UTF-8)
|
||||
//! * PIRegularExpression (regex, glob)
|
||||
//! * PISystemTime (d, h, m, s, ms, us, ns, Hz, KHz, MHz, GHz)
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
C++11 literals
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file piluaprogram.h
|
||||
* \ingroup Lua
|
||||
* \~\brief
|
||||
* \~english Lua Program
|
||||
* \~russian Программа Lua
|
||||
*/
|
||||
//! \addtogroup Lua
|
||||
//! \{
|
||||
//! \file piluaprogram.h
|
||||
//! \brief
|
||||
//! \~english Lua Program wrapper
|
||||
//! \~russian Обёртка программы Lua
|
||||
//! \details
|
||||
//! \~english Provides interface for loading and executing Lua scripts using LuaBridge
|
||||
//! \~russian Предоставляет интерфейс для загрузки и выполнения скриптов Lua с использованием LuaBridge
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PILuaProgram
|
||||
@@ -29,21 +33,46 @@
|
||||
#include "pip_lua.h"
|
||||
#include "pip_lua_export.h"
|
||||
|
||||
//! \~english Lua Program class provides interface for loading and executing Lua scripts
|
||||
//! \~russian Класс PILuaProgram предоставляет интерфейс для загрузки и выполнения скриптов Lua
|
||||
class PIP_LUA_EXPORT PILuaProgram {
|
||||
public:
|
||||
//! Constructs an empty PILuaProgram, initialize Lua context
|
||||
//! \~english Constructs an empty PILuaProgram and initializes Lua context
|
||||
//! \~russian Создаёт пустой PILuaProgram и инициализирует контекст Lua
|
||||
PILuaProgram();
|
||||
|
||||
//! Load Lua script from PIString
|
||||
//! \~english Loads Lua script from PIString
|
||||
//! \~russian Загружает скрипт Lua из PIString
|
||||
//! \param script
|
||||
//! \~english The Lua script to load
|
||||
//! \~russian Загружаемый скрипт Lua
|
||||
//! \return
|
||||
//! \~english true if script loaded successfully
|
||||
//! \~russian true, если скрипт успешно загружен
|
||||
bool load(const PIString & script);
|
||||
|
||||
//! Execute script
|
||||
//! \~english Prepares the loaded script for execution
|
||||
//! \~russian Подготавливает загруженный скрипт к выполнению
|
||||
//! \return
|
||||
//! \~english true if preparation successful
|
||||
//! \~russian true, если подготовка успешна
|
||||
bool prepare();
|
||||
|
||||
//! Get Lua Object or Function
|
||||
//! \~english Gets a global Lua object or function by name
|
||||
//! \~russian Получает глобальный объект или функцию Lua по имени
|
||||
//! \param name
|
||||
//! \~english Name of the global object or function
|
||||
//! \~russian Имя глобального объекта или функции
|
||||
//! \return
|
||||
//! \~english LuaRef to the global object or function
|
||||
//! \~russian LuaRef на глобальный объект или функцию
|
||||
luabridge::LuaRef getGlobal(const PIString & name);
|
||||
|
||||
//! Return Lua global namespace
|
||||
//! \~english Returns the global namespace of the Lua state
|
||||
//! \~russian Возвращает глобальное пространство имён состояния Lua
|
||||
//! \return
|
||||
//! \~english Namespace object representing global scope
|
||||
//! \~russian Объект Namespace, представляющий глобальную область видимости
|
||||
luabridge::Namespace getGlobalNamespace();
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file pievaluator.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Mathematic expressions calculator
|
||||
* \~russian Вычислитель математических выражений
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file pievaluator.h
|
||||
//! \brief
|
||||
//! \~english Mathematic expressions calculator
|
||||
//! \~russian Вычислитель математических выражений
|
||||
//! \details
|
||||
//! \~english Evaluator for parsing and calculating mathematical expressions
|
||||
//! \~russian Вычислитель для разбора и вычисления математических выражений
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Evaluator designed for stream calculations
|
||||
@@ -180,36 +184,72 @@ struct PIP_EXPORT Variable {
|
||||
⋁ |
|
||||
*/
|
||||
|
||||
//! Content container for variables and functions
|
||||
//! \~\english Container for variables and functions of the evaluator
|
||||
//! \~russian Контейнер для переменных и функций вычислителя
|
||||
class PIP_EXPORT PIEvaluatorContent {
|
||||
friend class PIEvaluator;
|
||||
BINARY_STREAM_FRIEND(PIEvaluatorContent);
|
||||
|
||||
public:
|
||||
//! Constructs an empty evaluator content
|
||||
PIEvaluatorContent();
|
||||
~PIEvaluatorContent() { ; }
|
||||
|
||||
//! Add function with specified name and argument count
|
||||
//! \~english Add function with name and default 1 argument
|
||||
//! \~russian Добавить функцию с указанным именем и количеством аргументов (по умолчанию 1)
|
||||
void addFunction(const PIString & name, int args = 1);
|
||||
//! Add variable with specified name and value
|
||||
//! \~english Add variable with name and optional value, returns variable index
|
||||
//! \~russian Добавить переменную с указанным именем и значением, возвращает индекс переменной
|
||||
int addVariable(const PIString & name, const complexd & val = 0.);
|
||||
//! Add custom function with handler
|
||||
//! \~english Add custom function with name, argument count and handler function
|
||||
//! \~russian Добавить пользовательскую функцию с обработчиком
|
||||
void addCustomFunction(const PIString & name, int args_count, PIEvaluatorTypes::FuncHanlder func);
|
||||
//! Get number of functions
|
||||
int functionsCount() const { return functions.size(); }
|
||||
//! Get number of variables
|
||||
int variablesCount() const { return variables.size(); }
|
||||
//! Get number of custom variables
|
||||
int customVariablesCount() const;
|
||||
//! Find function index by name
|
||||
int findFunction(const PIString & name) const;
|
||||
//! Find variable index by name
|
||||
int findVariable(const PIString & var_name) const;
|
||||
//! Get function by index
|
||||
PIEvaluatorTypes::Function function(int index);
|
||||
//! Get variable by index
|
||||
PIEvaluatorTypes::Variable variable(int index);
|
||||
//! Get function by name
|
||||
PIEvaluatorTypes::Function function(const PIString & name) { return function(findFunction(name)); }
|
||||
//! Get variable by name
|
||||
PIEvaluatorTypes::Variable variable(const PIString & name) { return variable(findVariable(name)); }
|
||||
//! Get custom variable by index
|
||||
PIEvaluatorTypes::Variable customVariable(int index);
|
||||
//! Set variable value by index
|
||||
//! \~english Set variable value by index, returns true on success
|
||||
//! \~russian Установить значение переменной по индексу, возвращает true при успехе
|
||||
bool setVariableValue(int index, complexd new_value);
|
||||
//! Set variable value by name
|
||||
//! \~english Set variable value by name, returns true on success
|
||||
//! \~russian Установить значение переменной по имени, возвращает true при успехе
|
||||
bool setVariableValue(const PIString & var_name, const complexd & new_value) {
|
||||
return setVariableValue(findVariable(var_name), new_value);
|
||||
}
|
||||
//! Set variable name by index
|
||||
bool setVariableName(int index, const PIString & new_name);
|
||||
//! Set variable name by name
|
||||
bool setVariableName(const PIString & var_name, const PIString & new_name) { return setVariableName(findVariable(var_name), new_name); }
|
||||
//! Clear all custom variables
|
||||
void clearCustomVariables();
|
||||
//! Get base function type by name
|
||||
PIEvaluatorTypes::BaseFunctions getBaseFunction(const PIString & name);
|
||||
|
||||
//! Dump content to console for debugging
|
||||
//! \~english Print all functions and variables to console
|
||||
//! \~russian Вывести все функции и переменные в консоль
|
||||
void dump();
|
||||
|
||||
private:
|
||||
@@ -219,6 +259,9 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! Main evaluator class for parsing and calculating mathematical expressions
|
||||
//! \~\english Main class for parsing and evaluating mathematical expressions
|
||||
//! \~russian Главный класс для разбора и вычисления математических выражений
|
||||
class PIP_EXPORT PIEvaluator {
|
||||
public:
|
||||
//! Constructs an empty evaluator
|
||||
|
||||
@@ -43,98 +43,99 @@ public:
|
||||
PIPoint<Type> p0;
|
||||
PIPoint<Type> p1;
|
||||
|
||||
//! \~russian
|
||||
//! Пустой конструктор.
|
||||
//! \~english Default constructor.
|
||||
//! \~russian Пустой конструктор.
|
||||
//! \details
|
||||
//! При выполнении пустого конструктора координаты не изменяются.
|
||||
//! Начало и конец совпадают.
|
||||
//! \~english Creates an empty line where start and end points coincide.
|
||||
//! \~russian При выполнении пустого конструктора координаты не изменяются. Начало и конец совпадают.
|
||||
PILine() {}
|
||||
|
||||
//! \~russian
|
||||
//! Создает линию по двум принятым точкам \a PIPoint начала и конца.
|
||||
//! \~english Creates a line from two points.
|
||||
//! \~russian Создает линию по двум принятым точкам \a PIPoint начала и конца.
|
||||
PILine(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
|
||||
p0 = p0_;
|
||||
p1 = p1_;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создает линию по принятым координатам начала и конца.
|
||||
//! \~english Creates a line from coordinates.
|
||||
//! \~russian Создает линию по принятым координатам начала и конца.
|
||||
PILine(Type x0, Type y0, Type x1, Type y1) {
|
||||
p0.set(x0, y0);
|
||||
p1.set(x1, y1);
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
|
||||
//! \~english Set new coordinates from two points.
|
||||
//! \~russian Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
|
||||
PILine<Type> & set(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
|
||||
p0 = p0_;
|
||||
p1 = p1_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Задать новые координаты начала и конца.
|
||||
//! \~english Set new coordinates.
|
||||
//! \~russian Задать новые координаты начала и конца.
|
||||
PILine<Type> & set(Type x0, Type y0, Type x1, Type y1) {
|
||||
p0.set(x0, y0);
|
||||
p1.set(x1, y1);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Проверить на совпадение координат начала и конца.
|
||||
//! \~english Check if start and end points coincide.
|
||||
//! \~russian Проверить на совпадение координат начала и конца.
|
||||
bool isEmpty() const { return (p0 == p1); }
|
||||
|
||||
//! \~russian
|
||||
//! Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
|
||||
//! \~english Calculate width of the rectangle whose diagonal is this line.
|
||||
//! \~russian Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
|
||||
Type width() const { return piAbs<Type>(p1.x - p0.x); }
|
||||
|
||||
//! \~russian
|
||||
//! Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
|
||||
//! \~english Calculate height of the rectangle whose diagonal is this line.
|
||||
//! \~russian Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
|
||||
Type height() const { return piAbs<Type>(p1.y - p0.y); }
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на \a x, \a y.
|
||||
//! \~english Translate line by x and y.
|
||||
//! \~russian Сдвинуть линию на \a x, \a y.
|
||||
PILine<Type> & translate(Type x, Type y) {
|
||||
p0.translate(x, y);
|
||||
p1.translate(x, y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
//! \~english Translate line by point coordinates.
|
||||
//! \~russian Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
PILine<Type> & translate(const PIPoint<Type> & p) {
|
||||
p0.translate(p);
|
||||
p1.translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Создать копию отрезка и сдвинуть её на `x` и `y`.
|
||||
//! \~english Create a copy of the line and translate it by x and y.
|
||||
//! \~russian Создать копию отрезка и сдвинуть её на `x` и `y`.
|
||||
PILine<Type> translated(Type x, Type y) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(x, y);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
//! \~english Create a copy of the line and translate it by point coordinates.
|
||||
//! \~russian Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
PILine<Type> translated(const PIPoint<Type> & p) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(p);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на \a x, \a y.
|
||||
//! \~english Translate line by x and y. Alias for \a translate().
|
||||
//! \~russian Сдвинуть линию на \a x, \a y.
|
||||
//! \details Является копией метода \a translate().
|
||||
PILine<Type> & move(Type x, Type y) { return translate(x, y); }
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
//! \~english Translate line by point coordinates. Alias for \a translate().
|
||||
//! \~russian Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
//! \details Является копией метода \a translate().
|
||||
PILine<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на \a x, \a y.
|
||||
//! \~english Create a copy of the line and translate it by x and y. Alias for \a translated().
|
||||
//! \~russian Создать копию отрезка и сдвинуть её на \a x, \a y.
|
||||
//! \details Является копией метода \a translated().
|
||||
PILine<Type> moved(Type x, Type y) const {
|
||||
PILine<Type> l(*this);
|
||||
@@ -142,8 +143,8 @@ public:
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
//! \~english Create a copy of the line and translate it by point coordinates. Alias for \a translated().
|
||||
//! \~russian Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
//! \details Является копией метода \a translated().
|
||||
PILine<Type> moved(const PIPoint<Type> & p) const {
|
||||
PILine<Type> l(*this);
|
||||
@@ -151,31 +152,40 @@ public:
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~english Translate line by x value on both coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
|
||||
void operator+=(Type x) { translate(x, x); }
|
||||
|
||||
//! \~english Translate line by point coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
void operator+=(const PIPoint<Type> & p) { translate(p); }
|
||||
|
||||
//! \~english Translate line by negative x value on both coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
|
||||
void operator-=(Type x) { translate(-x, -x); }
|
||||
|
||||
//! \~english Translate line by negative point coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
void operator-=(const PIPoint<Type> & p) { translate(-p); }
|
||||
|
||||
//! \~english Translate line by point coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
PILine<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
|
||||
|
||||
//! \~english Translate line by negative point coordinates.
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
PILine<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
|
||||
|
||||
//! \~english Check equality of two lines.
|
||||
//! \~russian Проверить равенство координат двух отрезков.
|
||||
bool operator==(const PILine<Type> & r) const { return (p0 == r.p0 && p1 == r.p1); }
|
||||
|
||||
//! \~english Check inequality of two lines.
|
||||
//! \~russian Проверить неравенство координат двух отрезков.
|
||||
bool operator!=(const PILine<Type> & r) const { return (p1 != r.p1 || p1 != r.p1); }
|
||||
};
|
||||
|
||||
//! \~english Stream output operator for PILine.
|
||||
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PILine<Type> & v) {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file pimathbase.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Basic mathematical functions and defines
|
||||
* \~russian Базовые математические функции и дефайны
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file pimathbase.h
|
||||
//! \brief
|
||||
//! \~english Basic mathematical functions and defines
|
||||
//! \~russian Базовые математические функции и дефайны
|
||||
//! \details
|
||||
//! \~english Common mathematical constants, conversion functions and utility functions
|
||||
//! \~russian Общие математические константы, функции преобразования и утилиты
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Basic mathematical functions and defines
|
||||
@@ -114,11 +118,29 @@ inline double sinc(const double & v) {
|
||||
return sin(t) / t;
|
||||
}
|
||||
|
||||
//! Bessel function of the first kind of order 0
|
||||
//! \~english Bessel function J0(x)
|
||||
//! \~russian Функция Бесселя первого рода порядка 0
|
||||
PIP_EXPORT double piJ0(const double & v);
|
||||
//! Bessel function of the first kind of order 1
|
||||
//! \~english Bessel function J1(x)
|
||||
//! \~russian Функция Бесселя первого рода порядка 1
|
||||
PIP_EXPORT double piJ1(const double & v);
|
||||
//! Bessel function of the first kind of order n
|
||||
//! \~english Bessel function Jn(n, x)
|
||||
//! \~russian Функция Бесселя первого рода порядка n
|
||||
PIP_EXPORT double piJn(int n, const double & v);
|
||||
//! Bessel function of the second kind of order 0
|
||||
//! \~english Bessel function Y0(x)
|
||||
//! \~russian Функция Бесселя второго рода порядка 0
|
||||
PIP_EXPORT double piY0(const double & v);
|
||||
//! Bessel function of the second kind of order 1
|
||||
//! \~english Bessel function Y1(x)
|
||||
//! \~russian Функция Бесселя второго рода порядка 1
|
||||
PIP_EXPORT double piY1(const double & v);
|
||||
//! Bessel function of the second kind of order n
|
||||
//! \~english Bessel function Yn(n, x)
|
||||
//! \~russian Функция Бесселя второго рода порядка n
|
||||
PIP_EXPORT double piYn(int n, const double & v);
|
||||
|
||||
// clang-format off
|
||||
@@ -129,24 +151,45 @@ inline constexpr float toDeg(float rad) {return rad * M_180_PI;}
|
||||
inline constexpr double toDeg(double rad) {return rad * M_180_PI;}
|
||||
inline constexpr ldouble toDeg(ldouble rad) {return rad * M_180_PI;}
|
||||
// clang-format on
|
||||
|
||||
//! Square of a value
|
||||
//! \~english Returns the square of value v (v * v)
|
||||
//! \~russian Возвращает квадрат значения v (v * v)
|
||||
template<typename T>
|
||||
inline constexpr T sqr(const T & v) {
|
||||
return v * v;
|
||||
}
|
||||
|
||||
//! Convert linear value to decibels
|
||||
//! \~english Convert linear value to decibels: 10 * log10(val)
|
||||
//! \~russian Преобразовать линейное значение в децибелы: 10 * log10(val)
|
||||
template<typename T>
|
||||
inline constexpr T toDb(T val) {
|
||||
return T(10.) * std::log10(val);
|
||||
}
|
||||
|
||||
//! Convert decibels to linear value
|
||||
//! \~english Convert decibels to linear value: 10^(val/10)
|
||||
//! \~russian Преобразовать децибелы в линейное значение: 10^(val/10)
|
||||
template<typename T>
|
||||
inline constexpr T fromDb(T val) {
|
||||
return std::pow(T(10.), val / T(10.));
|
||||
}
|
||||
|
||||
// [-1 ; 1]
|
||||
//! Generate random double in range [-1, 1]
|
||||
//! \~english Returns random double in range [-1, 1]
|
||||
//! \~russian Генерирует случайное число double в диапазоне [-1, 1]
|
||||
PIP_EXPORT double randomd();
|
||||
// [-1 ; 1] normal
|
||||
//! Generate random double with normal (Gaussian) distribution
|
||||
//! \~english Returns random double with normal distribution, mean=dv, stddev=sv
|
||||
//! \~russian Генерирует случайное число double с нормальным распределением, среднее=dv, стандартное отклонение=sv
|
||||
PIP_EXPORT double randomn(double dv = 0., double sv = 1.);
|
||||
|
||||
//! Absolute value of vector elements
|
||||
//! \~english Returns vector with absolute values of each element
|
||||
//! \~russian Возвращает вектор с абсолютными значениями каждого элемента
|
||||
template<typename T>
|
||||
inline PIVector<T> piAbs(const PIVector<T> & v) {
|
||||
PIVector<T> result;
|
||||
@@ -157,6 +200,9 @@ inline PIVector<T> piAbs(const PIVector<T> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! Normalize angle to [0, 360) range (in-place)
|
||||
//! \~english Normalizes angle to range [0, 360) degrees
|
||||
//! \~russian Нормализует угол в диапазон [0, 360) градусов (на месте)
|
||||
template<typename T>
|
||||
void normalizeAngleDeg360(T & a) {
|
||||
while (a < 0.)
|
||||
@@ -164,6 +210,9 @@ void normalizeAngleDeg360(T & a) {
|
||||
while (a > 360.)
|
||||
a -= 360.;
|
||||
}
|
||||
//! Normalize angle to [0, 360) range
|
||||
//! \~english Returns angle normalized to range [0, 360) degrees
|
||||
//! \~russian Возвращает угол нормализованный в диапазон [0, 360) градусов
|
||||
template<typename T>
|
||||
double normalizedAngleDeg360(T a) {
|
||||
normalizeAngleDeg360(a);
|
||||
@@ -171,6 +220,9 @@ double normalizedAngleDeg360(T a) {
|
||||
}
|
||||
|
||||
|
||||
//! Normalize angle to (-180, 180] range (in-place)
|
||||
//! \~english Normalizes angle to range (-180, 180] degrees
|
||||
//! \~russian Нормализует угол в диапазон (-180, 180] градусов (на месте)
|
||||
template<typename T>
|
||||
void normalizeAngleDeg180(T & a) {
|
||||
while (a < -180.)
|
||||
@@ -178,6 +230,9 @@ void normalizeAngleDeg180(T & a) {
|
||||
while (a > 180.)
|
||||
a -= 360.;
|
||||
}
|
||||
//! Normalize angle to (-180, 180] range
|
||||
//! \~english Returns angle normalized to range (-180, 180] degrees
|
||||
//! \~russian Возвращает угол нормализованный в диапазон (-180, 180] градусов
|
||||
template<typename T>
|
||||
double normalizedAngleDeg180(T a) {
|
||||
normalizeAngleDeg180(a);
|
||||
@@ -185,6 +240,13 @@ double normalizedAngleDeg180(T a) {
|
||||
}
|
||||
|
||||
|
||||
//! Ordinary Least Squares linear regression
|
||||
//! \~english Calculates linear regression coefficients using OLS method
|
||||
//! \~russian Вычисляет коэффициенты линейной регрессии методом наименьших квадратов
|
||||
//! \param input Vector of (x, y) pairs
|
||||
//! \param out_a Output pointer for slope coefficient (a), can be nullptr
|
||||
//! \param out_b Output pointer for intercept coefficient (b), can be nullptr
|
||||
//! \return true on success
|
||||
template<typename T>
|
||||
bool OLS_Linear(const PIVector<PIPair<T, T>> & input, T * out_a, T * out_b) {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
@@ -207,6 +269,14 @@ bool OLS_Linear(const PIVector<PIPair<T, T>> & input, T * out_a, T * out_b) {
|
||||
}
|
||||
|
||||
|
||||
//! Weighted Least Squares linear regression
|
||||
//! \~english Calculates linear regression coefficients using WLS method
|
||||
//! \~russian Вычисляет коэффициенты линейной регрессии методом взвешенных наименьших квадратов
|
||||
//! \param input Vector of (x, y) pairs
|
||||
//! \param weights Vector of weights for each point
|
||||
//! \param out_a Output pointer for slope coefficient (a), can be nullptr
|
||||
//! \param out_b Output pointer for intercept coefficient (b), can be nullptr
|
||||
//! \return true on success
|
||||
template<typename T>
|
||||
bool WLS_Linear(const PIVector<PIPair<T, T>> & input, const PIVector<T> & weights, T * out_a, T * out_b) {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
|
||||
@@ -32,9 +32,9 @@
|
||||
|
||||
/// Matrix templated
|
||||
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < Rows; ++r) \
|
||||
for (uint c = 0; c < Cols; ++c)
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < Rows; ++r) \
|
||||
for (uint c = 0; c < Cols; ++c)
|
||||
#define PIMM_FOR_C for (uint i = 0; i < Cols; ++i)
|
||||
#define PIMM_FOR_R for (uint i = 0; i < Rows; ++i)
|
||||
|
||||
@@ -891,9 +891,9 @@ class PIMathMatrix;
|
||||
|
||||
/// Matrix
|
||||
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < _V2D::rows_; ++r) \
|
||||
for (uint c = 0; c < _V2D::cols_; ++c)
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < _V2D::rows_; ++r) \
|
||||
for (uint c = 0; c < _V2D::cols_; ++c)
|
||||
#define PIMM_FOR_A for (uint i = 0; i < _V2D::mat.size(); ++i)
|
||||
#define PIMM_FOR_C for (uint i = 0; i < _V2D::cols_; ++i)
|
||||
#define PIMM_FOR_R for (uint i = 0; i < _V2D::rows_; ++i)
|
||||
|
||||
@@ -1,6 +1,13 @@
|
||||
/*! \file pimathsolver.h
|
||||
* \brief PIMathSolver
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file pimathsolver.h
|
||||
//! \brief
|
||||
//! \~english Mathematical solver for differential equations
|
||||
//! \~russian Математический решатель дифференциальных уравнений
|
||||
//! \details
|
||||
//! \~english Solver for ordinary differential equations using various numerical methods
|
||||
//! \~russian Решатель обыкновенных дифференциальных уравнений с использованием различных численных методов
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIMathSolver
|
||||
@@ -27,48 +34,83 @@
|
||||
|
||||
/// Differential evaluations
|
||||
|
||||
//! Transfer function representation
|
||||
//! \~english Structure representing transfer function with numerator and denominator coefficients
|
||||
//! \~russian Структура, представляющая передаточную функцию с коэффициентами числителя и знаменателя
|
||||
struct PIP_EXPORT TransferFunction {
|
||||
PIVector<double> vector_Bm, vector_An;
|
||||
};
|
||||
|
||||
//! Mathematical solver for differential equations
|
||||
//! \~\english Solver for ordinary differential equations using various numerical methods
|
||||
//! \~russian Решатель обыкновенных дифференциальных уравнений
|
||||
class PIP_EXPORT PIMathSolver {
|
||||
public:
|
||||
//! Solving methods for differential equations
|
||||
enum Method {
|
||||
Global = -1,
|
||||
Eyler_1 = 01,
|
||||
Eyler_2 = 02,
|
||||
EylerKoshi = 03,
|
||||
RungeKutta_4 = 14,
|
||||
AdamsBashfortMoulton_2 = 22,
|
||||
AdamsBashfortMoulton_3 = 23,
|
||||
AdamsBashfortMoulton_4 = 24,
|
||||
PolynomialApproximation_2 = 32,
|
||||
PolynomialApproximation_3 = 33,
|
||||
PolynomialApproximation_4 = 34,
|
||||
PolynomialApproximation_5 = 35
|
||||
Global = -1, //!< Use global method
|
||||
Eyler_1 = 01, //!< Euler method (first order)
|
||||
Eyler_2 = 02, //!< Euler method (second order)
|
||||
EylerKoshi = 03, //!< Euler-Cauchy method
|
||||
RungeKutta_4 = 14, //!< Runge-Kutta 4th order
|
||||
AdamsBashfortMoulton_2 = 22, //!< Adams-Bashforth-Moulton 2nd order
|
||||
AdamsBashfortMoulton_3 = 23, //!< Adams-Bashforth-Moulton 3rd order
|
||||
AdamsBashfortMoulton_4 = 24, //!< Adams-Bashforth-Moulton 4th order
|
||||
PolynomialApproximation_2 = 32, //!< Polynomial approximation 2nd order
|
||||
PolynomialApproximation_3 = 33, //!< Polynomial approximation 3rd order
|
||||
PolynomialApproximation_4 = 34, //!< Polynomial approximation 4th order
|
||||
PolynomialApproximation_5 = 35 //!< Polynomial approximation 5th order
|
||||
};
|
||||
|
||||
//! Constructs an empty solver
|
||||
PIMathSolver();
|
||||
|
||||
//! Solve differential equation with step h
|
||||
//! \~english Solve differential equation at point u with step h
|
||||
//! \~russian Решить дифференциальное уравнение в точке u с шагом h
|
||||
void solve(double u, double h);
|
||||
|
||||
//! Initialize from transfer function
|
||||
//! \~english Set up solver from transfer function coefficients
|
||||
//! \~russian Инициализировать решатель из коэффициентов передаточной функции
|
||||
void fromTF(const TransferFunction & TF);
|
||||
//! Set solving method
|
||||
//! \~english Set numerical method for solving
|
||||
//! \~russian Установить численный метод решения
|
||||
void setMethod(Method m) { method = m; }
|
||||
//! Set simulation time
|
||||
//! \~english Set simulation time
|
||||
//! \~russian Установить время моделирования
|
||||
void setTime(double time);
|
||||
|
||||
//! Solve using Euler method (1st order)
|
||||
void solveEyler1(double u, double h);
|
||||
//! Solve using Euler method (2nd order)
|
||||
void solveEyler2(double u, double h);
|
||||
//! Solve using Runge-Kutta 4th order
|
||||
void solveRK4(double u, double h);
|
||||
//! Solve using Adams-Bashforth-Moulton 2nd order
|
||||
void solveABM2(double u, double h);
|
||||
//! Solve using Adams-Bashforth-Moulton 3rd order
|
||||
void solveABM3(double u, double h);
|
||||
//! Solve using Adams-Bashforth-Moulton 4th order
|
||||
void solveABM4(double u, double h);
|
||||
//! Solve using polynomial approximation
|
||||
void solvePA(double u, double h, uint deg);
|
||||
//! Solve using polynomial approximation 2nd order
|
||||
void solvePA2(double u, double h);
|
||||
//! Solve using polynomial approximation 3rd order
|
||||
void solvePA3(double u, double h);
|
||||
//! Solve using polynomial approximation 4th order
|
||||
void solvePA4(double u, double h);
|
||||
//! Solve using polynomial approximation 5th order
|
||||
void solvePA5(double u, double h);
|
||||
|
||||
//! Solution vector
|
||||
PIMathVectord X;
|
||||
//! Global default method
|
||||
static Method method_global;
|
||||
//! Description of available methods
|
||||
static const char methods_desc[];
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file pimathvector.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Math vector
|
||||
* \~russian Математический вектор
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file pimathvector.h
|
||||
//! \brief
|
||||
//! \~english Math vector
|
||||
//! \~russian Математический вектор
|
||||
//! \details
|
||||
//! \~english Fixed-size and dynamic mathematical vector implementations
|
||||
//! \~russian Реализации математических векторов фиксированного и динамического размера
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIMathVector
|
||||
@@ -40,6 +44,9 @@ class PIMathMatrixT;
|
||||
|
||||
#define PIMV_FOR for (uint i = 0; i < Size; ++i)
|
||||
|
||||
//! Fixed-size mathematical vector
|
||||
//! \~english Template class for fixed-size mathematical vector
|
||||
//! \~russian Шаблонный класс для математического вектора фиксированного размера
|
||||
template<uint Size, typename Type = double>
|
||||
class PIP_EXPORT PIMathVectorT {
|
||||
typedef PIMathVectorT<Size, Type> _CVector;
|
||||
@@ -360,6 +367,9 @@ typedef PIMathVectorT<4u, double> PIMathVectorT4d;
|
||||
|
||||
#define PIMV_FOR for (uint i = 0; i < c.size(); ++i)
|
||||
|
||||
//! Dynamic-size mathematical vector
|
||||
//! \~english Template class for dynamic-size mathematical vector
|
||||
//! \~russian Шаблонный класс для математического вектора динамического размера
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PIMathVector {
|
||||
typedef PIMathVector<Type> _CVector;
|
||||
|
||||
@@ -40,12 +40,15 @@ public:
|
||||
Type x;
|
||||
Type y;
|
||||
|
||||
//! \~english Creates a new point.
|
||||
//! \~russian Создает новую точку.
|
||||
PIPoint() { x = y = Type(); }
|
||||
|
||||
//! \~english Creates a new point with given coordinates.
|
||||
//! \~russian Создает новую точку с заданными координатами.
|
||||
PIPoint(Type x_, Type y_) { set(x_, y_); }
|
||||
|
||||
//! \~english Set new coordinates for the point.
|
||||
//! \~russian Задать новые координаты точке.
|
||||
PIPoint<Type> & set(Type x_, Type y_) {
|
||||
x = x_;
|
||||
@@ -53,6 +56,7 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Set new coordinates from another point.
|
||||
//! \~russian Задать новые координаты точке.
|
||||
PIPoint<Type> & set(const PIPoint<Type> & p) {
|
||||
x = p.x;
|
||||
@@ -60,6 +64,7 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Translate the point by x and y.
|
||||
//! \~russian Переместить точку.
|
||||
PIPoint<Type> & translate(Type x_, Type y_) {
|
||||
x += x_;
|
||||
@@ -67,6 +72,7 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Translate the point by another point.
|
||||
//! \~russian Переместить точку.
|
||||
PIPoint<Type> & translate(const PIPoint<Type> & p) {
|
||||
x += p.x;
|
||||
@@ -74,6 +80,7 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Create a copy of the point and translate it.
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
PIPoint<Type> translated(Type x_, Type y_) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
@@ -81,6 +88,7 @@ public:
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~english Create a copy of the point and translate it by another point.
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
PIPoint<Type> translated(const PIPoint<Type> & p) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
@@ -88,14 +96,17 @@ public:
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~english Translate the point. Alias for \a translate().
|
||||
//! \~russian Переместить точку.
|
||||
//! \details Является копией метода \a translate().
|
||||
PIPoint<Type> & move(Type x_, Type y_) { return translate(x_, y_); }
|
||||
|
||||
//! \~english Translate the point by another point. Alias for \a translate().
|
||||
//! \~russian Переместить точку.
|
||||
//! \details Является копией метода \a translate().
|
||||
PIPoint<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//! \~english Create a copy of the point and translate it. Alias for \a translated().
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \details Является копией метода \a translated().
|
||||
PIPoint<Type> moved(Type x_, Type y_) const {
|
||||
@@ -104,6 +115,7 @@ public:
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~english Create a copy of the point and translate it by another point. Alias for \a translated().
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \details Является копией метода \a translated().
|
||||
PIPoint<Type> moved(const PIPoint<Type> & p) const {
|
||||
@@ -112,65 +124,82 @@ public:
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~english Calculate angle in radians in polar coordinate system.
|
||||
//! \~russian Посчитать угол(радианы) в поолярной системе координат.
|
||||
double angleRad() const { return atan2(y, x); }
|
||||
|
||||
//! \~english Calculate angle in degrees in polar coordinate system.
|
||||
//! \~russian Посчитать угол(градусы) в поолярной системе координат.
|
||||
double angleDeg() const { return toDeg(atan2(y, x)); }
|
||||
|
||||
//! \~english Convert copy of point to polar coordinate system.
|
||||
//! \~russian Перевести копию точки в полярную систему координат.
|
||||
PIPoint<Type> toPolar(bool isDeg = false) const { return PIPoint<Type>(sqrt(x * x + y * y), isDeg ? angleDeg() : angleRad()); }
|
||||
|
||||
//! \~english Convert point from polar to cartesian coordinate system.
|
||||
//! \~russian Перевести копию точки из полярной системы координат в декартовую.
|
||||
static PIPoint<Type> fromPolar(const PIPoint<Type> & p) { return PIPoint<Type>(p.y * cos(p.x), p.y * sin(p.x)); }
|
||||
|
||||
//! \~russian
|
||||
//! Прибавить координаты второй точки и сохранить.
|
||||
//! \~english Add second point coordinates and save.
|
||||
//! \~russian Прибавить координаты второй точки и сохранить.
|
||||
//! \details Является копией метода \a translate().
|
||||
PIPoint<Type> & operator+=(const PIPoint<Type> & p) {
|
||||
translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Multiply coordinates by value.
|
||||
PIPoint<Type> & operator*=(Type v) {
|
||||
x *= v;
|
||||
y *= v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Divide coordinates by value.
|
||||
PIPoint<Type> & operator/=(Type v) {
|
||||
x /= v;
|
||||
y /= v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Add coordinates of two points.
|
||||
//! \~russian Сложить координаты двух точек.
|
||||
PIPoint<Type> operator+(const PIPoint<Type> & p) { return PIPoint<Type>(x + p.x, y + p.y); }
|
||||
|
||||
//! \~english Add value to both coordinates.
|
||||
//! \~russian Прибавить к координатам одинаковое значение.
|
||||
PIPoint<Type> operator+(const Type & p) { return PIPoint<Type>(x + p, y + p); }
|
||||
|
||||
//! \~english Subtract second point coordinates - get offset.
|
||||
//! \~russian Вычесть из координат координаты второй точки - найти смещение.
|
||||
PIPoint<Type> operator-(const PIPoint<Type> & p) { return PIPoint<Type>(x - p.x, y - p.y); }
|
||||
|
||||
//! \~english Subtract value from both coordinates.
|
||||
//! \~russian Вычесть из координат одинаковое значение.
|
||||
PIPoint<Type> operator-(const Type & p) { return PIPoint<Type>(x - p, y - p); }
|
||||
|
||||
//! \~english Invert point coordinates.
|
||||
//! \~russian Инвертировать координаты точки.
|
||||
PIPoint<Type> operator-() { return PIPoint<Type>(-x, -y); }
|
||||
|
||||
//! \~english Multiply point coordinates.
|
||||
//! \~russian Умножить координаты точки.
|
||||
PIPoint<Type> operator*(Type v) { return PIPoint<Type>(x * v, y * v); }
|
||||
|
||||
//! \~english Divide point coordinates.
|
||||
//! \~russian Делить координаты точки.
|
||||
PIPoint<Type> operator/(Type v) { return PIPoint<Type>(x / v, y / v); }
|
||||
|
||||
//! \~english Check equality of two points.
|
||||
//! \~russian Проверить равенство координат двух точек.
|
||||
bool operator==(const PIPoint<Type> & p) const { return (x == p.x && y == p.y); }
|
||||
|
||||
//! \~english Check inequality of two points.
|
||||
//! \~russian Проверить неравенство координат двух точек.
|
||||
bool operator!=(const PIPoint<Type> & p) const { return (x != p.x || y != p.y); }
|
||||
};
|
||||
|
||||
//! \~english Stream output operator for PIPoint.
|
||||
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PIPoint<Type> & v) {
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file piquaternion.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Quaternion
|
||||
* \~russian Кватернион
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file piquaternion.h
|
||||
//! \brief
|
||||
//! \~english Quaternion
|
||||
//! \~russian Кватернион
|
||||
//! \details
|
||||
//! \~english Quaternion for 3D rotations and orientations
|
||||
//! \~russian Кватернион для 3D вращений и ориентаций
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Class for quaternions
|
||||
@@ -28,29 +32,69 @@
|
||||
|
||||
#include "pimathmatrix.h"
|
||||
|
||||
//! \~english Quaternion for representing 3D rotations and orientations
|
||||
//! \~russian Кватернион для представления 3D вращений и ориентаций
|
||||
class PIP_EXPORT PIQuaternion {
|
||||
friend PIP_EXPORT PIQuaternion operator*(const PIQuaternion & q0, const PIQuaternion & q1);
|
||||
friend PIP_EXPORT PIQuaternion operator*(const double & a, const PIQuaternion & q);
|
||||
|
||||
public:
|
||||
//! \~english Construct quaternion from rotation axis and angle
|
||||
//! \~russian Создать кватернион из оси вращения и угла
|
||||
PIQuaternion(const PIMathVectorT3d & u = PIMathVectorT3d(), double a = 0.);
|
||||
|
||||
//! \~english Returns conjugate of this quaternion (negated vector part)
|
||||
//! \~russian Возвращает сопряженный кватернион (с инвертированной векторной частью)
|
||||
PIQuaternion conjugate() const { return PIQuaternion(-vector(), scalar()); }
|
||||
|
||||
//! \~english Returns new quaternion rotated around axis u by angle a
|
||||
//! \~russian Возвращает новый кватернион, повернутый вокруг оси u на угол a
|
||||
PIQuaternion rotated(const PIMathVectorT3d & u, double a) const;
|
||||
|
||||
//! \~english Rotate this quaternion around axis u by angle a
|
||||
//! \~russian Повернуть этот кватернион вокруг оси u на угол a
|
||||
void rotate(const PIMathVectorT3d & u, double a);
|
||||
|
||||
//! \~english Normalize quaternion to unit length
|
||||
//! \~russian Нормализовать кватернион к единичной длине
|
||||
void normalize();
|
||||
|
||||
//! Get/Set scalar component
|
||||
double & scalar() { return q[0]; }
|
||||
|
||||
//! Get scalar component
|
||||
double scalar() const { return q[0]; }
|
||||
|
||||
//! \~english Returns vector part of quaternion
|
||||
//! \~russian Возвращает векторную часть кватерниона
|
||||
PIMathVectorT3d vector() const { return PIMathVectorT3d({q[1], q[2], q[3]}); }
|
||||
|
||||
//! \~english Returns Euler angles from quaternion
|
||||
//! \~russian Возвращает углы Эйлера из кватерниона
|
||||
PIMathVectorT3d eyler() const;
|
||||
|
||||
//! \~english Returns 3x3 rotation matrix from quaternion
|
||||
//! \~russian Возвращает матрицу вращения 3x3 из кватерниона
|
||||
PIMathMatrixT33d rotationMatrix() const;
|
||||
|
||||
//! \~english Extracts rotation axis from quaternion
|
||||
//! \~russian Извлекает ось вращения из кватерниона
|
||||
void axis(PIMathVectorT3d * ret) const;
|
||||
|
||||
//! \~english Create quaternion from Euler angles (roll, pitch, yaw)
|
||||
//! \~russian Создать кватернион из углов Эйлера (крен, тангаж, рыскание)
|
||||
static PIQuaternion fromEyler(double ax, double ay, double az);
|
||||
|
||||
//! \~english Create quaternion from 3x3 rotation matrix
|
||||
//! \~russian Создать кватернион из матрицы вращения 3x3
|
||||
static PIQuaternion fromRotationMatrix(const PIMathMatrixT33d & m);
|
||||
|
||||
//! \~english Create quaternion from rotation angles
|
||||
//! \~russian Создать кватернион из углов поворота
|
||||
static PIQuaternion fromAngles(double ax, double ay, double az);
|
||||
|
||||
//! \~english Create quaternion from rotation angles (alternative method)
|
||||
//! \~russian Создать кватернион из углов поворота (альтернативный метод)
|
||||
static PIQuaternion fromAngles2(double ax, double ay, double az);
|
||||
|
||||
protected:
|
||||
|
||||
@@ -38,17 +38,18 @@ class PIP_EXPORT PIRect {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//!
|
||||
//! \~english Default constructor.
|
||||
//! \~russian Конструктор по умолчанию.
|
||||
PIRect() {}
|
||||
|
||||
//! \brief
|
||||
//! \~english Constructor from bottom-left corner coordinates and width/height.
|
||||
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и размеров ширины и высоты
|
||||
PIRect(Type left_, Type bottom_, Type width_, Type height_) {
|
||||
set(left_, bottom_, width_, height_);
|
||||
normalize();
|
||||
}
|
||||
|
||||
//! \brief
|
||||
//! \~english Constructor from bottom-left and top-right points.
|
||||
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и правого верхнего угла
|
||||
PIRect(const PIPoint<Type> & bottom_left, const PIPoint<Type> & top_right) {
|
||||
bl = bottom_left;
|
||||
@@ -61,128 +62,128 @@ public:
|
||||
// piMax<Type>(p0.x, p1.x, p2.x), piMax<Type>(p0.y, p1.y, p2.y));
|
||||
// }
|
||||
|
||||
//!
|
||||
//! \~english Set rectangle from coordinates and dimensions.
|
||||
PIRect<Type> & set(Type left_, Type bottom_, Type width_, Type height_) {
|
||||
bl = PIPoint<Type>(left_, bottom_);
|
||||
tr = PIPoint<Type>(left_ + width_, bottom_ + height_);
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set rectangle from two points.
|
||||
PIRect<Type> & set(const PIPoint<Type> & top_left, const PIPoint<Type> & bottom_right) {
|
||||
bl = top_left;
|
||||
tr = bottom_right;
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//! \brief
|
||||
//! \~english Check if point with given coordinates is inside the rectangle.
|
||||
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
|
||||
bool pointIn(Type x, Type y) const { return (x <= bl.x && x >= tr.x && y <= bl.y && y >= tr.y); }
|
||||
|
||||
//! \brief
|
||||
//! \~english Check if point is inside the rectangle.
|
||||
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
|
||||
bool pointIn(const PIPoint<Type> & p) const { return pointIn(p.x, p.y); }
|
||||
|
||||
//!
|
||||
//! \~english Check if rectangle is empty.
|
||||
bool isEmpty() const { return (width() == 0 && height() == 0); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by x and y.
|
||||
PIRect<Type> & translate(Type x, Type y) {
|
||||
bl.translate(x, y);
|
||||
tr.translate(x, y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by point.
|
||||
PIRect<Type> & translate(const PIPoint<Type> & p) {
|
||||
bl.translate(p);
|
||||
tr.translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and translate it by x and y.
|
||||
PIRect<Type> translated(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and translate it by point.
|
||||
PIRect<Type> translated(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by x and y. Alias for \a translate().
|
||||
PIRect<Type> & move(Type x, Type y) { return translate(x, y); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by point. Alias for \a translate().
|
||||
PIRect<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and translate it by x and y. Alias for \a translated().
|
||||
PIRect<Type> moved(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and translate it by point. Alias for \a translated().
|
||||
PIRect<Type> moved(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Scale rectangle by x and y factors.
|
||||
PIRect<Type> & scale(Type x, Type y) {
|
||||
setWidth(width() * x);
|
||||
setHeight(height() * y);
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Scale rectangle uniformly.
|
||||
PIRect<Type> & scale(Type s) { return scale(s, s); }
|
||||
|
||||
//!
|
||||
//! \~english Scale rectangle by point factors.
|
||||
PIRect<Type> & scale(const PIPoint<Type> & p) { return scale(p.x, p.y); }
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and scale it by x and y factors.
|
||||
PIRect<Type> scaled(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and scale it uniformly.
|
||||
PIRect<Type> scaled(Type s) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(s);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create a copy of rectangle and scale it by point factors.
|
||||
PIRect<Type> scaled(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Normalize rectangle so that left <= right and bottom <= top.
|
||||
PIRect<Type> & normalize() {
|
||||
if (bl.x > tr.x) piSwap<Type>(bl.x, tr.x);
|
||||
if (bl.y > tr.y) piSwap<Type>(bl.y, tr.y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create normalized copy of rectangle.
|
||||
PIRect<Type> normalized() const {
|
||||
PIRect<Type> r(*this);
|
||||
r.normalize();
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Unite rectangle with another rectangle.
|
||||
PIRect<Type> & unite(const PIRect<Type> & r) {
|
||||
bl.x = piMax<Type>(bl.x, r.left());
|
||||
bl.y = piMax<Type>(bl.y, r.bottom());
|
||||
@@ -191,14 +192,14 @@ public:
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create united copy of rectangle with another rectangle.
|
||||
PIRect<Type> united(const PIRect<Type> & rect) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.unite(rect);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Intersect rectangle with another rectangle.
|
||||
PIRect<Type> & intersect(const PIRect<Type> & r) {
|
||||
bl.x = piMax<Type>(bl.x, r.left());
|
||||
bl.y = piMax<Type>(bl.y, r.bottom());
|
||||
@@ -208,101 +209,101 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Create intersected copy of rectangle with another rectangle.
|
||||
PIRect<Type> intersected(const PIRect<Type> & rect) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.intersect(rect);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Get top coordinate.
|
||||
Type top() const { return tr.y; }
|
||||
|
||||
//!
|
||||
//! \~english Get left coordinate.
|
||||
Type left() const { return bl.x; }
|
||||
|
||||
//!
|
||||
//! \~english Get right coordinate.
|
||||
Type right() const { return tr.x; }
|
||||
|
||||
//!
|
||||
//! \~english Get bottom coordinate.
|
||||
Type bottom() const { return bl.y; }
|
||||
|
||||
//!
|
||||
//! \~english Get rectangle width.
|
||||
Type width() const { return tr.x - bl.x; }
|
||||
|
||||
//!
|
||||
//! \~english Get rectangle height.
|
||||
Type height() const { return tr.y - bl.y; }
|
||||
|
||||
//!
|
||||
//! \~english Get top-left corner point.
|
||||
PIPoint<Type> topLeft() const { return PIPoint<Type>(bl.x, tr.y); }
|
||||
|
||||
//!
|
||||
//! \~english Get top-right corner point.
|
||||
PIPoint<Type> topRigth() const { return tr; }
|
||||
|
||||
//!
|
||||
//! \~english Get bottom-left corner point.
|
||||
PIPoint<Type> bottomLeft() const { return bl; }
|
||||
|
||||
//!
|
||||
//! \~english Get bottom-right corner point.
|
||||
PIPoint<Type> bottomRight() const { return PIPoint<Type>(tr.x, bl.y); }
|
||||
|
||||
//!
|
||||
//! \~english Get center point of rectangle.
|
||||
PIPoint<Type> center() const { return bl.moved(width() / 2, height() / 2); }
|
||||
|
||||
//!
|
||||
//! \~english Set top coordinate.
|
||||
void setTop(Type v) {
|
||||
tr.y = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set left coordinate.
|
||||
void setLeft(Type v) {
|
||||
bl.x = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set right coordinate.
|
||||
void setRigth(Type v) {
|
||||
tr.x = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set bottom coordinate.
|
||||
void setBottom(Type v) {
|
||||
bl.y = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set rectangle width.
|
||||
void setWidth(Type v) { setTop(bl.x + v); }
|
||||
|
||||
//!
|
||||
//! \~english Set rectangle height.
|
||||
void setHeight(Type v) { setRigth(bl.y + v); }
|
||||
|
||||
//!
|
||||
//! \~english Set top-left corner point.
|
||||
void setTopLeft(const PIPoint<Type> & p) {
|
||||
setLeft(p.x);
|
||||
setTop(p.y);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set bottom-right corner point.
|
||||
void setBottomRight(const PIPoint<Type> & p) {
|
||||
setRigth(p.x);
|
||||
setBottom(p.y);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set bottom-left corner point.
|
||||
void setBottomLeft(const PIPoint<Type> & p) {
|
||||
bl = p;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set top-right corner point.
|
||||
void setTopRigth(const PIPoint<Type> & p) {
|
||||
tr = p;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set center point.
|
||||
void setCenter(const PIPoint<Type> & p) {
|
||||
Type w = width();
|
||||
Type h = height();
|
||||
@@ -310,46 +311,46 @@ public:
|
||||
tr = PIPoint<Type>(bl.x + w, bl.y + h);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Set rectangle size.
|
||||
void setSize(Type w, Type h) {
|
||||
tr = PIPoint<Type>(bl.x + w, bl.y + h);
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by x on both coordinates.
|
||||
void operator+=(Type x) { translate(x, x); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by point.
|
||||
void operator+=(const PIPoint<Type> & p) { translate(p); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by negative x on both coordinates.
|
||||
void operator-=(Type x) { translate(-x, -x); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by negative point.
|
||||
void operator-=(const PIPoint<Type> & p) { translate(-p); }
|
||||
|
||||
//!
|
||||
//! \~english Unite rectangle with another.
|
||||
void operator|=(const PIRect<Type> & r) { unite(r); }
|
||||
|
||||
//!
|
||||
//! \~english Intersect rectangle with another.
|
||||
void operator&=(const PIRect<Type> & r) { intersect(r); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by point.
|
||||
PIRect<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
|
||||
|
||||
//!
|
||||
//! \~english Translate rectangle by negative point.
|
||||
PIRect<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
|
||||
|
||||
//!
|
||||
//! \~english Unite rectangle with another.
|
||||
PIRect<Type> operator|(const PIRect<Type> & r) { return united(r); }
|
||||
|
||||
//!
|
||||
//! \~english Intersect rectangle with another.
|
||||
PIRect<Type> operator&(const PIRect<Type> & r) { return intersected(r); }
|
||||
|
||||
//!
|
||||
//! \~english Check equality of two rectangles.
|
||||
bool operator==(const PIRect<Type> & r) const { return (bl == r.bl && tr == r.tr); }
|
||||
|
||||
//!
|
||||
//! \~english Check inequality of two rectangles.
|
||||
bool operator!=(const PIRect<Type> & r) const { return (bl != r.bl || tr != r.tr); }
|
||||
|
||||
private:
|
||||
@@ -357,7 +358,8 @@ private:
|
||||
PIPoint<Type> tr;
|
||||
};
|
||||
|
||||
|
||||
//! \~english Stream output operator for PIRect.
|
||||
//! \~russian Перегруженный оператор для вывода прямоугольника в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PIRect<Type> & v) {
|
||||
s.space();
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/*! \file pistatistic.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Calculating math statistic of values array
|
||||
* \~russian Вычисление математической статистики у массива чисел
|
||||
*/
|
||||
//! \addtogroup Math
|
||||
//! \{
|
||||
//! \file pistatistic.h
|
||||
//! \brief
|
||||
//! \~english Calculating math statistic of values array
|
||||
//! \~russian Вычисление математической статистики у массива чисел
|
||||
//! \details
|
||||
//! \~english Template class for calculating statistical measures of a data set
|
||||
//! \~russian Шаблонный класс для вычисления статистических характеристик набора данных
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Class for calculacing math statistic in values array
|
||||
@@ -28,13 +32,20 @@
|
||||
|
||||
#include "pimathbase.h"
|
||||
|
||||
//! Statistical calculator template class
|
||||
//! \~english Template class for calculating statistical measures (mean, variance, skewness, kurtosis)
|
||||
//! \~russian Шаблонный класс для вычисления статистических показателей (среднее, дисперсия, асимметрия, эксцесс)
|
||||
template<typename T>
|
||||
class PIStatistic {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//! Construct empty statistic calculator
|
||||
PIStatistic() { mean = variance = skewness = kurtosis = T(); }
|
||||
|
||||
//! Calculate arithmetic mean
|
||||
//! \~english Calculate arithmetic mean of values
|
||||
//! \~russian Вычислить среднее арифметическое значение
|
||||
static T calculateMean(const PIVector<T> & val) {
|
||||
T ret = T();
|
||||
int n = val.size();
|
||||
@@ -43,10 +54,13 @@ public:
|
||||
ret += val[i];
|
||||
return ret / n;
|
||||
}
|
||||
//! Calculate all statistics with given mean
|
||||
//! \~english Calculate variance, skewness and kurtosis using provided mean value
|
||||
//! \~russian Вычислить дисперсию, асимметрию и эксцесс с использованием заданного среднего значения
|
||||
bool calculate(const PIVector<T> & val, const T & given_mean) {
|
||||
T v = T(), v1 = T(), v2 = T(), stddev = T(), var = T();
|
||||
int i, n = val.size();
|
||||
mean = given_mean;
|
||||
mean = given_mean;
|
||||
if (n < 2) return false;
|
||||
variance = skewness = kurtosis = T();
|
||||
// Variance (using corrected two-pass algorithm)
|
||||
@@ -72,11 +86,18 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
//! Calculate all statistics
|
||||
//! \~english Calculate mean, variance, skewness and kurtosis
|
||||
//! \~russian Вычислить среднее, дисперсию, асимметрию и эксцесс
|
||||
bool calculate(const PIVector<T> & val) { return calculate(val, calculateMean(val)); }
|
||||
|
||||
//! Arithmetic mean
|
||||
T mean;
|
||||
//! Variance
|
||||
T variance;
|
||||
//! Skewness (third standardized moment)
|
||||
T skewness;
|
||||
//! Kurtosis (fourth standardized moment)
|
||||
T kurtosis;
|
||||
};
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@
|
||||
#include "pivariant.h"
|
||||
|
||||
|
||||
//! \~english Main OpenCL wrapper class
|
||||
//! \~russian Главный класс-обёртка OpenCL
|
||||
class PIP_OPENCL_EXPORT PIOpenCL {
|
||||
public:
|
||||
//! \~english Kernel argument structure
|
||||
|
||||
@@ -66,6 +66,8 @@ public:
|
||||
PIMap<PIString, PIByteArray *> entries;
|
||||
};
|
||||
|
||||
//! \~english Resource entry constructor
|
||||
//! \~russian Конструктор записи ресурса
|
||||
struct PIP_EXPORT __RCEntry {
|
||||
__RCEntry(const PIString & s = PIString(),
|
||||
const PIString & n = PIString(),
|
||||
|
||||
@@ -34,17 +34,17 @@
|
||||
|
||||
#define PIP_BINARY_STREAM
|
||||
|
||||
#define BINARY_STREAM_FRIEND(T) \
|
||||
template<typename P> \
|
||||
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v); \
|
||||
template<typename P> \
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v);
|
||||
#define BINARY_STREAM_FRIEND(T) \
|
||||
template<typename P> \
|
||||
friend PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v); \
|
||||
template<typename P> \
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v);
|
||||
#define BINARY_STREAM_WRITE(T) \
|
||||
template<typename P> \
|
||||
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v)
|
||||
template<typename P> \
|
||||
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const T & v)
|
||||
#define BINARY_STREAM_READ(T) \
|
||||
template<typename P> \
|
||||
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v)
|
||||
template<typename P> \
|
||||
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, T & v)
|
||||
|
||||
|
||||
//! \ingroup Serialization
|
||||
|
||||
@@ -106,7 +106,12 @@ public:
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Set source buffer for read from "data"
|
||||
//! \~russian Устанавливает исходный буфер для чтения из "data"
|
||||
void setSource(const PIByteArray & data);
|
||||
|
||||
//! \~english Set source buffer for read or write to/from "data", or empty stream for write if "data" = 0
|
||||
//! \~russian Устанавливает исходный буфер для чтения или записи из/в "data", или пустой поток на запись если "data" = 0
|
||||
void setSource(PIByteArray * data);
|
||||
|
||||
//! \~english Returns internal buffer with written data
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/*! \file pijson.h
|
||||
* \ingroup Serialization
|
||||
/*! \file pijsonserialization.h
|
||||
* \addtogroup Serialization
|
||||
* \brief
|
||||
* \~english JSON serialization
|
||||
* \~russian Сериализация JSON
|
||||
* \~english JSON serialization and deserialization template functions
|
||||
* \~russian Шаблонные функции сериализации и десериализации JSON
|
||||
* \details
|
||||
* \~english This file provides template functions for serializing and deserializing
|
||||
* various types to and from PIJSON format.
|
||||
* \~russian Этот файл предоставляет шаблонные функции для сериализации и десериализации
|
||||
* различных типов в формат PIJSON и из него.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -38,14 +43,14 @@
|
||||
|
||||
template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
|
||||
inline PIJSON piSerializeJSON(const T & v) {
|
||||
return PIJSON() = (int)v;
|
||||
return PIJSON() = (int)v;
|
||||
}
|
||||
|
||||
template<typename T,
|
||||
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
|
||||
typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
|
||||
inline PIJSON piSerializeJSON(const T & v) {
|
||||
return PIJSON() = v;
|
||||
return PIJSON() = v;
|
||||
}
|
||||
|
||||
template<typename T,
|
||||
@@ -53,7 +58,7 @@ template<typename T,
|
||||
typename std::enable_if<!std::is_arithmetic<T>::value, int>::type = 0>
|
||||
inline PIJSON piSerializeJSON(const T & v) {
|
||||
static_assert(std::is_enum<T>::value || std::is_arithmetic<T>::value,
|
||||
"[piSerializeJSON] Error: using undeclared piSerializeJSON() for complex type!");
|
||||
"[piSerializeJSON] Error: using undeclared piSerializeJSON() for complex type!");
|
||||
return {};
|
||||
}
|
||||
|
||||
@@ -229,14 +234,14 @@ inline PIJSON piSerializeJSON(const PIMap<K, T> & v) {
|
||||
|
||||
template<typename T, typename std::enable_if<std::is_enum<T>::value, int>::type = 0>
|
||||
inline void piDeserializeJSON(T & v, const PIJSON & js) {
|
||||
v = (T)js.toInt();
|
||||
v = (T)js.toInt();
|
||||
}
|
||||
|
||||
template<typename T,
|
||||
typename std::enable_if<!std::is_enum<T>::value, int>::type = 0,
|
||||
typename std::enable_if<std::is_arithmetic<T>::value, int>::type = 0>
|
||||
inline void piDeserializeJSON(T & v, const PIJSON & js) {
|
||||
v = js.value().value<T>();
|
||||
v = js.value().value<T>();
|
||||
}
|
||||
|
||||
template<typename T,
|
||||
@@ -244,7 +249,7 @@ template<typename T,
|
||||
typename std::enable_if<!std::is_arithmetic<T>::value, int>::type = 0>
|
||||
inline void piDeserializeJSON(T & v, const PIJSON & js) {
|
||||
static_assert(std::is_enum<T>::value || std::is_arithmetic<T>::value,
|
||||
"[piDeserializeJSON] Error: using undeclared piDeserializeJSON() for complex type!");
|
||||
"[piDeserializeJSON] Error: using undeclared piDeserializeJSON() for complex type!");
|
||||
v = {};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
/*! \file pivaluetree_conversions.h
|
||||
* \ingroup Serialization
|
||||
* \addtogroup Serialization
|
||||
* \brief
|
||||
* \~english PIValueTree conversions
|
||||
* \~russian Преобразования PIValueTree
|
||||
* \~english PIValueTree conversion functions
|
||||
* \~russian Функции преобразования PIValueTree
|
||||
* \details
|
||||
* \~english This file provides functions for converting PIValueTree to and from
|
||||
* various formats (JSON, text, property storage).
|
||||
* \~russian Этот файл предоставляет функции для преобразования PIValueTree в различные
|
||||
* форматы (JSON, текст, хранилище свойств) и из них.
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -32,31 +37,65 @@ class PIPropertyStorage;
|
||||
class PIJSON;
|
||||
class PIIODevice;
|
||||
|
||||
//! \~english PIValueTree conversion namespace.
|
||||
//! \~russian Пространство имён преобразований PIValueTree.
|
||||
namespace PIValueTreeConversions {
|
||||
|
||||
//! \~english Conversion options. \~russian Параметры преобразования.
|
||||
enum Option {
|
||||
WithAttributes = 0x1,
|
||||
WithComment = 0x2,
|
||||
WithType = 0x4,
|
||||
WithAll = 0xFFF,
|
||||
IncludeRoot = 0x1000,
|
||||
Default = WithAll
|
||||
WithAttributes = 0x1, //!< \~english Include attributes \~russian Включить атрибуты
|
||||
WithComment = 0x2, //!< \~english Include comments \~russian Включить комментарии
|
||||
WithType = 0x4, //!< \~english Include type information \~russian Включить информацию о типе
|
||||
WithAll = 0xFFF, //!< \~english Include everything \~russian Включить всё
|
||||
IncludeRoot = 0x1000, //!< \~english Include root node \~russian Включить корневой узел
|
||||
Default = WithAll //!< \~english Default options \~russian Параметры по умолчанию
|
||||
};
|
||||
//! \~english Options flags type.
|
||||
//! \~russian Тип флагов параметров.
|
||||
typedef PIFlags<Option> Options;
|
||||
|
||||
//! \~english Convert PIPropertyStorage to PIValueTree.
|
||||
//! \~russian Преобразование PIPropertyStorage в PIValueTree.
|
||||
PIP_EXPORT PIValueTree fromPropertyStorage(const PIPropertyStorage & ps);
|
||||
|
||||
//! \~english Convert PIVariantMap to PIValueTree.
|
||||
//! \~russian Преобразование PIVariantMap в PIValueTree.
|
||||
PIP_EXPORT PIValueTree fromVariantMap(const PIVariantMap & vm);
|
||||
|
||||
//! \~english Convert PIJSON to PIValueTree.
|
||||
//! \~russian Преобразование PIJSON в PIValueTree.
|
||||
PIP_EXPORT PIValueTree fromJSON(const PIJSON & json);
|
||||
|
||||
//! \~english Read PIValueTree from IODevice as text.
|
||||
//! \~russian Чтение PIValueTree из IODevice как текст.
|
||||
PIP_EXPORT PIValueTree fromText(PIIODevice * device);
|
||||
|
||||
//! \~english Parse PIValueTree from text string.
|
||||
//! \~russian Разбор PIValueTree из текстовой строки.
|
||||
PIP_EXPORT PIValueTree fromText(const PIString & str);
|
||||
|
||||
//! \~english Load PIValueTree from JSON file.
|
||||
//! \~russian Загрузка PIValueTree из JSON файла.
|
||||
PIP_EXPORT PIValueTree fromJSONFile(const PIString & path);
|
||||
|
||||
//! \~english Load PIValueTree from text file.
|
||||
//! \~russian Загрузка PIValueTree из текстового файла.
|
||||
PIP_EXPORT PIValueTree fromTextFile(const PIString & path);
|
||||
|
||||
//! \~english Convert PIValueTree to JSON.
|
||||
//! \~russian Преобразование PIValueTree в JSON.
|
||||
PIP_EXPORT PIJSON toJSON(const PIValueTree & root, Options options = Default);
|
||||
|
||||
//! \~english Convert PIValueTree to text.
|
||||
//! \~russian Преобразование PIValueTree в текст.
|
||||
PIP_EXPORT PIString toText(const PIValueTree & root, Options options = Default);
|
||||
|
||||
//! \~english Save PIValueTree to JSON file.
|
||||
//! \~russian Сохранение PIValueTree в JSON файл.
|
||||
PIP_EXPORT bool toJSONFile(const PIString & path, const PIValueTree & root, Options options = Default);
|
||||
|
||||
//! \~english Save PIValueTree to text file.
|
||||
//! \~russian Сохранение PIValueTree в текстовый файл.
|
||||
PIP_EXPORT bool toTextFile(const PIString & path, const PIValueTree & root, Options options = Default);
|
||||
|
||||
} // namespace PIValueTreeConversions
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/*! \file pistatemachine.h
|
||||
* \ingroup StateMachine
|
||||
* \~\brief
|
||||
* \~english State machine.
|
||||
* \~russian Машина состояний.
|
||||
*/
|
||||
//! \addtogroup StateMachine
|
||||
//! \{
|
||||
//! \file pistatemachine.h
|
||||
//! \brief
|
||||
//! \~english State machine.
|
||||
//! \~russian Машина состояний.
|
||||
//! \details
|
||||
//! \~english Main state machine class that manages states and transitions
|
||||
//! \~russian Основной класс машины состояний, управляющий состояниями и переходами
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
State machine
|
||||
State machine
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -31,17 +35,36 @@
|
||||
|
||||
|
||||
//! \ingroup StateMachine
|
||||
//! \~\brief
|
||||
//! \~english
|
||||
//! \~russian
|
||||
//! \~english Main state machine class
|
||||
//! \~russian Основной класс машины состояний
|
||||
class PIP_EXPORT PIStateMachine: public PIStateBase {
|
||||
public:
|
||||
//! \~english Creates state machine with optional name
|
||||
//! \~russian Создает машину состояний с опциональным именем
|
||||
//! \param n Machine name
|
||||
PIStateMachine(const PIString & n = {});
|
||||
|
||||
//! \~english Starts state machine execution
|
||||
//! \~russian Запускает выполнение машины состояний
|
||||
//! \return true if started successfully
|
||||
bool start();
|
||||
|
||||
//! \~english Checks if state machine is running
|
||||
//! \~russian Проверяет, запущена ли машина состояний
|
||||
//! \return true if running
|
||||
bool isRunning() const { return is_running; }
|
||||
|
||||
//! \~english Sets finish callback
|
||||
//! \~russian Устанавливает коллбэк завершения
|
||||
//! \param f Callback function to call when machine finishes
|
||||
void setOnFinish(std::function<void()> f) { on_finish = f; }
|
||||
|
||||
//! \~english Posts event to state machine
|
||||
//! \~russian Отправляет событие в машину состояний
|
||||
//! \tparam Args Event arguments types
|
||||
//! \param event_id Event identifier
|
||||
//! \param args Event arguments
|
||||
//! \return true if transition was triggered
|
||||
template<typename... Args>
|
||||
bool postEvent(int event_id, Args... args) {
|
||||
if (!is_running) return false;
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/*! \file pistatemachine_base.h
|
||||
* \ingroup StateMachine
|
||||
* \~\brief
|
||||
* \~english Some template helpers for PIStateMachine
|
||||
* \~russian Несколько шаблонов для PIStateMachine
|
||||
*/
|
||||
//! \addtogroup StateMachine
|
||||
//! \{
|
||||
//! \file pistatemachine_base.h
|
||||
//! \brief
|
||||
//! \~english Some template helpers for PIStateMachine
|
||||
//! \~russian Несколько шаблонов для PIStateMachine
|
||||
//! \details
|
||||
//! \~english Contains helper classes and functions for state machine implementation
|
||||
//! \~russian Содержит вспомогательные классы и функции для реализации машины состояний
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Some template helpers for PIStateMachine
|
||||
Some template helpers for PIStateMachine
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -31,11 +35,19 @@
|
||||
|
||||
namespace PIStateMachineHelpers {
|
||||
|
||||
//! \~english Helper namespace for state machine implementation
|
||||
//! \~russian Вспомогательное пространство имён для реализации машины состояний
|
||||
|
||||
//! \~english Base class for function wrappers
|
||||
//! \~russian Базовый класс для обёрток функций
|
||||
class FunctionBase {
|
||||
public:
|
||||
//! \~english Virtual destructor
|
||||
//! \~russian Виртуальный деструктор
|
||||
virtual ~FunctionBase() {}
|
||||
|
||||
//! \~english Returns format hash for type checking
|
||||
//! \~russian Возвращает хеш формата для проверки типов
|
||||
virtual uint formatHash() = 0;
|
||||
};
|
||||
|
||||
@@ -44,15 +56,24 @@ public:
|
||||
template<typename... Args>
|
||||
class Function: public FunctionBase {
|
||||
public:
|
||||
//! \~english Returns format hash for type checking
|
||||
//! \~russian Возвращает хеш формата для проверки типов
|
||||
uint formatHash() override {
|
||||
static uint ret = PIConstChars(typeid(std::function<void(Args...)>).name()).hash();
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Stored function
|
||||
//! \~russian Сохранённая функция
|
||||
std::function<bool(Args...)> func;
|
||||
};
|
||||
|
||||
//! \~english Creates function wrapper from std::function
|
||||
//! \~russian Создает обёртку функции из std::function
|
||||
//! \tparam Ret Return type of the function
|
||||
//! \tparam Args Argument types of the function
|
||||
//! \param func Function to wrap
|
||||
//! \return Pointer to function wrapper
|
||||
template<typename Ret, typename... Args>
|
||||
FunctionBase * makeFunction(std::function<Ret(Args...)> func) {
|
||||
auto * ret = new Function<Args...>();
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/*! \file pistatemachine_state.h
|
||||
* \ingroup StateMachine
|
||||
* \~\brief
|
||||
* \~english State machine node
|
||||
* \~russian Узел машины состояний
|
||||
*/
|
||||
//! \addtogroup StateMachine
|
||||
//! \{
|
||||
//! \file pistatemachine_state.h
|
||||
//! \brief
|
||||
//! \~english State machine node
|
||||
//! \~russian Узел машины состояний
|
||||
//! \details
|
||||
//! \~english Contains state classes for building state machines
|
||||
//! \~russian Содержит классы состояний для построения машин состояний
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
State machine node
|
||||
State machine node
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -208,6 +212,11 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Output stream operator for PIStateBase
|
||||
//! \~russian Оператор вывода потока для PIStateBase
|
||||
//! \param c Output stream
|
||||
//! \param s State to output
|
||||
//! \return Reference to output stream
|
||||
inline PICout operator<<(PICout c, PIStateBase * s) {
|
||||
if (!s)
|
||||
c << "state(nullptr)";
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
/*! \file pistatemachine_transition.h
|
||||
* \ingroup StateMachine
|
||||
* \~\brief
|
||||
* \~english State machine transition
|
||||
* \~russian Переход машины состояний
|
||||
*/
|
||||
//! \addtogroup StateMachine
|
||||
//! \{
|
||||
//! \file pistatemachine_transition.h
|
||||
//! \brief
|
||||
//! \~english State machine transition
|
||||
//! \~russian Переход машины состояний
|
||||
//! \details
|
||||
//! \~english Contains transition classes for state machine
|
||||
//! \~russian Содержит классы переходов для машины состояний
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
State machine transition
|
||||
State machine transition
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -39,7 +43,13 @@ class PIP_EXPORT PITransitionBase {
|
||||
public:
|
||||
//! \~english Creates transition from source to target on event
|
||||
//! \~russian Создает переход от source к target по событию
|
||||
//! \param source Source state
|
||||
//! \param target Target state
|
||||
//! \param event_id Event identifier that triggers this transition
|
||||
PITransitionBase(PIStateBase * source, PIStateBase * target, int event_id);
|
||||
|
||||
//! \~english Virtual destructor
|
||||
//! \~russian Виртуальный деструктор
|
||||
virtual ~PITransitionBase();
|
||||
|
||||
//! \~english Returns state machine this transition belongs to
|
||||
@@ -114,11 +124,20 @@ protected:
|
||||
|
||||
//! \~english Timeout transition
|
||||
//! \~russian Переход по таймауту
|
||||
//! \details
|
||||
//! \~english Transition that triggers after specified timeout
|
||||
//! \~russian Переход, который срабатывает после указанного таймаута
|
||||
class PIP_EXPORT PITransitionTimeout: public PITransitionBase {
|
||||
public:
|
||||
//! \~english Creates timeout transition
|
||||
//! \~russian Создает переход по таймауту
|
||||
//! \param source Source state
|
||||
//! \param target Target state
|
||||
//! \param timeout Timeout duration
|
||||
PITransitionTimeout(PIStateBase * source, PIStateBase * target, PISystemTime timeout);
|
||||
|
||||
//! \~english Destructor
|
||||
//! \~russian Деструктор
|
||||
~PITransitionTimeout();
|
||||
|
||||
private:
|
||||
@@ -128,4 +147,6 @@ private:
|
||||
PITimer timer;
|
||||
};
|
||||
|
||||
//! \}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -88,42 +88,55 @@
|
||||
# define __PIP_PLUGIN_STATIC_MERGE_FUNC__ pip_merge_static
|
||||
# define __PIP_PLUGIN_LOADER_VERSION__ 2
|
||||
|
||||
# define PIP_PLUGIN_SET_USER_VERSION(v) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIPluginInfo * pi = PIPluginInfoStorage::instance()->currentInfo(); \
|
||||
if (pi) pi->setUserVersion(v); \
|
||||
STATIC_INITIALIZER_END
|
||||
# define PIP_PLUGIN_SET_USER_VERSION(v) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIPluginInfo * pi = PIPluginInfoStorage::instance()->currentInfo(); \
|
||||
if (pi) pi->setUserVersion(v); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
# define PIP_PLUGIN_ADD_STATIC_SECTION(type, ptr) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIPluginInfo * pi = PIPluginInfoStorage::instance()->currentInfo(); \
|
||||
if (pi) pi->setStaticSection(type, ptr); \
|
||||
STATIC_INITIALIZER_END
|
||||
# define PIP_PLUGIN_ADD_STATIC_SECTION(type, ptr) \
|
||||
STATIC_INITIALIZER_BEGIN \
|
||||
PIPluginInfo * pi = PIPluginInfoStorage::instance()->currentInfo(); \
|
||||
if (pi) pi->setStaticSection(type, ptr); \
|
||||
STATIC_INITIALIZER_END
|
||||
|
||||
# define PIP_PLUGIN \
|
||||
extern "C" { \
|
||||
PIP_PLUGIN_EXPORT int __PIP_PLUGIN_LOADER_VERSION_FUNC__() { \
|
||||
return __PIP_PLUGIN_LOADER_VERSION__; \
|
||||
} \
|
||||
}
|
||||
# define PIP_PLUGIN \
|
||||
extern "C" { \
|
||||
PIP_PLUGIN_EXPORT int __PIP_PLUGIN_LOADER_VERSION_FUNC__() { return __PIP_PLUGIN_LOADER_VERSION__; } \
|
||||
}
|
||||
|
||||
# define PIP_PLUGIN_STATIC_SECTION_MERGE \
|
||||
extern "C" { \
|
||||
PIP_PLUGIN_EXPORT void __PIP_PLUGIN_STATIC_MERGE_FUNC__(int type, void * from, void * to); \
|
||||
} \
|
||||
void __PIP_PLUGIN_STATIC_MERGE_FUNC__(int type, void * from, void * to)
|
||||
# define PIP_PLUGIN_STATIC_SECTION_MERGE \
|
||||
extern "C" { \
|
||||
PIP_PLUGIN_EXPORT void __PIP_PLUGIN_STATIC_MERGE_FUNC__(int type, void * from, void * to); \
|
||||
} \
|
||||
void __PIP_PLUGIN_STATIC_MERGE_FUNC__(int type, void * from, void * to)
|
||||
|
||||
|
||||
# endif
|
||||
|
||||
|
||||
//! \~english Plugin information
|
||||
//! \~russian Информация о плагине
|
||||
class PIP_EXPORT PIPluginInfo {
|
||||
public:
|
||||
//! \~english Constructs empty plugin info
|
||||
//! \~russian Создает пустую информацию о плагине
|
||||
PIPluginInfo();
|
||||
|
||||
//! \~english Sets user version
|
||||
//! \~russian Устанавливает пользовательскую версию
|
||||
void setUserVersion(const PIString & v);
|
||||
|
||||
//! \~english Sets static section pointer
|
||||
//! \~russian Устанавливает указатель статической секции
|
||||
void setStaticSection(int type, void * ptr);
|
||||
|
||||
//! \~english Returns user version
|
||||
//! \~russian Возвращает пользовательскую версию
|
||||
PIString userVersion() const;
|
||||
|
||||
//! \~english Returns all static sections
|
||||
//! \~russian Возвращает все статические секции
|
||||
PIMap<int, void *> staticSections() const;
|
||||
|
||||
private:
|
||||
@@ -132,16 +145,36 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Plugin info storage
|
||||
//! \~russian Хранилище информации о плагинах
|
||||
class PIP_EXPORT PIPluginInfoStorage {
|
||||
public:
|
||||
//! \~english Constructs storage
|
||||
//! \~russian Создает хранилище
|
||||
PIPluginInfoStorage();
|
||||
|
||||
//! \~english Returns current plugin info
|
||||
//! \~russian Возвращает информацию о текущем плагине
|
||||
PIPluginInfo * currentInfo();
|
||||
|
||||
//! \~english Returns plugin info by pointer
|
||||
//! \~russian Возвращает информацию о плагине по указателю
|
||||
PIPluginInfo * pluginInfo(void * p);
|
||||
|
||||
//! \~english Returns application plugin info
|
||||
//! \~russian Возвращает информацию о приложении
|
||||
PIPluginInfo * applicationInfo();
|
||||
|
||||
//! \~english Enters plugin context
|
||||
//! \~russian Входит в контекст плагина
|
||||
PIPluginInfo * enterPlugin(void * p);
|
||||
|
||||
//! \~english Unloads plugin
|
||||
//! \~russian Выгружает плагин
|
||||
void unloadPlugin(void * p);
|
||||
|
||||
//! \~english Returns singleton instance
|
||||
//! \~russian Возвращает синглтон
|
||||
static PIPluginInfoStorage * instance();
|
||||
|
||||
private:
|
||||
@@ -223,6 +256,8 @@ public:
|
||||
//! \~russian Вызывает у плагина \a PIP_PLUGIN_STATIC_SECTION_MERGE
|
||||
void mergeStatic();
|
||||
|
||||
//! \~english Returns directories where plugins can be located
|
||||
//! \~russian Возвращает директории где могут располагаться плагины
|
||||
static PIStringList pluginsDirectories(const PIString & name);
|
||||
|
||||
private:
|
||||
|
||||
@@ -17,22 +17,48 @@
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef PISYSTEMTESTS_H
|
||||
#define PISYSTEMTESTS_H
|
||||
//! \addtogroup System
|
||||
//! \{
|
||||
//! \file pisystemtests.h
|
||||
//! \brief System tests results
|
||||
//! \~english Provides access to system test results and timing information
|
||||
//! \~russian Предоставляет доступ к результатам системных тестов и информации о времени
|
||||
//! \details
|
||||
//! \~english This module contains functionality for reading system test results, including timing information
|
||||
//! \~russian Этот модуль содержит функциональность для чтения результатов системных тестов, включая информацию о времени
|
||||
|
||||
#include "pibase.h"
|
||||
#ifndef PISYSTEMTESTS_H
|
||||
# define PISYSTEMTESTS_H
|
||||
|
||||
# include "pibase.h"
|
||||
|
||||
namespace PISystemTests {
|
||||
|
||||
//! \~english Time resolution in nanoseconds
|
||||
//! \~russian Разрешение времени в наносекундах
|
||||
extern PIP_EXPORT long time_resolution_ns;
|
||||
|
||||
//! \~english Time elapsed in nanoseconds
|
||||
//! \~russian Прошедшее время в наносекундах
|
||||
extern PIP_EXPORT long time_elapsed_ns;
|
||||
|
||||
//! \~english Usleep offset in microseconds
|
||||
//! \~russian Смещение usleep в микросекундах
|
||||
extern PIP_EXPORT long usleep_offset_us;
|
||||
|
||||
//! \~english System test reader class
|
||||
//! \~russian Класс чтения системных тестов
|
||||
class PIP_EXPORT PISystemTestReader {
|
||||
public:
|
||||
//! \~english Constructor
|
||||
//! \~russian Конструктор
|
||||
PISystemTestReader();
|
||||
};
|
||||
|
||||
//! \~english Global system test reader instance
|
||||
//! \~russian Глобальный экземпляр чтеца системных тестов
|
||||
extern PIP_EXPORT PISystemTestReader pisystestreader;
|
||||
} // namespace PISystemTests
|
||||
|
||||
#endif // PISYSTEMTESTS_H
|
||||
//! \}
|
||||
|
||||
@@ -39,12 +39,12 @@ public:
|
||||
//! \~english Options for regular expression matching behavior
|
||||
//! \~russian Опции поведения регулярного выражения
|
||||
enum Option {
|
||||
None = 0x0, /*!< \~english No special options \~russian Без специальных опций */
|
||||
CaseInsensitive = 0x01, /*!< \~english Case insensitive matching \~russian Регистронезависимое сопоставление */
|
||||
Singleline = 0x02, /*!< \~english Dot matches newline \~russian Точка соответствует символу новой строки */
|
||||
Multiline = 0x04, /*!< \~english ^ and $ match at line boundaries \~russian ^ и $ соответствуют границам строк */
|
||||
None = 0x0, /*!< \~english No special options \~russian Без специальных опций */
|
||||
CaseInsensitive = 0x01, /*!< \~english Case insensitive matching \~russian Регистронезависимое сопоставление */
|
||||
Singleline = 0x02, /*!< \~english Dot matches newline \~russian Точка соответствует символу новой строки */
|
||||
Multiline = 0x04, /*!< \~english ^ and $ match at line boundaries \~russian ^ и $ соответствуют границам строк */
|
||||
InvertedGreediness = 0x08, /*!< \~english Quantifiers are non-greedy by default \~russian Квантификаторы по умолчанию нежадные */
|
||||
Extended = 0x10 /*!< \~english Extended pattern syntax \~russian Расширенный синтаксис шаблона */
|
||||
Extended = 0x10 /*!< \~english Extended pattern syntax \~russian Расширенный синтаксис шаблона */
|
||||
};
|
||||
|
||||
//! \brief
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIReadWriteLock, PIReadLocker, PIWriteLocker
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
PIReadWriteLock, PIReadLocker, PIWriteLocker
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
|
||||
@@ -6,8 +6,8 @@
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PISemaphore, PISemaphoreLocker
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
PISemaphore, PISemaphoreLocker
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU Lesser General Public License as published by
|
||||
|
||||
@@ -3,6 +3,11 @@
|
||||
* \brief
|
||||
* \~english PITime conversions for Windows
|
||||
* \~russian Преобразования PITime для Windows
|
||||
* \details
|
||||
* \~english This file provides conversion functions between Windows time structures (FILETIME, SYSTEMTIME) and PIP time structures
|
||||
* (PISystemTime, PIDateTime).
|
||||
* \~russian Этот файл предоставляет функции преобразования между структурами времени Windows (FILETIME, SYSTEMTIME) и структурами времени
|
||||
* PIP (PISystemTime, PIDateTime).
|
||||
*/
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
@@ -32,7 +37,16 @@
|
||||
|
||||
# include <windows.h>
|
||||
|
||||
//! \addtogroup Types
|
||||
//! \{
|
||||
|
||||
//! \~english Converts FILETIME to PISystemTime.
|
||||
//! \~russian Преобразует FILETIME в PISystemTime.
|
||||
//! \details
|
||||
//! \~english Converts Windows FILETIME structure to PISystemTime. FILETIME is a 64-bit value representing the number of 100-nanosecond
|
||||
//! intervals since January 1, 1601 (UTC).
|
||||
//! \~russian Преобразует структуру Windows FILETIME в PISystemTime. FILETIME - это 64-битное значение, представляющее количество интервалов
|
||||
//! по 100 наносекунд с 1 января 1601 года (UTC).
|
||||
inline PISystemTime FILETIME2PISystemTime(const FILETIME & t) {
|
||||
PISystemTime st;
|
||||
ullong lt = ullong(t.dwHighDateTime) * 0x100000000U + ullong(t.dwLowDateTime);
|
||||
@@ -42,6 +56,13 @@ inline PISystemTime FILETIME2PISystemTime(const FILETIME & t) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Converts SYSTEMTIME to PIDateTime.
|
||||
//! \~russian Преобразует SYSTEMTIME в PIDateTime.
|
||||
//! \details
|
||||
//! \~english Converts Windows SYSTEMTIME structure to PIDateTime. SYSTEMTIME represents a date and time using individual members for month,
|
||||
//! day, year, etc.
|
||||
//! \~russian Преобразует структуру Windows SYSTEMTIME в PIDateTime. SYSTEMTIME представляет дату и время с помощью отдельных членов для
|
||||
//! месяца, дня, года и т.д.
|
||||
inline PIDateTime SYSTEMTIME2PIDateTime(const SYSTEMTIME & t) {
|
||||
PIDateTime dt;
|
||||
dt.year = t.wYear;
|
||||
@@ -54,6 +75,13 @@ inline PIDateTime SYSTEMTIME2PIDateTime(const SYSTEMTIME & t) {
|
||||
return dt;
|
||||
}
|
||||
|
||||
//! \~english Converts FILETIME to PIDateTime.
|
||||
//! \~russian Преобразует FILETIME в PIDateTime.
|
||||
//! \details
|
||||
//! \~english Converts Windows FILETIME to PIDateTime. The FILETIME is first converted to local time, then to SYSTEMTIME, and finally to
|
||||
//! PIDateTime.
|
||||
//! \~russian Преобразует Windows FILETIME в PIDateTime. Сначала FILETIME преобразуется в местное время, затем в SYSTEMTIME и наконец в
|
||||
//! PIDateTime.
|
||||
inline PIDateTime FILETIME2PIDateTime(const FILETIME & t) {
|
||||
FILETIME lt;
|
||||
SYSTEMTIME st;
|
||||
@@ -62,6 +90,11 @@ inline PIDateTime FILETIME2PIDateTime(const FILETIME & t) {
|
||||
return SYSTEMTIME2PIDateTime(st);
|
||||
}
|
||||
|
||||
//! \~english Converts PIDateTime to SYSTEMTIME.
|
||||
//! \~russian Преобразует PIDateTime в SYSTEMTIME.
|
||||
//! \details
|
||||
//! \~english Converts PIDateTime to Windows SYSTEMTIME structure.
|
||||
//! \~russian Преобразует PIDateTime в структуру Windows SYSTEMTIME.
|
||||
inline SYSTEMTIME PIDateTime2SYSTEMTIME(const PIDateTime & dt) {
|
||||
SYSTEMTIME st;
|
||||
st.wYear = dt.year;
|
||||
@@ -74,6 +107,13 @@ inline SYSTEMTIME PIDateTime2SYSTEMTIME(const PIDateTime & dt) {
|
||||
return st;
|
||||
}
|
||||
|
||||
//! \~english Converts PIDateTime to FILETIME.
|
||||
//! \~russian Преобразует PIDateTime в FILETIME.
|
||||
//! \details
|
||||
//! \~english Converts PIDateTime to Windows FILETIME. The PIDateTime is first converted to SYSTEMTIME, then to local FILETIME, and finally
|
||||
//! to UTC FILETIME.
|
||||
//! \~russian Преобразует PIDateTime в Windows FILETIME. Сначала PIDateTime преобразуется в SYSTEMTIME, затем в местное FILETIME и наконец в
|
||||
//! UTC FILETIME.
|
||||
inline FILETIME PIDateTime2FILETIME(const PIDateTime & dt) {
|
||||
FILETIME lt, ret;
|
||||
SYSTEMTIME st = PIDateTime2SYSTEMTIME(dt);
|
||||
@@ -82,6 +122,7 @@ inline FILETIME PIDateTime2FILETIME(const PIDateTime & dt) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \}
|
||||
|
||||
#endif // WINDOWS
|
||||
#endif // PITIME_WIN_H
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file piunits.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Unit conversions
|
||||
* \~russian Преобразование единиц измерения
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits.h
|
||||
//! \brief
|
||||
//! \~english Unit conversions main header
|
||||
//! \~russian Главный заголовочный файл преобразования единиц измерения
|
||||
//! \details
|
||||
//! \~english This is the main include file for unit conversion functionality. It includes all unit classes: Angle, Distance, Information,
|
||||
//! Mass, Pressure, Temperature, and Time.
|
||||
//! \~russian Это главный включаемый файл для функциональности преобразования единиц. Он включает все классы единиц: Angle, Distance,
|
||||
//! Information, Mass, Pressure, Temperature и Time.
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Unit conversions
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file piunits_class_angle.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Angle units
|
||||
* \~russian Единицы измерения угла
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_angle.h
|
||||
//! \brief
|
||||
//! \~english Angle units header
|
||||
//! \~russian Заголовочный файл единиц измерения угла
|
||||
//! \details
|
||||
//! \~english Defines the Angle unit class with support for Degree and Radian units.
|
||||
//! \~russian Определяет класс единиц Angle с поддержкой единиц Degree и Radian.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Angle
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Angle units
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file piunits_class_distance.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Distance units
|
||||
* \~russian Единицы измерения расстояния
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_distance.h
|
||||
//! \brief
|
||||
//! \~english Distance units header
|
||||
//! \~russian Заголовочный файл единиц измерения расстояния
|
||||
//! \details
|
||||
//! \~english Defines the Distance unit class with support for Meter, Inch, Mil, Foot, Yard, Angstrom, and AstronomicalUnit.
|
||||
//! \~russian Определяет класс единиц Distance с поддержкой единиц Meter, Inch, Mil, Foot, Yard, Angstrom и AstronomicalUnit.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Distance
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Distance units
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file piunits_class_information.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Information units
|
||||
* \~russian Единицы измерения информации
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_information.h
|
||||
//! \brief
|
||||
//! \~english Information units header
|
||||
//! \~russian Заголовочный файл единиц измерения информации
|
||||
//! \details
|
||||
//! \~english Defines the Information unit class with support for Bit and Byte units.
|
||||
//! \~russian Определяет класс единиц Information с поддержкой единиц Bit и Byte.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Information
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Information units
|
||||
|
||||
@@ -1,12 +1,18 @@
|
||||
/*! \file piunits_class_distance.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Mass units
|
||||
* \~russian Единицы измерения массы
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_mass.h
|
||||
//! \brief
|
||||
//! \~english Mass units header
|
||||
//! \~russian Заголовочный файл единиц измерения массы
|
||||
//! \details
|
||||
//! \~english Defines the Mass unit class with support for Gram, Pound, and Ounce units.
|
||||
//! \~russian Определяет класс единиц Mass с поддержкой единиц Gram, Pound и Ounce.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Mass
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Mass units
|
||||
Mass units
|
||||
Ivan Pelipenko peri4ko@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
|
||||
@@ -1,9 +1,15 @@
|
||||
/*! \file piunits_class_pressure.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Pressure units
|
||||
* \~russian Единицы измерения давления
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_pressure.h
|
||||
//! \brief
|
||||
//! \~english Pressure units header
|
||||
//! \~russian Заголовочный файл единиц измерения давления
|
||||
//! \details
|
||||
//! \~english Defines the Pressure unit class with support for Pascal, Atmosphere, Bar, and MillimetreOfMercury units.
|
||||
//! \~russian Определяет класс единиц Pressure с поддержкой единиц Pascal, Atmosphere, Bar и MillimetreOfMercury.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Pressure
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Pressure units
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
/*! \file piunits_class_temperature.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Temperature units
|
||||
* \~russian Единицы измерения температуры
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_temperature.h
|
||||
//! \brief
|
||||
//! \~english Temperature units header
|
||||
//! \~russian Заголовочный файл единиц измерения температуры
|
||||
//! \details
|
||||
//! \~english Defines the Temperature unit class with support for Kelvin, Celsius, and Fahrenheit units.
|
||||
//! \~russian Определяет класс единиц Temperature с поддержкой единиц Kelvin, Celsius и Fahrenheit.
|
||||
//!
|
||||
//! \note
|
||||
//! \~english Temperature conversion requires offset calculations, not just multiplication.
|
||||
//! \~russian Преобразование температуры требует вычислений со смещением, а не только умножения.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Temperature
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Temperature units
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
/*! \file piunits_class_time.h
|
||||
* \ingroup Core
|
||||
* \~\brief
|
||||
* \~english Time units
|
||||
* \~russian Единицы измерения времени
|
||||
*/
|
||||
//! \addtogroup Units
|
||||
//! \{
|
||||
//! \file piunits_class_time.h
|
||||
//! \brief
|
||||
//! \~english Time units header
|
||||
//! \~russian Заголовочный файл единиц измерения времени
|
||||
//! \details
|
||||
//! \~english Defines the Time unit class with support for Second and Hertz units.
|
||||
//! \~russian Определяет класс единиц Time с поддержкой единиц Second и Hertz.
|
||||
//!
|
||||
//! \note
|
||||
//! \~english Hertz is the frequency unit, inverse of second.
|
||||
//! \~russian Герц - единица частоты, обратная секунде.
|
||||
//!
|
||||
//! \~\sa PIUnits::Class::Time
|
||||
//! \}
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Time units
|
||||
|
||||
Reference in New Issue
Block a user