merged AI doc, some new pages
This commit is contained in:
26
doc/pages/application.md
Normal file
26
doc/pages/application.md
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
\~english \page application Application-level tools
|
||||||
|
\~russian \page application Инструменты уровня приложения
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
The Application module provides classes commonly needed at program startup and runtime:
|
||||||
|
|
||||||
|
* **PICLI** — command-line argument parser. Add named arguments (e.g. \c addArgument("debug") for \c -d / \c --debug), check presence with \a hasArgument(), optionally read values. Used in \ref using_basic for console and debug flags.
|
||||||
|
* **PILog** — high-level logging with categories and levels. Configure sinks and severity; write log lines from anywhere in the process.
|
||||||
|
* **PISystemMonitor** — snapshot of system resources (CPU, memory, etc.). Query current stats or subscribe to periodic updates.
|
||||||
|
* **PISingleApplication** — ensure only one instance of the application runs; optional inter-process messaging when a second instance is started.
|
||||||
|
* **PITranslator** — translation support: load catalogs, select language, translate strings at runtime.
|
||||||
|
|
||||||
|
All are included via the main PIP library or the Application umbrella (\a piapplicationmodule.h). For CLI and logging, see \ref using_basic; for full API details see the headers \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
Модуль Application предоставляет классы, часто нужные при запуске и работе приложения:
|
||||||
|
|
||||||
|
* **PICLI** — разбор аргументов командной строки. Добавление именованных аргументов (\c addArgument("debug") для \c -d / \c --debug), проверка наличия \a hasArgument(), при необходимости чтение значений. Используется в \ref using_basic для флагов консоли и отладки.
|
||||||
|
* **PILog** — логирование с категориями и уровнями. Настройка приёмников и уровня детализации; запись строк лога из любой части процесса.
|
||||||
|
* **PISystemMonitor** — снимок ресурсов системы (CPU, память и т.д.). Запрос текущей статистики или подписка на периодические обновления.
|
||||||
|
* **PISingleApplication** — гарантия единственного экземпляра приложения; при необходимости обмен сообщениями между процессами при запуске второго экземпляра.
|
||||||
|
* **PITranslator** — поддержка перевода: загрузка каталогов, выбор языка, перевод строк в runtime.
|
||||||
|
|
||||||
|
Всё подключается через основную библиотеку PIP или зонтичный заголовок (\a piapplicationmodule.h). Для CLI и лога см. \ref using_basic; детали API — в заголовках \a picli.h, \a pilog.h, \a pisystemmonitor.h, \a pisingleapplication.h, \a pitranslator.h.
|
||||||
56
doc/pages/chunk_stream.md
Normal file
56
doc/pages/chunk_stream.md
Normal file
@@ -0,0 +1,56 @@
|
|||||||
|
\~english \page chunk_stream Chunk stream and versioned serialization
|
||||||
|
\~russian \page chunk_stream Поток чанков и версионная сериализация
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
\a PIChunkStream is a binary stream where data is stored as **chunks**: each chunk has an integer \e id and a value. Reading is id-based, so you can add or reorder fields over time and stay backward compatible: old readers ignore unknown ids, new readers can skip optional ids.
|
||||||
|
|
||||||
|
Two format versions exist (\a PIChunkStream::Version_1 and \a Version_2); the writer chooses the version, the reader detects it automatically. By default new data is written in Version_2.
|
||||||
|
|
||||||
|
# When to use
|
||||||
|
|
||||||
|
Use chunk streams when:
|
||||||
|
* You need to extend structures without breaking existing stored data (add new fields with new ids).
|
||||||
|
* You want optional or reordered fields in a single stream.
|
||||||
|
* You use \ref code_model to generate serialization: with default (chunk) mode, \c pip_cmg emits operators that read/write via \a PIChunkStream and field ids (see \ref code_model "code_model" for PIMETA \c id and \c simple-stream / \c no-stream).
|
||||||
|
|
||||||
|
For fixed, non-extensible layouts, plain \a PIBinaryStream operators (see \ref iostream) are enough.
|
||||||
|
|
||||||
|
# Usage
|
||||||
|
|
||||||
|
Build a \a PIChunkStream from a \a PIByteArray (read or read-write). Write with \c cs << cs.chunk(id, value) or \c add(id, value); read with \c read() to get the next id, then \c get(value). Call \c data() to get the byte buffer for storing or sending. Example (conceptually as in code_model output):
|
||||||
|
|
||||||
|
\code{.cpp}
|
||||||
|
PIByteArray buf;
|
||||||
|
PIChunkStream cs(&buf);
|
||||||
|
cs << cs.chunk(1, i) << cs.chunk(2, s);
|
||||||
|
// later:
|
||||||
|
PIChunkStream reader(buf);
|
||||||
|
while (!reader.atEnd()) {
|
||||||
|
switch (reader.read()) {
|
||||||
|
case 1: reader.get(i); break;
|
||||||
|
case 2: reader.get(s); break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
\endcode
|
||||||
|
|
||||||
|
Generated operators for structs use the same pattern; see \ref code_model.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
\a PIChunkStream — бинарный поток, в котором данные хранятся **чанками**: у каждого чанка целочисленный \e id и значение. Чтение идёт по id, поэтому можно добавлять или менять порядок полей с сохранением обратной совместимости: старые читатели игнорируют неизвестные id, новые могут пропускать необязательные.
|
||||||
|
|
||||||
|
Есть две версии формата (\a PIChunkStream::Version_1 и \a Version_2); версию выбирает запись, при чтении она определяется автоматически. По умолчанию запись идёт в Version_2.
|
||||||
|
|
||||||
|
# Когда использовать
|
||||||
|
|
||||||
|
Имеет смысл использовать поток чанков, когда:
|
||||||
|
* Нужно расширять структуры без поломки уже сохранённых данных (новые поля — новые id).
|
||||||
|
* Нужны необязательные или переставляемые поля в одном потоке.
|
||||||
|
* Используется \ref code_model для генерации сериализации: в режиме по умолчанию (chunk) \c pip_cmg выдаёт операторы через \a PIChunkStream и id полей (см. \ref code_model по PIMETA \c id и \c simple-stream / \c no-stream).
|
||||||
|
|
||||||
|
Для фиксированных неизменяемых форматов достаточно обычных операторов \a PIBinaryStream (см. \ref iostream).
|
||||||
|
|
||||||
|
# Использование
|
||||||
|
|
||||||
|
Создают \a PIChunkStream из \a PIByteArray (чтение или чтение/запись). Запись: \c cs << cs.chunk(id, value) или \c add(id, value); чтение: \c read() — следующий id, затем \c get(value). \c data() возвращает буфер для сохранения или передачи. Примеры генерации операторов — в \ref code_model.
|
||||||
46
doc/pages/client_server.md
Normal file
46
doc/pages/client_server.md
Normal file
@@ -0,0 +1,46 @@
|
|||||||
|
\~english \page client_server TCP client-server
|
||||||
|
\~russian \page client_server TCP клиент-сервер
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
The ClientServer module provides a TCP server that accepts connections and manages per-client objects, and an active client that connects to a server. All in the \a PIClientServer namespace.
|
||||||
|
|
||||||
|
# Server
|
||||||
|
|
||||||
|
\a PIClientServer::Server listens on an address (e.g. \a listenAll(port) for all interfaces). For each accepted connection the server creates a \a PIClientServer::ServerClient. You can override the client type and handle client lifecycle (e.g. data received, disconnected). Use \a getMaxClients() / \a setMaxClients() to limit simultaneous connections. \a listen(addr) starts listening, \a stopServer() stops the server, \a closeAll() closes all current clients.
|
||||||
|
|
||||||
|
# ServerClient
|
||||||
|
|
||||||
|
\a PIClientServer::ServerClient is the server-side representation of one connected client. The server creates and owns these objects. Override \a aboutDelete() if you need cleanup before the client is removed. Use the base API (\a ClientBase) to send and receive data on the connection.
|
||||||
|
|
||||||
|
# Client
|
||||||
|
|
||||||
|
\a PIClientServer::Client is the active client: it connects to a remote server (address/port). After connecting you use the same send/receive API as on the server side. Connect, exchange data, then disconnect when done.
|
||||||
|
|
||||||
|
# Typical flow
|
||||||
|
|
||||||
|
Server: construct \a Server, optionally set max clients and callbacks, call \a listen() or \a listenAll(port). Handle client events (new client, data, disconnect) in your overrides or via the provided hooks. Client: construct \a Client, connect to server address, send/receive, disconnect.
|
||||||
|
|
||||||
|
See \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h for the full API.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
Модуль ClientServer предоставляет TCP-сервер, принимающий соединения и управляющий объектами клиентов, и активный клиент, подключающийся к серверу. Всё в пространстве имён \a PIClientServer.
|
||||||
|
|
||||||
|
# Сервер
|
||||||
|
|
||||||
|
\a PIClientServer::Server слушает адрес (например \a listenAll(port) на всех интерфейсах). Для каждого принятого соединения создаётся \a PIClientServer::ServerClient. Можно подменить тип клиента и обрабатывать жизненный цикл (данные, отключение). \a getMaxClients() / \a setMaxClients() ограничивают число одновременных соединений. \a listen(addr) — запуск, \a stopServer() — остановка, \a closeAll() — закрытие всех клиентов.
|
||||||
|
|
||||||
|
# Серверный клиент
|
||||||
|
|
||||||
|
\a PIClientServer::ServerClient — серверное представление одного подключённого клиента. Объекты создаёт и владеет сервер. Переопределите \a aboutDelete() при необходимости очистки перед удалением. Отправка и приём данных — через базовый API (\a ClientBase).
|
||||||
|
|
||||||
|
# Клиент
|
||||||
|
|
||||||
|
\a PIClientServer::Client — активный клиент: подключается к удалённому серверу (адрес/порт). После подключения используется тот же API отправки/приёма. Подключение, обмен, отключение.
|
||||||
|
|
||||||
|
# Типичный сценарий
|
||||||
|
|
||||||
|
Сервер: создать \a Server, при необходимости задать лимит клиентов и обработчики, вызвать \a listen() или \a listenAll(port). Обрабатывать события клиентов в переопределениях или через хуки. Клиент: создать \a Client, подключиться к адресу сервера, обмен данными, отключиться.
|
||||||
|
|
||||||
|
Полный API: \a piclientserver_server.h, \a piclientserver_client.h, \a piclientserver_client_base.h.
|
||||||
@@ -3,6 +3,26 @@
|
|||||||
|
|
||||||
\~english
|
\~english
|
||||||
|
|
||||||
|
# Introduction
|
||||||
|
|
||||||
|
Code generation helps when you need string representation of entities (classes, enums, etc.) or automated serialization/deserialization of structures and classes. For example, you may need a list of "name" = "value" pairs from an enumeration for a UI, or to traverse nested structures with metadata. You can describe a structure of any complexity, assign field IDs, and get ready-made operators for \a PIBinaryStream with versioning and backward compatibility.
|
||||||
|
|
||||||
|
# pip_cmg
|
||||||
|
|
||||||
|
PIP provides the \c pip_cmg utility: it takes source files, include paths, and options, and produces a .h/.cpp pair. Depending on options, the output may include: entity metadata; serialization operators; and the ability to get a \a PIVariant for any member by name.
|
||||||
|
|
||||||
|
Processing options: \c -s (do not follow #include); \c -I<include_dir> (add include path); \c -D<define> (add macro; \c PICODE is always defined).
|
||||||
|
|
||||||
|
Creation options: \c -A (create all); \c -M (metadata); \c -E (enums); \c -S (serialization operators); \c -G (get value by name); \c -o <output_file> (output base name without extension).
|
||||||
|
|
||||||
|
# CMake
|
||||||
|
|
||||||
|
The \c pip_code_model CMake macro invokes \c pip_cmg and keeps the model up to date. Call format: \c pip_code_model(<out_var> file0 [file1 ...] [OPTIONS ...] [NAME name]). Parameters: \c out_var receives generated file paths; \c file... are sources; \c OPTIONS are passed to \c pip_cmg (e.g. \c "-Es"); \c NAME sets the model file base (default \c "ccm_${PROJECT_NAME}"). The macro adds PIP include paths. Run \c pip_cmg -v for current options.
|
||||||
|
|
||||||
|
# Details
|
||||||
|
|
||||||
|
Metadata: attach \c PIMETA(...) to types, members or enums; read at runtime via \a PICODEINFO::classes() and \a PICODEINFO::enums(). Serialization: struct-level \c PIMETA(simple-stream) or \c PIMETA(no-stream), or per-member chunk ids (default); see \ref chunk_stream. Add the generated .h/.cpp to your target and \c #include the generated header; metadata loads before \c main().
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
|
|
||||||
# Введение
|
# Введение
|
||||||
|
|||||||
14
doc/pages/config.md
Normal file
14
doc/pages/config.md
Normal file
@@ -0,0 +1,14 @@
|
|||||||
|
\~english \page config Configuration from file
|
||||||
|
\~russian \page config Конфигурация из файла
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
\a PIConfig parses and writes configuration from files, strings, or any \a PIIODevice. The internal model is a tree of entries; each node is \a PIConfig::Entry, and a list of entries is \a PIConfig::Branch. Use dotted paths to get values, e.g. \c getValue("section.key.subkey"). Supports INI-style \c [section] prefixes, multiline values, and \c include directives resolved at parse time.
|
||||||
|
|
||||||
|
Typical use: open a file or device, then call \c getValue(name) or \c getValue(name, default) on the root or on a \a PIConfig::Branch. Overloads exist for string, numeric, and bool defaults. To configure an I/O device from config, pass \a PIConfig::Entry pointers to \a PIIODevice::configure(); see \a PIIODevice and device-specific headers.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
\a PIConfig разбирает и записывает конфигурацию из файлов, строк или любого \a PIIODevice. Внутренняя модель — дерево записей; узел — \a PIConfig::Entry, список узлов — \a PIConfig::Branch. Доступ по точечным путям, например \c getValue("section.key.subkey"). Поддерживаются префиксы секций в стиле INI (\c [section]), многострочные значения и директивы \c include, разрешаемые при разборе.
|
||||||
|
|
||||||
|
Типичное использование: открыть файл или устройство, затем вызывать \c getValue(name) или \c getValue(name, default) от корня или от \a PIConfig::Branch. Есть перегрузки для строковых, числовых и булевых значений по умолчанию. Для настройки устройства ввода-вывода из конфига в \a PIIODevice::configure() передают указатели на \a PIConfig::Entry; см. \a PIIODevice и заголовки конкретных устройств.
|
||||||
50
doc/pages/connection.md
Normal file
50
doc/pages/connection.md
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
\~english \page connection Complex I/O (PIConnection)
|
||||||
|
\~russian \page connection Сложный ввод-вывод (PIConnection)
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
\a PIConnection is an abstract layer over physical I/O devices: it manages a **device pool**, **filters** (packet extraction), **senders** (timed output), and **diagnostics**. Several connections can share one physical device through the pool; each device has an associated read thread that you start/stop with \a startThreadedRead() and \a stopThreadedRead().
|
||||||
|
|
||||||
|
# Device pool
|
||||||
|
|
||||||
|
The device pool is a single per-application container of unique devices. Each \a PIConnection talks to real hardware through this pool, so one serial port or socket can feed multiple logical connections.
|
||||||
|
|
||||||
|
# Filters
|
||||||
|
|
||||||
|
A filter is a \a PIPacketExtractor plus a set of bound devices or other filters. When the read thread gets data from a device, that data can be passed to one or more filters. Filters have unique names; use \a filter(name) to get the \a PIPacketExtractor*, and \a filterBoundedDevices() for the list of bound devices/filters. One filter can receive from several sources and be bound to several others.
|
||||||
|
|
||||||
|
# Senders
|
||||||
|
|
||||||
|
Senders are named timers that periodically send data to bound devices. Create a sender or add a device to a sender with \a addSender(). Each sender runs a timer and calls the virtual \a senderData(); the returned value is sent to bound devices. Alternatively use \a setSenderFixedData() to send fixed data without calling \a senderData().
|
||||||
|
|
||||||
|
# Diagnostics
|
||||||
|
|
||||||
|
\a PIConnection creates a \a PIDiagnostics for each device or filter. Access them with \a diagnostic().
|
||||||
|
|
||||||
|
# Configuration
|
||||||
|
|
||||||
|
You can build a \a PIConnection from a config file section or configure it later with \a configureFromConfig() (see \ref config). Devices are described by full paths (see \a PIIODevice documentation). \a makeConfig() produces a string you can insert into a config file.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
\a PIConnection — абстрактный слой над физическими устройствами ввода-вывода: **пул устройств**, **фильтры** (извлечение пакетов), **отправители** (периодическая отправка) и **диагностика**. Несколько соединений могут использовать одно физическое устройство через пул; у каждого устройства есть поток чтения, запуск и остановка — \a startThreadedRead() и \a stopThreadedRead().
|
||||||
|
|
||||||
|
# Пул устройств
|
||||||
|
|
||||||
|
Пул устройств — единственный на приложение набор уникальных устройств. \a PIConnection обращается к железу через этот пул, поэтому один порт или сокет может обслуживать несколько логических соединений.
|
||||||
|
|
||||||
|
# Фильтры
|
||||||
|
|
||||||
|
Фильтр — это \a PIPacketExtractor и набор привязанных устройств или других фильтров. Когда поток чтения получает данные с устройства, они могут передаваться в один или несколько фильтров. У фильтров уникальные имена; \a filter(name) возвращает \a PIPacketExtractor*, \a filterBoundedDevices() — список привязанных устройств и фильтров. Один фильтр может получать данные из нескольких источников и быть привязан к нескольким.
|
||||||
|
|
||||||
|
# Отправители (senders)
|
||||||
|
|
||||||
|
Отправители — именованные таймеры, периодически отправляющие данные на привязанные устройства. Создание или добавление устройства — \a addSender(). У каждого отправителя свой таймер и вызов виртуального \a senderData(); возвращённое значение отправляется на устройства. Либо \a setSenderFixedData() — отправка фиксированных данных без вызова \a senderData().
|
||||||
|
|
||||||
|
# Диагностика
|
||||||
|
|
||||||
|
Для каждого устройства или фильтра создаётся \a PIDiagnostics. Доступ — \a diagnostic().
|
||||||
|
|
||||||
|
# Конфигурация
|
||||||
|
|
||||||
|
\a PIConnection можно собрать из секции конфига или настроить позже через \a configureFromConfig() (см. \ref config). Устройства задаются полными путями (см. документацию \a PIIODevice). \a makeConfig() формирует строку для вставки в конфиг.
|
||||||
42
doc/pages/console.md
Normal file
42
doc/pages/console.md
Normal file
@@ -0,0 +1,42 @@
|
|||||||
|
\~english \page console Tiling console (PIScreen)
|
||||||
|
\~russian \page console Тайлинговая консоль (PIScreen)
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
\a PIScreen is the console screen manager: it runs a drawing thread, hosts **tiles** (layout regions), and routes keyboard and optionally mouse input to the focused tile. Tiles can contain widgets: text rows, scroll bars, lists, buttons, button groups, check boxes, progress bars, \a PICout output, text input, etc.
|
||||||
|
|
||||||
|
# Basic use
|
||||||
|
|
||||||
|
Create a \a PIScreen (optionally with \c startNow = false and a key callback). Call \a enableExitCapture() so that a key (e.g. 'Q') triggers \a waitForFinish(). Add tiles and attach widgets to them; set focus and layout as needed. \a PIScreen inherits \a PIThread and runs the redraw loop; start it before \a waitForFinish() if you did not use \c startNow.
|
||||||
|
|
||||||
|
# Tiles and layout
|
||||||
|
|
||||||
|
Tiles (\a PIScreenTile) are attached to the screen and arranged in a layout. Each tile can hold widgets. Focus determines which tile receives keyboard input. See \a piscreentile.h, \a piscreentiles.h for composed tile widgets and layout types.
|
||||||
|
|
||||||
|
# Widgets
|
||||||
|
|
||||||
|
Widget types are declared in the console headers: list, button, buttons group, check box, progress bar, text input, terminal (PICout output), etc. Add them to a tile; they draw and react to input within the tile. Details and behavior per widget: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
|
||||||
|
|
||||||
|
# Notes
|
||||||
|
|
||||||
|
Some widget options or behaviors may be refined in the implementation; when in doubt, check the header and example usage.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
\a PIScreen — менеджер консольного экрана: поток отрисовки, **тайлы** (области раскладки), маршрутизация клавиатуры и при необходимости мыши в активный тайл. В тайлах размещают виджеты: строки текста, скроллбары, списки, кнопки, группы кнопок, галочки, прогрессбары, вывод \a PICout, текстовый ввод и др.
|
||||||
|
|
||||||
|
# Базовое использование
|
||||||
|
|
||||||
|
Создать \a PIScreen (при необходимости \c startNow = false и callback клавиш). Вызвать \a enableExitCapture(), чтобы клавиша (например 'Q') вызывала \a waitForFinish(). Добавлять тайлы и виджеты, настраивать фокус и раскладку. \a PIScreen наследует \a PIThread и выполняет цикл перерисовки; запустить до \a waitForFinish(), если не использовали \c startNow.
|
||||||
|
|
||||||
|
# Тайлы и раскладка
|
||||||
|
|
||||||
|
Тайлы (\a PIScreenTile) присоединяются к экрану и располагаются в раскладке. В каждом тайле — виджеты. Фокус определяет получателя ввода с клавиатуры. Составные виджеты и типы раскладки: \a piscreentile.h, \a piscreentiles.h.
|
||||||
|
|
||||||
|
# Виджеты
|
||||||
|
|
||||||
|
Типы виджетов объявлены в заголовках консоли: список, кнопка, группа кнопок, галочка, прогрессбар, текстовый ввод, терминал (вывод PICout) и др. Их добавляют в тайл; отрисовка и реакция на ввод — внутри тайла. Подробности по виджетам: \a piscreenconsole.h, \a piscreentiles.h, \a piterminal.h, \a piscreendrawer.h.
|
||||||
|
|
||||||
|
# Замечания
|
||||||
|
|
||||||
|
Часть опций или поведения виджетов может уточняться в реализации; при сомнениях смотрите заголовки и примеры.
|
||||||
52
doc/pages/examples.md
Normal file
52
doc/pages/examples.md
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
\~english \page examples Examples
|
||||||
|
\~russian \page examples Примеры
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
The \c doc/examples directory contains sample code that can be built and run. Below, each file is listed with a short description and a pointer to related documentation where applicable.
|
||||||
|
|
||||||
|
| File | Description | See also |
|
||||||
|
|------|-------------|----------|
|
||||||
|
| pibytearray.cpp | \a PIByteArray and binary stream usage | \ref iostream |
|
||||||
|
| pichunkstream.cpp | \a PIChunkStream read/write | \ref chunk_stream |
|
||||||
|
| picollection.cpp | Collection helpers | — |
|
||||||
|
| picontainers.cpp | Containers (\a PIVector, \a PIMap, etc.) | \ref summary |
|
||||||
|
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, dotted paths | \ref config |
|
||||||
|
| picli.cpp | \a PICLI (stub) | \ref application |
|
||||||
|
| picout.cpp | \a PICout, console output | \ref using_basic |
|
||||||
|
| pievaluator.cpp | \a PIEvaluator, expression evaluation | \ref summary (Mathematics) |
|
||||||
|
| piincludes.cpp | Include paths and module discovery | — |
|
||||||
|
| piiodevice.cpp | \a PIIODevice, custom device and \a PIConfig | \ref config, \ref connection |
|
||||||
|
| pikbdlistener.cpp | \a PIKbdListener, keyboard input | \ref console |
|
||||||
|
| pimutex.cpp | \a PIMutex (minimal) | \ref threading |
|
||||||
|
| piobject.cpp | \a PIObject, events and handlers | \ref PIObject_sec0 |
|
||||||
|
| piparsehelper.cpp | Parse utilities | — |
|
||||||
|
| pistatemachine.cpp | \a PIStateMachine, states and transitions | \ref state_machine |
|
||||||
|
| pitimer.cpp | \a PITimer, periodic callbacks | \ref threading |
|
||||||
|
|
||||||
|
Examples are referenced from the main PIP build when documentation is enabled; paths and build integration may vary by project configuration.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
В каталоге \c doc/examples находятся примеры кода, которые можно собирать и запускать. Ниже перечислены файлы с кратким описанием и ссылкой на связанную документацию.
|
||||||
|
|
||||||
|
| Файл | Описание | См. также |
|
||||||
|
|------|----------|-----------|
|
||||||
|
| pibytearray.cpp | \a PIByteArray и бинарный поток | \ref iostream |
|
||||||
|
| pichunkstream.cpp | Чтение/запись \a PIChunkStream | \ref chunk_stream |
|
||||||
|
| picollection.cpp | Вспомогательные типы коллекций | — |
|
||||||
|
| picontainers.cpp | Контейнеры (\a PIVector, \a PIMap и др.) | \ref summary |
|
||||||
|
| piconfig.cpp | \a PIConfig, \a PIConfig::Entry, точечные пути | \ref config |
|
||||||
|
| picli.cpp | \a PICLI (заглушка) | \ref application |
|
||||||
|
| picout.cpp | \a PICout, вывод в консоль | \ref using_basic |
|
||||||
|
| pievaluator.cpp | \a PIEvaluator, вычисление выражений | \ref summary (Математика) |
|
||||||
|
| piincludes.cpp | Пути включения и поиск модулей | — |
|
||||||
|
| piiodevice.cpp | \a PIIODevice, своё устройство и \a PIConfig | \ref config, \ref connection |
|
||||||
|
| pikbdlistener.cpp | \a PIKbdListener, ввод с клавиатуры | \ref console |
|
||||||
|
| pimutex.cpp | \a PIMutex (минимальный пример) | \ref threading |
|
||||||
|
| piobject.cpp | \a PIObject, события и обработчики | \ref PIObject_sec0 |
|
||||||
|
| piparsehelper.cpp | Утилиты разбора | — |
|
||||||
|
| pistatemachine.cpp | \a PIStateMachine, состояния и переходы | \ref state_machine |
|
||||||
|
| pitimer.cpp | \a PITimer, периодические вызовы | \ref threading |
|
||||||
|
|
||||||
|
Примеры подключаются к сборке PIP при включённой документации; пути и способ интеграции зависят от конфигурации проекта.
|
||||||
@@ -3,8 +3,10 @@
|
|||||||
|
|
||||||
\~english
|
\~english
|
||||||
|
|
||||||
|
\a PIBinaryStream is the binary serialization interface. For versioned, extensible formats with chunk ids see \ref chunk_stream. It is not used standalone; only as a mixin or via concrete classes such as \a PIByteArray and \a PIIOBinaryStream. Use it to save or load any data. Trivial types are read/written as memory blocks unless custom operators are defined; non-trivial types must have stream operators or the code will not compile. Containers are supported under the same rules. Enums are treated as int, bool as one byte. Write operators append to the stream; read operators consume from the beginning. Macros: \c BINARY_STREAM_FRIEND(T), \c BINARY_STREAM_WRITE(T), \c BINARY_STREAM_READ(T) (inside them \c s is the stream, \c v is the value).
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
%PIBinaryStream представляет собой интерфейс бинарной сериализации.
|
%PIBinaryStream представляет собой интерфейс бинарной сериализации. Для версионных расширяемых форматов с id чанков см. \ref chunk_stream.
|
||||||
Не может быть использован в чистом виде, только в виде миксина или
|
Не может быть использован в чистом виде, только в виде миксина или
|
||||||
готовых классов: PIByteArray и PIIOBinaryStream.
|
готовых классов: PIByteArray и PIIOBinaryStream.
|
||||||
|
|
||||||
@@ -28,7 +30,7 @@
|
|||||||
* BINARY_STREAM_READ(T) - чтение из потока, "s" - объект потока, "v" - объект типа T.
|
* BINARY_STREAM_READ(T) - чтение из потока, "s" - объект потока, "v" - объект типа T.
|
||||||
|
|
||||||
Пример:
|
Пример:
|
||||||
\~\code{.cpp}
|
\code{.cpp}
|
||||||
#include <pibytearray.h>
|
#include <pibytearray.h>
|
||||||
|
|
||||||
class MyType {
|
class MyType {
|
||||||
@@ -69,7 +71,7 @@ int main(int argc, char * argv[]) {
|
|||||||
|
|
||||||
\~english Result:
|
\~english Result:
|
||||||
\~russian Результат:
|
\~russian Результат:
|
||||||
\~\code{.cpp}
|
\code{.cpp}
|
||||||
0a000000040000007400650078007400
|
0a000000040000007400650078007400
|
||||||
10 text
|
10 text
|
||||||
|
|
||||||
@@ -84,7 +86,7 @@ operators of this class simply store/restore data block to/from stream:
|
|||||||
Для сохранения/извлечения блоков произвольных данных используется класс PIMemoryBlock.
|
Для сохранения/извлечения блоков произвольных данных используется класс PIMemoryBlock.
|
||||||
Потоковые операторы для него просто сохраняют/извлекают блоки байтов в/из потока:
|
Потоковые операторы для него просто сохраняют/извлекают блоки байтов в/из потока:
|
||||||
|
|
||||||
\~\code{.cpp}
|
\code{.cpp}
|
||||||
float a_read[10], a_write[10];
|
float a_read[10], a_write[10];
|
||||||
for (int i = 0; i < 10; ++i) {
|
for (int i = 0; i < 10; ++i) {
|
||||||
a_read [i] = 0.f;
|
a_read [i] = 0.f;
|
||||||
@@ -103,7 +105,7 @@ for (int i = 0; i < 10; ++i)
|
|||||||
|
|
||||||
\~english Result:
|
\~english Result:
|
||||||
\~russian Результат:
|
\~russian Результат:
|
||||||
\~\code{.cpp}
|
\code{.cpp}
|
||||||
00000000cdcccc3dcdcc4c3e9a99993ecdcccc3e0000003f9a99193f3333333fcdcc4c3f6666663f
|
00000000cdcccc3dcdcc4c3e9a99993ecdcccc3e0000003f9a99193f3333333fcdcc4c3f6666663f
|
||||||
0
|
0
|
||||||
0.1
|
0.1
|
||||||
@@ -119,7 +121,9 @@ for (int i = 0; i < 10; ++i)
|
|||||||
|
|
||||||
\~english
|
\~english
|
||||||
|
|
||||||
|
If a read runs out of data (e.g. end of array or file), the stream's \c wasReadError() returns \c true. Check it after reads to handle errors correctly.
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
Если при чтении из потока не хватило данных (например, закончился массив или файл), то проверка
|
Если при чтении из потока не хватило данных (например, закончился массив или файл), то проверка
|
||||||
объекта потока на wasReadError() вернёт true. Рекомендуется делать эту проверку после чтения
|
объекта потока на \c wasReadError() вернёт \c true. Рекомендуется делать эту проверку после чтения
|
||||||
данных для корректной обработки ошибки.
|
данных для корректной обработки ошибки.
|
||||||
|
|||||||
@@ -8,19 +8,19 @@ PIP - Platform-Independent Primitives - is crossplatform library for C++ develop
|
|||||||
This library can help developers write non-GUI projects much more quickly, efficiently
|
This library can help developers write non-GUI projects much more quickly, efficiently
|
||||||
and customizable than on pure C++.
|
and customizable than on pure C++.
|
||||||
|
|
||||||
Application written on PIP works the same on any system. One can read and write
|
Applications written on PIP work the same on any system. One can read and write
|
||||||
any data types, serialize any types to device channels between any systems.
|
any data types, serialize any types to device channels between any systems.
|
||||||
|
|
||||||
Many common data types, system primitives and devices implemented in this library.
|
Many common data types, system primitives and devices implemented in this library.
|
||||||
|
|
||||||
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handly search
|
PIP also tightly integrates with [CMake](https://cmake.org/) build system, providing handy search for the
|
||||||
main library, additional modules of PIP and several utilites. With
|
main library, additional modules of PIP and several utilities. With
|
||||||
CMake with PIP one can easily generate and use code metainformation or
|
CMake and PIP one can easily generate and use code metainformation or
|
||||||
serialize custom types with it versions back-compatability.
|
serialize custom types with version back-compatibility.
|
||||||
|
|
||||||
Summary one can find at \ref summary page.
|
Summary one can find at \ref summary page.
|
||||||
|
|
||||||
Basic using of PIP described at \ref using_basic page.
|
Basic using — \ref using_basic. Further topics — \ref using_advanced. Configuration — \ref config. Code generation — \ref code_model. Streams: \ref iostream, \ref chunk_stream. State machine — \ref state_machine. Complex I/O — \ref connection. TCP client-server — \ref client_server. Tiling console — \ref console. Application tools — \ref application. Threading — \ref threading. Examples — \ref examples.
|
||||||
|
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
@@ -41,4 +41,4 @@ PIP также тесно интегрируется с системой сбо
|
|||||||
|
|
||||||
Сводку можно найти на странице \ref summary.
|
Сводку можно найти на странице \ref summary.
|
||||||
|
|
||||||
Базовое использование PIP описано на странице \ref using_basic.
|
Базовое использование — \ref using_basic. Дополнительные темы — \ref using_advanced. Конфигурация — \ref config. Кодогенерация — \ref code_model. Потоки: \ref iostream, \ref chunk_stream. Машина состояний — \ref state_machine. Сложный ввод-вывод — \ref connection. TCP клиент-сервер — \ref client_server. Тайлинговая консоль — \ref console. Инструменты приложения — \ref application. Многопоточность — \ref threading. Примеры — \ref examples.
|
||||||
|
|||||||
69
doc/pages/state_machine.md
Normal file
69
doc/pages/state_machine.md
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
\~english \page state_machine State machine
|
||||||
|
\~russian \page state_machine Машина состояний
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
The state machine module (\a PIStateMachine) provides hierarchical states, event-driven and timeout-driven transitions, and aligns with the [SCXML](https://www.w3.org/TR/scxml/) idea of state charts.
|
||||||
|
|
||||||
|
# Concepts
|
||||||
|
|
||||||
|
* **State** — a named node with an optional entry handler. You add states with \a PIStateMachine::addState() (or equivalent on the template subclass), giving an enum or id, name, and optional handler.
|
||||||
|
* **Transition (rule)** — from one state to another, triggered by an event (and optionally guarded). Use \a addRule() to register a transition; you can attach conditions and actions.
|
||||||
|
* **Event** — an integer id posted with \a postEvent(); the machine delivers it to active states and runs the first matching transition guard.
|
||||||
|
* **Conditions** — named flags that can be required for a transition (e.g. \a addCondition() on a \a Rule). Call \a performCondition() to set them; \a resetConditions() to clear.
|
||||||
|
* **Timeout** — a transition can fire after a delay; combine with \a PITimer or internal timeout support in transition classes.
|
||||||
|
|
||||||
|
The machine is a \a PIObject subclass; you can connect timers or other objects to post events. Call \a setInitialState() and \a start() to run. Use \a switchToState() for direct state changes, \a performCondition() to satisfy named conditions.
|
||||||
|
|
||||||
|
# Minimal example
|
||||||
|
|
||||||
|
Define an enum for states, subclass \a PIStateMachine<YourEnum>, add states and rules in the constructor, set the initial state, then start. Post events from keyboard, timer, or other handlers.
|
||||||
|
|
||||||
|
\code{.cpp}
|
||||||
|
enum Mode { Start, Manual, Auto, Finish, End };
|
||||||
|
|
||||||
|
class Machine : public PIStateMachine<Mode> {
|
||||||
|
PIOBJECT_SUBCLASS(Machine, PIObject)
|
||||||
|
public:
|
||||||
|
Machine() {
|
||||||
|
addState(Start, "start", HANDLER(onStart));
|
||||||
|
addState(Manual, "manual", HANDLER(onManual));
|
||||||
|
addState(Auto, "auto", HANDLER(onAuto));
|
||||||
|
addRule(Start, Manual, "init_ok", HANDLER(beginManual));
|
||||||
|
addRule(Manual, Auto, HANDLER(toAuto));
|
||||||
|
addRule(Auto, Manual, HANDLER(toManual));
|
||||||
|
setInitialState(Start);
|
||||||
|
}
|
||||||
|
EVENT_HANDLER(void, onStart) { /* entry */ }
|
||||||
|
EVENT_HANDLER(void, onManual) { /* entry */ }
|
||||||
|
EVENT_HANDLER(void, onAuto) { /* entry */ }
|
||||||
|
EVENT_HANDLER(void, beginManual) { /* transition */ }
|
||||||
|
EVENT_HANDLER(void, toAuto) { }
|
||||||
|
EVENT_HANDLER(void, toManual) { }
|
||||||
|
};
|
||||||
|
|
||||||
|
Machine machine;
|
||||||
|
// In key handler: machine.performCondition("init_ok"); or machine.switchToState(Manual);
|
||||||
|
\endcode
|
||||||
|
|
||||||
|
Full example: doc/examples/pistatemachine.cpp. API details: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
Модуль машины состояний (\a PIStateMachine) предоставляет иерархические состояния, переходы по событиям и по таймауту и ориентирован на идеи [SCXML](https://www.w3.org/TR/scxml/).
|
||||||
|
|
||||||
|
# Концепции
|
||||||
|
|
||||||
|
* **Состояние** — именованный узел с опциональным обработчиком входа. Состояния добавляются через \a PIStateMachine::addState() (или аналог в шаблонном подклассе): enum/id, имя, при необходимости обработчик.
|
||||||
|
* **Переход (правило)** — из одного состояния в другое по событию (и при выполнении условий). \a addRule() регистрирует переход; можно задать условия и действия.
|
||||||
|
* **Событие** — целочисленный id, посылаемый через \a postEvent(); машина доставляет его активным состояниям и выполняет первый подходящий переход.
|
||||||
|
* **Условия** — именованные флаги, требуемые для перехода (например \a addCondition() на \a Rule). Установка через \a performCondition(), сброс — \a resetConditions().
|
||||||
|
* **Таймаут** — переход по истечении времени; используется вместе с \a PITimer или встроенной поддержкой таймаутов в классах переходов.
|
||||||
|
|
||||||
|
Машина — подкласс \a PIObject; к ней можно подключать таймеры и другие объекты для посылки событий. Перед запуском задают \a setInitialState() и вызывают \a start(). \a switchToState() — прямая смена состояния, \a performCondition() — выполнение именованного условия.
|
||||||
|
|
||||||
|
# Минимальный пример
|
||||||
|
|
||||||
|
Определяют enum состояний, подкласс \a PIStateMachine<YourEnum>, в конструкторе добавляют состояния и правила, задают начальное состояние и запускают. События посылают из обработчика клавиш, таймера и т.д. Код минимального примера приведён выше в англоязычной секции.
|
||||||
|
|
||||||
|
Полный пример: doc/examples/pistatemachine.cpp. Детали API: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h.
|
||||||
@@ -35,7 +35,7 @@
|
|||||||
* binary log (\a PIBinaryLog)
|
* binary log (\a PIBinaryLog)
|
||||||
* complex I/O point (\a PIConnection)
|
* complex I/O point (\a PIConnection)
|
||||||
* peering net node (\a PIPeer)
|
* peering net node (\a PIPeer)
|
||||||
* connection quality diagnotic (\a PIDiagnostics)
|
* connection quality diagnostic (\a PIDiagnostics)
|
||||||
* Run-time libraries
|
* Run-time libraries
|
||||||
* external process (\a PIProcess)
|
* external process (\a PIProcess)
|
||||||
* external library (\a PILibrary)
|
* external library (\a PILibrary)
|
||||||
@@ -56,11 +56,13 @@
|
|||||||
* single-instance application control (\a PISingleApplication)
|
* single-instance application control (\a PISingleApplication)
|
||||||
* high-level log (\a PILog)
|
* high-level log (\a PILog)
|
||||||
* translation support (\a PITranslator)
|
* translation support (\a PITranslator)
|
||||||
* State machine ([By stantard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
|
* State machine ([By standard](https://www.w3.org/TR/scxml/)) (\a PIStateMachine)
|
||||||
* High-level TCP client-server
|
* High-level TCP client-server
|
||||||
* server (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
* server (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
||||||
* client (\a PIClientServer::Client)
|
* client (\a PIClientServer::Client)
|
||||||
* Crypt support (\a PICrypt, \a PIAuth)
|
* Crypt support (\a PICrypt, \a PIAuth)
|
||||||
|
* Cloud (\a PICloudClient, \a PICloudServer) — named endpoints over ethernet
|
||||||
|
* HTTP client and server (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
|
|
||||||
@@ -122,3 +124,5 @@
|
|||||||
* сервер (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
* сервер (\a PIClientServer::Server, \a PIClientServer::ServerClient)
|
||||||
* клиент (\a PIClientServer::Client)
|
* клиент (\a PIClientServer::Client)
|
||||||
* Поддержка шифрования (\a PICrypt, \a PIAuth)
|
* Поддержка шифрования (\a PICrypt, \a PIAuth)
|
||||||
|
* Облако (\a PICloudClient, \a PICloudServer) — именованные конечные точки поверх Ethernet
|
||||||
|
* HTTP-клиент и сервер (\a PIHTTPClient, \a PIHTTPServer, \a MicrohttpdServer)
|
||||||
|
|||||||
28
doc/pages/threading.md
Normal file
28
doc/pages/threading.md
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
\~english \page threading Multithreading
|
||||||
|
\~russian \page threading Многопоточность
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
The Thread module provides threads, timers, synchronization primitives and task execution:
|
||||||
|
|
||||||
|
* **PIThread** — run a loop or one-off work in a separate thread. Override \a run() or use the default loop; start/stop with \a start() and \a stop(). Can act as the event performer for \a PIObject (see \ref using_advanced "Threading and events").
|
||||||
|
* **PITimer** — periodic callbacks at a given frequency (e.g. Hz). Connect to a handler; start/stop the timer. Used in \ref using_basic and in state machine examples.
|
||||||
|
* **Synchronization** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock for protecting shared data and coordinating threads.
|
||||||
|
* **PIThreadPoolExecutor** — submit tasks to a fixed pool of worker threads; wait for completion or shutdown.
|
||||||
|
* **PIThreadPoolLoop** — run a function over a range in parallel (parallel-for style).
|
||||||
|
* **PIBlockingDequeue** — blocking producer-consumer queue for passing work between threads.
|
||||||
|
|
||||||
|
Use \a PIMutexLocker (and similar guards) for exception-safe locking. Events from other threads can be queued and processed in the object's thread via \a callQueuedEvents() (see \ref PIObject_sec0). Full API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
Модуль Thread предоставляет потоки, таймеры, примитивы синхронизации и выполнение задач:
|
||||||
|
|
||||||
|
* **PIThread** — выполнение цикла или разовой работы в отдельном потоке. Переопределение \a run() или использование цикла по умолчанию; запуск и остановка — \a start() и \a stop(). Может быть исполнителем событий для \a PIObject (см. \ref using_advanced "Потоки и события").
|
||||||
|
* **PITimer** — периодические вызовы с заданной частотой (например в Гц). Подключение обработчика; запуск и остановка таймера. Используется в \ref using_basic и в примерах машины состояний.
|
||||||
|
* **Синхронизация** — \a PIMutex, \a PISpinlock, \a PIConditionVariable, \a PISemaphore, \a PIReadWriteLock для защиты общих данных и согласования потоков.
|
||||||
|
* **PIThreadPoolExecutor** — отправка задач в пул рабочих потоков; ожидание завершения или остановка пула.
|
||||||
|
* **PIThreadPoolLoop** — параллельный запуск функции по диапазону (стиль parallel-for).
|
||||||
|
* **PIBlockingDequeue** — блокирующая очередь производитель–потребитель для передачи работы между потоками.
|
||||||
|
|
||||||
|
Для исключений-безопасной блокировки используйте \a PIMutexLocker и аналогичные охранные классы. События из других потоков можно ставить в очередь и обрабатывать в потоке объекта через \a callQueuedEvents() (см. \ref PIObject_sec0). Полный API: \a pithread.h, \a pitimer.h, \a pimutex.h, \a pithreadpoolexecutor.h, \a piblockingqueue.h, \a pithreadmodule.h.
|
||||||
64
doc/pages/using_advanced.md
Normal file
64
doc/pages/using_advanced.md
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
\~english \page using_advanced Further topics
|
||||||
|
\~russian \page using_advanced Дополнительные темы
|
||||||
|
|
||||||
|
\~english
|
||||||
|
|
||||||
|
After \ref using_basic you may want to explore:
|
||||||
|
|
||||||
|
* \ref summary — full list of PIP modules and classes (containers, I/O, threading, math, state machine, etc.).
|
||||||
|
* \ref config — reading and writing configuration with \a PIConfig (files, dotted paths, INI-style sections).
|
||||||
|
* \ref code_model — code generation: metadata, serialization operators, PIMETA, \c pip_cmg and CMake integration.
|
||||||
|
* \ref iostream — binary streams (\a PIBinaryStream, \a PIByteArray), operators and \a PIMemoryBlock.
|
||||||
|
* \ref chunk_stream — versioned serialization with \a PIChunkStream (chunks by id, backward compatibility).
|
||||||
|
* \ref state_machine — state machine concepts, states, transitions, conditions, \a PIStateMachine.
|
||||||
|
* \ref connection — complex I/O: \a PIConnection, device pool, filters, senders, diagnostics.
|
||||||
|
* \ref client_server — TCP server and client (\a PIClientServer::Server, \a PIClientServer::Client).
|
||||||
|
* \ref console — tiling console \a PIScreen, tiles, widgets (list, button, progress, input, etc.).
|
||||||
|
* \ref application — application-level: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
|
||||||
|
* \ref threading — multithreading: \a PIThread, \a PITimer, synchronization, executor, blocking queue.
|
||||||
|
* \ref examples — index of sample code in doc/examples.
|
||||||
|
|
||||||
|
Events and handlers are documented on the \a PIObject reference page (\ref PIObject_sec0).
|
||||||
|
|
||||||
|
\par Threading and events
|
||||||
|
|
||||||
|
Many PIP classes inherit \a PIObject and use events: handlers can be invoked directly or queued. When events are queued (e.g. from another thread), they are dispatched in the object's thread; call \a callQueuedEvents() or \a maybeCallQueuedEvents() to drain the queue. \a PIThread can act as the performer for such objects. See \ref PIObject_sec0 and \a PIThread.
|
||||||
|
|
||||||
|
\par Introspection
|
||||||
|
|
||||||
|
With \c PIP_INTROSPECTION defined at build time, the introspection module provides macros and APIs to traverse objects and containers at runtime (e.g. for debugging or serialization). Build PIP with this option and link the introspection library; see the introspection headers in \a piintrospection_base.h and related files.
|
||||||
|
|
||||||
|
\par GPU / OpenCL
|
||||||
|
|
||||||
|
The OpenCL module wraps OpenCL for buffers and programs. See \a piopencl.h for the public API. Behavior and limitations may depend on the implementation; check the header and backend when integrating.
|
||||||
|
|
||||||
|
\~russian
|
||||||
|
|
||||||
|
После \ref using_basic имеет смысл перейти к:
|
||||||
|
|
||||||
|
* \ref summary — полный перечень модулей и классов PIP (контейнеры, ввод-вывод, потоки, математика, машина состояний и др.).
|
||||||
|
* \ref config — чтение и запись конфигурации с помощью \a PIConfig (файлы, точечные пути, секции в стиле INI).
|
||||||
|
* \ref code_model — кодогенерация: метаинформация, операторы сериализации, PIMETA, утилита \c pip_cmg и интеграция с CMake.
|
||||||
|
* \ref iostream — бинарные потоки (\a PIBinaryStream, \a PIByteArray), операторы и \a PIMemoryBlock.
|
||||||
|
* \ref chunk_stream — версионная сериализация с \a PIChunkStream (чанки по id, обратная совместимость).
|
||||||
|
* \ref state_machine — машина состояний: концепции, состояния, переходы, условия, \a PIStateMachine.
|
||||||
|
* \ref connection — сложный ввод-вывод: \a PIConnection, пул устройств, фильтры, отправители, диагностика.
|
||||||
|
* \ref client_server — TCP-сервер и клиент (\a PIClientServer::Server, \a PIClientServer::Client).
|
||||||
|
* \ref console — тайлинговая консоль \a PIScreen, тайлы, виджеты (список, кнопка, прогресс, ввод и др.).
|
||||||
|
* \ref application — уровень приложения: \a PICLI, \a PILog, \a PISystemMonitor, \a PISingleApplication, \a PITranslator.
|
||||||
|
* \ref threading — многопоточность: \a PIThread, \a PITimer, синхронизация, исполнитель, блокирующая очередь.
|
||||||
|
* \ref examples — перечень примеров в doc/examples.
|
||||||
|
|
||||||
|
События и обработчики описаны на странице \a PIObject (\ref PIObject_sec0).
|
||||||
|
|
||||||
|
\par Потоки и события
|
||||||
|
|
||||||
|
Многие классы PIP наследуют \a PIObject и используют события: обработчики могут вызываться сразу или ставиться в очередь. При постановке в очередь (например из другого потока) они обрабатываются в потоке объекта; вызов \a callQueuedEvents() или \a maybeCallQueuedEvents() обрабатывает очередь. \a PIThread может выступать исполнителем для таких объектов. См. \ref PIObject_sec0 и \a PIThread.
|
||||||
|
|
||||||
|
\par Интроспекция
|
||||||
|
|
||||||
|
При сборке с макросом \c PIP_INTROSPECTION модуль интроспекции предоставляет макросы и API для обхода объектов и контейнеров в runtime (например для отладки или сериализации). Соберите PIP с этой опцией и подключите библиотеку интроспекции; см. заголовки \a piintrospection_base.h и связанные.
|
||||||
|
|
||||||
|
\par GPU / OpenCL
|
||||||
|
|
||||||
|
Модуль OpenCL — обёртка над OpenCL для буферов и программ. Публичный API: \a piopencl.h. Поведение и ограничения зависят от реализации; при интеграции смотрите заголовок и бэкенд.
|
||||||
@@ -3,10 +3,10 @@
|
|||||||
|
|
||||||
\~english
|
\~english
|
||||||
|
|
||||||
Many novice programmers are solved many common task with system integrity: output to console,
|
Many novice programmers face common tasks when interacting with the system: output to console,
|
||||||
keyboard buttons press detecting, working with serial ports, ethernet or files, and many other.
|
detecting keyboard presses, working with serial ports, ethernet or files, and more.
|
||||||
These tasks can solve this library, and code, based only on PIP will be compile and work
|
This library addresses these tasks; code based on PIP will compile and work
|
||||||
similar on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
|
similarly on many systems: Windows, any Linux, Red Hat, FreeBSD, MacOS X and QNX.
|
||||||
Typical application on PIP looks like this: \n
|
Typical application on PIP looks like this: \n
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
@@ -112,17 +112,17 @@ int main(int argc, char * argv[]) {
|
|||||||
This code demonstrates simple interactive configurable program, which can be started with console
|
This code demonstrates simple interactive configurable program, which can be started with console
|
||||||
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
|
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
|
||||||
\a PIThread and reimplement \a run() function.
|
\a PIThread and reimplement \a run() function.
|
||||||
\n Many PIP classes has events and event handlers, which can be connected one to another.
|
\n Many PIP classes have events and event handlers, which can be connected one to another.
|
||||||
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
|
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
|
||||||
\n To configure your program from file use \a PIConfig.
|
\n To configure your program from file use \a PIConfig (see \ref config).
|
||||||
\n If you want more information see \ref using_advanced
|
\n For more topics see \ref using_advanced.
|
||||||
|
|
||||||
\~russian
|
\~russian
|
||||||
|
|
||||||
Этот код демонстрирует простую конфигурируемую программу, которая может быть запущена с
|
Этот код демонстрирует простую конфигурируемую программу, которая может быть запущена с
|
||||||
This code demonstrates simple interactive configurable program, which can be started with console
|
консолью или без неё, с отладочным выводом или без. \b MainClass — центральный класс, который
|
||||||
display or not, and with debug or not. \b MainClass is central class that also can be inherited from
|
также может быть унаследован от \a PIThread с переопределением \a run().
|
||||||
\a PIThread and reimplement \a run() function.
|
\n У многих классов PIP есть события и обработчики, которые можно связывать между собой.
|
||||||
\n Many PIP classes has events and event handlers, which can be connected one to another.
|
Подробности — на странице \a PIObject (\ref PIObject_sec0).
|
||||||
Details you can see at \a PIObject reference page (\ref PIObject_sec0).
|
\n Для настройки приложения из файла используйте \a PIConfig (см. \ref config).
|
||||||
\n To configure your program from file use \a PIConfig.
|
\n Дополнительные темы — на странице \ref using_advanced.
|
||||||
|
|||||||
@@ -1,35 +0,0 @@
|
|||||||
/*
|
|
||||||
PIP - Platform Independent Primitives
|
|
||||||
Tile for PIScreen with PIConsole API
|
|
||||||
Andrey Bychkov work.a.b@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 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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include "piscreenconsole.h"
|
|
||||||
|
|
||||||
using namespace PIScreenTypes;
|
|
||||||
|
|
||||||
|
|
||||||
TileVars::TileVars(const PIString & n): PIScreenTile(n) {
|
|
||||||
alignment = Left;
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
void TileVars::sizeHint(int & w, int & h) const {}
|
|
||||||
|
|
||||||
void TileVars::drawEvent(PIScreenDrawer * d) {}
|
|
||||||
|
|
||||||
|
|
||||||
PIScreenConsoleTile::PIScreenConsoleTile() {}
|
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file piapplicationmodule.h
|
||||||
|
* \ingroup Application
|
||||||
|
* \~\brief
|
||||||
|
* \~english Application-level classes.
|
||||||
|
* \~russian Классы уровня "приложение".
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public CLI, logging, single-application, system monitoring, and translation headers.
|
||||||
|
* \~russian Подключает публичные заголовки CLI, логирования, одиночного приложения, системного мониторинга и перевода.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -30,14 +40,14 @@
|
|||||||
//! target_link_libraries([target] PIP)
|
//! target_link_libraries([target] PIP)
|
||||||
//! \endcode
|
//! \endcode
|
||||||
//!
|
//!
|
||||||
//! \~english \par Common
|
|
||||||
//! \~russian \par Общее
|
|
||||||
//!
|
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides some classes for help to create application
|
//! This umbrella header includes public Application classes for command-line
|
||||||
|
//! parsing, logging, single-instance control, process monitoring and translation.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы предоставляют классы для облегчения создания приложения
|
//! Этот зонтичный заголовок подключает публичные классы Application для
|
||||||
|
//! разбора командной строки, ведения лога, контроля одного экземпляра,
|
||||||
|
//! мониторинга процесса и перевода.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picli.h
|
//! \~\file picli.h
|
||||||
* \ingroup Application
|
//! \~\ingroup Application
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Command-Line parser
|
//! \~english Command-line argument parser
|
||||||
* \~russian Парсер командной строки
|
//! \~russian Парсер аргументов командной строки
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Command-Line Parser
|
Command-Line Parser
|
||||||
@@ -29,10 +28,15 @@
|
|||||||
#include "piset.h"
|
#include "piset.h"
|
||||||
#include "pistringlist.h"
|
#include "pistringlist.h"
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Command-Line parser.
|
//! \~english Command-line argument parser class
|
||||||
//! \~russian Парсер командной строки.
|
//! \~russian Класс парсера аргументов командной строки
|
||||||
|
//! \details
|
||||||
|
//! \~english The PICLI class provides convenient parsing of command-line arguments. It supports short keys (e.g., -c), full keys (e.g.,
|
||||||
|
//! --console), and arguments with/without values.
|
||||||
|
//! \~russian Класс PICLI предоставляет удобный разбор аргументов командной строки. Поддерживаются короткие ключи (например, -c), полные
|
||||||
|
//! ключи (например, --console) и аргументы с значениями/без значений.
|
||||||
class PIP_EXPORT PICLI {
|
class PIP_EXPORT PICLI {
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs %PICLI from "argc" and "argv" from "int main()" method.
|
//! \~english Constructs %PICLI from "argc" and "argv" from "int main()" method.
|
||||||
@@ -64,13 +68,25 @@ public:
|
|||||||
//! \~english Returns unparsed command-line argument by index "index". Index 0 is program execute command.
|
//! \~english Returns unparsed command-line argument by index "index". Index 0 is program execute command.
|
||||||
//! \~russian Возвращает исходный аргумент командной строки по индексу "index". Индекс 0 это команда вызова программы.
|
//! \~russian Возвращает исходный аргумент командной строки по индексу "index". Индекс 0 это команда вызова программы.
|
||||||
PIString rawArgument(int index);
|
PIString rawArgument(int index);
|
||||||
|
|
||||||
|
//! \~english Returns mandatory positional argument by index.
|
||||||
|
//! \~russian Возвращает обязательный позиционный аргумент по индексу.
|
||||||
PIString mandatoryArgument(int index);
|
PIString mandatoryArgument(int index);
|
||||||
|
|
||||||
|
//! \~english Returns optional positional argument by index.
|
||||||
|
//! \~russian Возвращает необязательный позиционный аргумент по индексу.
|
||||||
PIString optionalArgument(int index);
|
PIString optionalArgument(int index);
|
||||||
|
|
||||||
//! \~english Returns unparsed command-line arguments.
|
//! \~english Returns unparsed command-line arguments.
|
||||||
//! \~russian Возвращает исходные аргументы командной строки.
|
//! \~russian Возвращает исходные аргументы командной строки.
|
||||||
const PIStringList & rawArguments();
|
const PIStringList & rawArguments();
|
||||||
|
|
||||||
|
//! \~english Returns all mandatory positional arguments.
|
||||||
|
//! \~russian Возвращает все обязательные позиционные аргументы.
|
||||||
const PIStringList & mandatoryArguments();
|
const PIStringList & mandatoryArguments();
|
||||||
|
|
||||||
|
//! \~english Returns all optional positional arguments.
|
||||||
|
//! \~russian Возвращает все необязательные позиционные аргументы.
|
||||||
const PIStringList & optionalArguments();
|
const PIStringList & optionalArguments();
|
||||||
|
|
||||||
//! \~english Returns program execute command without arguments.
|
//! \~english Returns program execute command without arguments.
|
||||||
@@ -93,18 +109,52 @@ public:
|
|||||||
//! \~russian Возвращает полный ключ аргумента "name" или пустую строку, если аргумента нет.
|
//! \~russian Возвращает полный ключ аргумента "name" или пустую строку, если аргумента нет.
|
||||||
PIString argumentFullKey(const PIString & name);
|
PIString argumentFullKey(const PIString & name);
|
||||||
|
|
||||||
|
//! \~english Returns prefix used for short keys.
|
||||||
|
//! \~russian Возвращает префикс коротких ключей.
|
||||||
const PIString & shortKeyPrefix() const { return _prefix_short; }
|
const PIString & shortKeyPrefix() const { return _prefix_short; }
|
||||||
|
|
||||||
|
//! \~english Returns prefix used for full keys.
|
||||||
|
//! \~russian Возвращает префикс полных ключей.
|
||||||
const PIString & fullKeyPrefix() const { return _prefix_full; }
|
const PIString & fullKeyPrefix() const { return _prefix_full; }
|
||||||
|
|
||||||
|
//! \~english Returns expected count of mandatory positional arguments.
|
||||||
|
//! \~russian Возвращает ожидаемое количество обязательных позиционных аргументов.
|
||||||
int mandatoryArgumentsCount() const { return _count_mand; }
|
int mandatoryArgumentsCount() const { return _count_mand; }
|
||||||
|
|
||||||
|
//! \~english Returns expected count of optional positional arguments.
|
||||||
|
//! \~russian Возвращает ожидаемое количество необязательных позиционных аргументов.
|
||||||
int optionalArgumentsCount() const { return _count_opt; }
|
int optionalArgumentsCount() const { return _count_opt; }
|
||||||
|
|
||||||
|
//! \~english Sets prefix used for short keys such as "-d".
|
||||||
|
//! \~russian Устанавливает префикс коротких ключей, например "-d".
|
||||||
void setShortKeyPrefix(const PIString & prefix);
|
void setShortKeyPrefix(const PIString & prefix);
|
||||||
|
|
||||||
|
//! \~english Sets prefix used for full keys such as "--debug".
|
||||||
|
//! \~russian Устанавливает префикс полных ключей, например "--debug".
|
||||||
void setFullKeyPrefix(const PIString & prefix);
|
void setFullKeyPrefix(const PIString & prefix);
|
||||||
|
|
||||||
|
//! \~english Sets count of mandatory positional arguments collected before optional ones.
|
||||||
|
//! \~russian Устанавливает количество обязательных позиционных аргументов, собираемых до необязательных.
|
||||||
void setMandatoryArgumentsCount(const int count);
|
void setMandatoryArgumentsCount(const int count);
|
||||||
|
|
||||||
|
//! \~english Sets count of optional positional arguments. Negative value means unlimited.
|
||||||
|
//! \~russian Устанавливает количество необязательных позиционных аргументов. Отрицательное значение означает без ограничения.
|
||||||
void setOptionalArgumentsCount(const int count);
|
void setOptionalArgumentsCount(const int count);
|
||||||
|
|
||||||
|
//! \~english Returns debug mode flag.
|
||||||
|
//! \~russian Возвращает флаг режима отладки.
|
||||||
bool debug() const { return debug_; }
|
bool debug() const { return debug_; }
|
||||||
|
|
||||||
|
//! \~english Enables or disables debug mode.
|
||||||
|
//! \~russian Включает или выключает режим отладки.
|
||||||
void setDebug(bool debug) { debug_ = debug; }
|
void setDebug(bool debug) { debug_ = debug; }
|
||||||
|
|
||||||
|
//! \~english Returns class name.
|
||||||
|
//! \~russian Возвращает имя класса.
|
||||||
PIConstChars className() const { return "PICLI"; }
|
PIConstChars className() const { return "PICLI"; }
|
||||||
|
|
||||||
|
//! \~english Returns human-readable object name.
|
||||||
|
//! \~russian Возвращает читаемое имя объекта.
|
||||||
PIString name() const { return PIStringAscii("CLI"); }
|
PIString name() const { return PIStringAscii("CLI"); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pilog.h
|
//! \~\file pilog.h
|
||||||
* \ingroup Application
|
//! \~\ingroup Application
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english High-level log
|
//! \~english High-level log
|
||||||
* \~russian Высокоуровневый лог
|
//! \~russian Высокоуровневый лог
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
High-level log
|
High-level log
|
||||||
@@ -30,15 +29,23 @@
|
|||||||
#include "piiostream.h"
|
#include "piiostream.h"
|
||||||
#include "pithread.h"
|
#include "pithread.h"
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english High-level log
|
//! \~english High-level log
|
||||||
//! \~russian Высокоуровневый лог
|
//! \~russian Высокоуровневый лог
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Provides log with optional file and console output, with configurable timestamp format and line format.
|
||||||
|
//! \~russian Предоставляет лог с опциональным выводом в файл и консоль, с настраиваемым форматом метки времени и форматом строки.
|
||||||
class PIP_EXPORT PILog: public PIThread {
|
class PIP_EXPORT PILog: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PILog, PIThread)
|
PIOBJECT_SUBCLASS(PILog, PIThread)
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs log with console output, timestamped lines and rotated log files.
|
||||||
|
//! \~russian Создает лог с выводом в консоль, строками с метками времени и ротацией файлов.
|
||||||
PILog();
|
PILog();
|
||||||
|
|
||||||
|
//! \~english Stops logging thread and flushes queued messages.
|
||||||
|
//! \~russian Останавливает поток логирования и дописывает сообщения из очереди.
|
||||||
~PILog();
|
~PILog();
|
||||||
|
|
||||||
//! \~english Message category
|
//! \~english Message category
|
||||||
@@ -58,8 +65,8 @@ public:
|
|||||||
All /** \~english All \~russian Все */ = 0xFF,
|
All /** \~english All \~russian Все */ = 0xFF,
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Set output channel \"o\" to \"on\".
|
//! \~english Enables or disables output channel "o".
|
||||||
//! \~russian Установить канал вывода \"o\" в \"on\".
|
//! \~russian Включает или выключает канал вывода "o".
|
||||||
void setOutput(Output o, bool on = true) { output.setFlag(o, on); }
|
void setOutput(Output o, bool on = true) { output.setFlag(o, on); }
|
||||||
|
|
||||||
//! \~english Returns prefix for filename.
|
//! \~english Returns prefix for filename.
|
||||||
@@ -80,7 +87,7 @@ public:
|
|||||||
|
|
||||||
|
|
||||||
//! \~english Returns directory for log files.
|
//! \~english Returns directory for log files.
|
||||||
//! \~russian Возвращает директорию для файлов.
|
//! \~russian Возвращает директорию файлов лога.
|
||||||
PIString dir() const { return log_dir; }
|
PIString dir() const { return log_dir; }
|
||||||
|
|
||||||
//! \~english Set directory for log files. Should be set \b after \a setLogName()!
|
//! \~english Set directory for log files. Should be set \b after \a setLogName()!
|
||||||
@@ -92,8 +99,8 @@ public:
|
|||||||
//! \~russian Возвращает время жизни файла.
|
//! \~russian Возвращает время жизни файла.
|
||||||
PISystemTime fileSplitTime() const { return split_time; }
|
PISystemTime fileSplitTime() const { return split_time; }
|
||||||
|
|
||||||
//! \~english Set lifetime for file. Each "st" interval new file will be created.
|
//! \~english Sets log file rotation interval. A new file is created every "st".
|
||||||
//! \~russian Устанавливает время жизни файла. Каждый интервал "st" будет создан новый файл.
|
//! \~russian Устанавливает интервал ротации файла лога. Новый файл создается каждые "st".
|
||||||
void setFileSplitTime(PISystemTime st) { split_time = st; }
|
void setFileSplitTime(PISystemTime st) { split_time = st; }
|
||||||
|
|
||||||
|
|
||||||
@@ -110,8 +117,8 @@ public:
|
|||||||
//! \~russian Возвращает формат строки.
|
//! \~russian Возвращает формат строки.
|
||||||
PIString lineFormat() const { return line_format; }
|
PIString lineFormat() const { return line_format; }
|
||||||
|
|
||||||
//! \~english Set line format. "t" is timestamp, "c" is category and "m" is message. Default is "t - c: m".
|
//! \~english Sets line format. "t" is timestamp, "c" is category and "m" is message. Default is "t - c: m".
|
||||||
//! \~russian Устанавливает формат строки. "t" - метка времени, "c" - категория и "m" - сообщение. По умолчанию "t - c: m".
|
//! \~russian Устанавливает формат строки. "t" - метка времени, "c" - категория, "m" - сообщение. По умолчанию "t - c: m".
|
||||||
void setLineFormat(const PIString & f);
|
void setLineFormat(const PIString & f);
|
||||||
|
|
||||||
|
|
||||||
@@ -119,9 +126,8 @@ public:
|
|||||||
//! \~russian Возвращает максимальную категорию.
|
//! \~russian Возвращает максимальную категорию.
|
||||||
Level level() const { return max_level; }
|
Level level() const { return max_level; }
|
||||||
|
|
||||||
//! \~english Set maximum level. All levels greater than \"l\" will be ignored. Default is \a Level::Debug.
|
//! \~english Sets maximum accepted level. Messages above "l" are ignored. Default is \a Level::Debug.
|
||||||
//! \~russian Устанавливает максимальную категорию. Все сообщения с большей категорией, чем \"l\", будут игнорироваться. По умолчанию \a
|
//! \~russian Устанавливает максимальный принимаемый уровень. Сообщения выше "l" игнорируются. По умолчанию \a Level::Debug.
|
||||||
//! Level::Debug.
|
|
||||||
void setLevel(Level l);
|
void setLevel(Level l);
|
||||||
|
|
||||||
//! \~english Returns \a PICout for \a Level::Error level.
|
//! \~english Returns \a PICout for \a Level::Error level.
|
||||||
@@ -140,12 +146,12 @@ public:
|
|||||||
//! \~russian Возвращает \a PICout для категории \a Level::Debug.
|
//! \~russian Возвращает \a PICout для категории \a Level::Debug.
|
||||||
PICout debug(PIObject * context = nullptr);
|
PICout debug(PIObject * context = nullptr);
|
||||||
|
|
||||||
//! \~english Write all queued lines and stop. Also called in destructor.
|
//! \~english Writes all queued lines and stops logging. Also called from destructor.
|
||||||
//! \~russian Записывает все строки из очереди и останавливается. Также вызывается в деструкторе.
|
//! \~russian Записывает все строки из очереди и останавливает логирование. Также вызывается из деструктора.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
//! \~english Read all previous and current log content and returns them as %PIStringList.
|
//! \~english Reads all rotated and current log lines and returns them as %PIStringList.
|
||||||
//! \~russian Читает все предыдущие и текущий логи и возвращает их как %PIStringList.
|
//! \~russian Читает строки из текущего и уже ротированных логов и возвращает их как %PIStringList.
|
||||||
PIStringList readAllLogs() const;
|
PIStringList readAllLogs() const;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pisingleapplication.h
|
//! \~\file pisingleapplication.h
|
||||||
* \ingroup Application
|
//! \~\ingroup Application
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Single-instance application control
|
//! \~english Single-instance application control
|
||||||
* \~russian Контроль одного экземпляра приложения
|
//! \~russian Контроль одного экземпляра приложения
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Single application
|
Single application
|
||||||
@@ -30,35 +29,44 @@
|
|||||||
|
|
||||||
class PISharedMemory;
|
class PISharedMemory;
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Single-instance application control.
|
//! \~english Single-instance application control.
|
||||||
//! \~russian Контроль одного экземпляра приложения.
|
//! \~russian Контроль одного экземпляра приложения.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english The PISingleApplication class provides single-instance application control. It allows detecting if the current application
|
||||||
|
//! instance is the first one launched and enables inter-process communication between multiple instances. Multiple instances with the same
|
||||||
|
//! "app_name" can detect each other and communicate. The first instance becomes the server, receiving messages from subsequent instances.
|
||||||
|
//! \~russian Класс PISingleApplication предоставляет контроль одного экземпляра приложения. Он позволяет определить, является ли текущий
|
||||||
|
//! экземпляр первым запущенным, и обеспечивает межпроцессное взаимодействие между несколькими экземплярами. Несколько экземпляров с
|
||||||
|
//! одинаковым "app_name" могут обнаруживать друг друга и обмениваться сообщениями. Первый экземпляр становится сервером, принимающим
|
||||||
|
//! сообщения от последующих экземпляров.
|
||||||
|
|
||||||
class PIP_EXPORT PISingleApplication: public PIThread {
|
class PIP_EXPORT PISingleApplication: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PISingleApplication, PIThread);
|
PIOBJECT_SUBCLASS(PISingleApplication, PIThread);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Construct %PISingleApplication with name "app_name"
|
//! \~english Constructs %PISingleApplication for application name "app_name".
|
||||||
//! \~russian Создает %PISingleApplication с именем "app_name"
|
//! \~russian Создает %PISingleApplication для имени приложения "app_name".
|
||||||
PISingleApplication(const PIString & app_name = PIString());
|
PISingleApplication(const PIString & app_name = PIString());
|
||||||
|
|
||||||
|
//! \~english Stops instance monitoring and releases shared resources.
|
||||||
|
//! \~russian Останавливает мониторинг экземпляра и освобождает общие ресурсы.
|
||||||
~PISingleApplication();
|
~PISingleApplication();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns if this application instance is launched first
|
//! \~english Returns whether this process is the first launched instance.
|
||||||
//! \~russian Возвращает первым ли был запущен этот экземпляр приложения
|
//! \~russian Возвращает, является ли этот процесс первым запущенным экземпляром.
|
||||||
bool isFirst() const;
|
bool isFirst() const;
|
||||||
|
|
||||||
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
|
|
||||||
EVENT1(messageReceived, PIByteArray, m);
|
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void sendMessage(const PIByteArray & m)
|
//! \fn void sendMessage(const PIByteArray & m)
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Send message "m" to first launched application
|
//! \~english Sends message "m" to the first launched application instance
|
||||||
//! \~russian Посылает сообщение "m" первому запущеному приложению
|
//! \~russian Посылает сообщение "m" первому запущенному экземпляру приложения
|
||||||
|
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \events
|
//! \events
|
||||||
@@ -66,8 +74,9 @@ public:
|
|||||||
|
|
||||||
//! \fn void messageReceived(PIByteArray m)
|
//! \fn void messageReceived(PIByteArray m)
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Raise on first launched application receive message from another
|
//! \~english Emitted by the first launched application when receiving a message from another instance
|
||||||
//! \~russian Вызывается первым запущеным приложением по приему сообщения от других
|
//! \~russian Вызывается первым запущенным приложением при получении сообщения от другого экземпляра
|
||||||
|
EVENT1(messageReceived, PIByteArray, m);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pisystemmonitor.h
|
//! \~\file pisystemmonitor.h
|
||||||
* \ingroup Application
|
//! \~\ingroup Application
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english System resources monitoring
|
//! \~english System resources monitoring
|
||||||
* \~russian Мониторинг ресурсов системы
|
//! \~russian Мониторинг ресурсов системы
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Process resource monitor
|
Process resource monitor
|
||||||
@@ -30,23 +29,30 @@
|
|||||||
#include "pithread.h"
|
#include "pithread.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Process monitoring.
|
//! \~english Process and thread resource monitoring.
|
||||||
//! \~russian Мониторинг процесса.
|
//! \~russian Мониторинг ресурсов процесса и его потоков.
|
||||||
|
//! \details
|
||||||
|
//! \~english This module provides process and system resource monitoring capabilities including CPU usage, memory consumption, and thread
|
||||||
|
//! statistics. It supports cross-platform monitoring on Linux, Windows, macOS, and ESP platforms.
|
||||||
|
//! \~russian Этот модуль предоставляет возможности мониторинга ресурсов процессов и системы, включая использование CPU, потребление памяти
|
||||||
|
//! и статистику потоков. Поддерживается кроссплатформенный мониторинг на Linux, Windows, macOS и ESP платформах.
|
||||||
class PIP_EXPORT PISystemMonitor: public PIThread {
|
class PIP_EXPORT PISystemMonitor: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PISystemMonitor, PIThread);
|
PIOBJECT_SUBCLASS(PISystemMonitor, PIThread);
|
||||||
friend class PIIntrospectionServer;
|
friend class PIIntrospectionServer;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs unassigned %PISystemMonitor
|
//! \~english Constructs unassigned %PISystemMonitor.
|
||||||
//! \~russian Создает непривязанный %PISystemMonitor
|
//! \~russian Создает непривязанный %PISystemMonitor.
|
||||||
PISystemMonitor();
|
PISystemMonitor();
|
||||||
|
|
||||||
|
//! \~english Stops monitoring and detaches from the current process target.
|
||||||
|
//! \~russian Останавливает мониторинг и отсоединяет объект от текущей цели.
|
||||||
~PISystemMonitor();
|
~PISystemMonitor();
|
||||||
|
|
||||||
#pragma pack(push, 1)
|
#pragma pack(push, 1)
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Process statistics (fixed-size fields).
|
//! \~english Process statistics (fixed-size fields).
|
||||||
//! \~russian Статистика процесса (фиксированные поля).
|
//! \~russian Статистика процесса (фиксированные поля).
|
||||||
@@ -95,16 +101,16 @@ public:
|
|||||||
//! \~russian Память данных в байтах
|
//! \~russian Память данных в байтах
|
||||||
ullong data_memsize = 0;
|
ullong data_memsize = 0;
|
||||||
|
|
||||||
//! \~english
|
//! \~english Total RAM in bytes.
|
||||||
//! \~russian
|
//! \~russian Общий объем RAM в байтах.
|
||||||
ullong ram_total = 0;
|
ullong ram_total = 0;
|
||||||
|
|
||||||
//! \~english
|
//! \~english Free RAM in bytes.
|
||||||
//! \~russian
|
//! \~russian Свободный объем RAM в байтах.
|
||||||
ullong ram_free = 0;
|
ullong ram_free = 0;
|
||||||
|
|
||||||
//! \~english
|
//! \~english Used RAM in bytes.
|
||||||
//! \~russian
|
//! \~russian Используемый объем RAM в байтах.
|
||||||
ullong ram_used = 0;
|
ullong ram_used = 0;
|
||||||
|
|
||||||
//! \~english CPU load in kernel space
|
//! \~english CPU load in kernel space
|
||||||
@@ -116,7 +122,7 @@ public:
|
|||||||
float cpu_load_user = 0.f;
|
float cpu_load_user = 0.f;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Thread statistics (fixed-size fields).
|
//! \~english Thread statistics (fixed-size fields).
|
||||||
//! \~russian Статистика потока (фиксированные поля).
|
//! \~russian Статистика потока (фиксированные поля).
|
||||||
@@ -151,13 +157,13 @@ public:
|
|||||||
};
|
};
|
||||||
#pragma pack(pop)
|
#pragma pack(pop)
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Process statistics.
|
//! \~english Process statistics.
|
||||||
//! \~russian Статистика процесса.
|
//! \~russian Статистика процесса.
|
||||||
struct PIP_EXPORT ProcessStats: ProcessStatsFixed {
|
struct PIP_EXPORT ProcessStats: ProcessStatsFixed {
|
||||||
//! \~english Fill human-readable fields
|
//! \~english Fills human-readable memory size fields.
|
||||||
//! \~russian Заполнить читаемые поля
|
//! \~russian Заполняет поля с человекочитаемыми размерами памяти.
|
||||||
void makeStrings();
|
void makeStrings();
|
||||||
|
|
||||||
//! \~english Execution command
|
//! \~english Execution command
|
||||||
@@ -189,7 +195,7 @@ public:
|
|||||||
PIString data_memsize_readable;
|
PIString data_memsize_readable;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \ingroup Application
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Thread statistics.
|
//! \~english Thread statistics.
|
||||||
//! \~russian Статистика потока.
|
//! \~russian Статистика потока.
|
||||||
@@ -201,51 +207,59 @@ public:
|
|||||||
|
|
||||||
#ifndef MICRO_PIP
|
#ifndef MICRO_PIP
|
||||||
|
|
||||||
//! \~english Starts monitoring of process with PID "pID" and update interval "interval_ms" milliseconds
|
//! \~english Starts monitoring the process with PID "pID" using the given update interval.
|
||||||
//! \~russian Начинает мониторинг процесса с PID "pID" и интервалом обновления "interval_ms" миллисекунд
|
//! \~russian Запускает мониторинг процесса с PID "pID" с указанным интервалом обновления.
|
||||||
bool startOnProcess(int pID, PISystemTime interval = PISystemTime::fromSeconds(1.));
|
bool startOnProcess(int pID, PISystemTime interval = PISystemTime::fromSeconds(1.));
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
//! \~english Starts monitoring of application process with update interval "interval_ms" milliseconds
|
//! \~english Starts monitoring the current application process.
|
||||||
//! \~russian Начинает мониторинг процесса приложения с интервалом обновления "interval_ms" миллисекунд
|
//! \~russian Запускает мониторинг текущего процесса приложения.
|
||||||
bool startOnSelf(PISystemTime interval = PISystemTime::fromSeconds(1.));
|
bool startOnSelf(PISystemTime interval = PISystemTime::fromSeconds(1.));
|
||||||
|
|
||||||
//! \~english Stop monitoring
|
//! \~english Stops monitoring.
|
||||||
//! \~russian Останавливает мониторинг
|
//! \~russian Останавливает мониторинг.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns monitoring process PID
|
//! \~english Returns PID of the monitored process.
|
||||||
//! \~russian Возвращает PID наблюдаемого процесса
|
//! \~russian Возвращает PID наблюдаемого процесса.
|
||||||
int pID() const { return pID_; }
|
int pID() const { return pID_; }
|
||||||
|
|
||||||
//! \~english Returns monitoring process statistics
|
//! \~english Returns latest process statistics snapshot.
|
||||||
//! \~russian Возвращает статистику наблюдаемого процесса
|
//! \~russian Возвращает последний снимок статистики процесса.
|
||||||
ProcessStats statistic() const;
|
ProcessStats statistic() const;
|
||||||
|
|
||||||
//! \~english Returns monitoring process threads statistics
|
//! \~english Returns latest per-thread statistics snapshot.
|
||||||
//! \~russian Возвращает статистику потоков наблюдаемого процесса
|
//! \~russian Возвращает последний снимок статистики по потокам.
|
||||||
PIVector<ThreadStats> threadsStatistic() const;
|
PIVector<ThreadStats> threadsStatistic() const;
|
||||||
|
|
||||||
|
//! \~english Replaces current process statistics with external data.
|
||||||
|
//! \~russian Заменяет текущую статистику процесса внешними данными.
|
||||||
void setStatistic(const ProcessStats & s);
|
void setStatistic(const ProcessStats & s);
|
||||||
|
|
||||||
|
|
||||||
//! \~english
|
//! \~english Returns total RAM in bytes on supported platforms.
|
||||||
//! \~russian
|
//! \~russian Возвращает общий объем RAM в байтах на поддерживаемых платформах.
|
||||||
static ullong totalRAM();
|
static ullong totalRAM();
|
||||||
|
|
||||||
//! \~english
|
//! \~english Returns free RAM in bytes on supported platforms.
|
||||||
//! \~russian
|
//! \~russian Возвращает свободный объем RAM в байтах на поддерживаемых платформах.
|
||||||
static ullong freeRAM();
|
static ullong freeRAM();
|
||||||
|
|
||||||
//! \~english
|
//! \~english Returns used RAM in bytes on supported platforms.
|
||||||
//! \~russian
|
//! \~russian Возвращает используемый объем RAM в байтах на поддерживаемых платформах.
|
||||||
static ullong usedRAM();
|
static ullong usedRAM();
|
||||||
|
|
||||||
//! \~english
|
//! \~\events
|
||||||
//! \~russian
|
//! \~\{
|
||||||
|
|
||||||
|
//! \~\fn void measured()
|
||||||
|
//! \~english Raised after a new statistics snapshot is measured.
|
||||||
|
//! \~russian Вызывается после измерения нового снимка статисти
|
||||||
EVENT(measured);
|
EVENT(measured);
|
||||||
|
|
||||||
|
//! \~\}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void run() override;
|
void run() override;
|
||||||
void gatherThread(llong id);
|
void gatherThread(llong id);
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pitranslator.h
|
//! \~\file pitranslator.h
|
||||||
* \ingroup Application
|
//! \~\ingroup Application
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Translation support
|
//! \~english Translation support
|
||||||
* \~russian Поддержка перевода
|
//! \~russian Поддержка перевода
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Translation support
|
Translation support
|
||||||
@@ -29,24 +28,74 @@
|
|||||||
#include "pistring.h"
|
#include "pistring.h"
|
||||||
|
|
||||||
|
|
||||||
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
|
//! \relatesalso PITranslator
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Alias to \a PITranslator::tr().
|
||||||
|
//! \~russian Алиас к \a PITranslator::tr().
|
||||||
|
# define piTr
|
||||||
|
|
||||||
|
//! \relatesalso PITranslator
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Alias to \a PITranslator::trNoOp().
|
||||||
|
//! \~russian Алиас к \a PITranslator::trNoOp().
|
||||||
|
# define piTrNoOp
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
# define piTr PITranslator::tr
|
# define piTr PITranslator::tr
|
||||||
# define piTrNoOp PITranslator::trNoOp
|
# define piTrNoOp PITranslator::trNoOp
|
||||||
|
|
||||||
//! \ingroup Application
|
#endif
|
||||||
|
|
||||||
|
//! \~\ingroup Application
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Translation support
|
//! \~english Translation support
|
||||||
//! \~russian Поддержка перевода
|
//! \~russian Поддержка перевода
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Provides translation support with context-aware string wrappers and multiple loading methods.
|
||||||
|
//! %PITranslator stores loaded translations in a process-wide singleton.
|
||||||
|
//! If translation or context is missing, the source string is returned unchanged.
|
||||||
|
//! \~russian Предоставляет поддержку перевода с контекстно-зависимыми обертками строк и методами загрузки.
|
||||||
|
//! %PITranslator хранит загруженные переводы в синглтоне процесса.
|
||||||
|
//! Если перевод или контекст не найдены, исходная строка возвращается без изменений.
|
||||||
class PIP_EXPORT PITranslator {
|
class PIP_EXPORT PITranslator {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Returns translated string for "in" in optional "context".
|
||||||
|
//! \~russian Возвращает перевод строки "in" в необязательном "context".
|
||||||
static PIString tr(const PIString & in, const PIString & context = {});
|
static PIString tr(const PIString & in, const PIString & context = {});
|
||||||
|
|
||||||
|
//! \~english Converts UTF-8 string literal to %PIString and translates it.
|
||||||
|
//! \~russian Преобразует UTF-8 строковый литерал в %PIString и переводит его.
|
||||||
static PIString tr(const char * in, const PIString & context = {}) { return tr(PIString::fromUTF8(in), context); }
|
static PIString tr(const char * in, const PIString & context = {}) { return tr(PIString::fromUTF8(in), context); }
|
||||||
|
|
||||||
|
//! \~english Marks string for translation-aware code paths and returns it unchanged.
|
||||||
|
//! \~russian Помечает строку для кода, работающего с переводом, и возвращает ее без изменений.
|
||||||
static PIString trNoOp(const PIString & in, const PIString & context = {}) { return in; }
|
static PIString trNoOp(const PIString & in, const PIString & context = {}) { return in; }
|
||||||
|
|
||||||
|
//! \~english UTF-8 overload of \a trNoOp().
|
||||||
|
//! \~russian UTF-8 перегрузка для \a trNoOp().
|
||||||
static PIString trNoOp(const char * in, const PIString & context = {}) { return trNoOp(PIString::fromUTF8(in), context); }
|
static PIString trNoOp(const char * in, const PIString & context = {}) { return trNoOp(PIString::fromUTF8(in), context); }
|
||||||
|
|
||||||
|
//! \~english Clears all loaded translations.
|
||||||
|
//! \~russian Очищает все загруженные переводы.
|
||||||
static void clear();
|
static void clear();
|
||||||
|
|
||||||
|
//! \~english Clears current translations and loads language files matching "short_lang" from "dir".
|
||||||
|
//! \~russian Очищает текущие переводы и загружает языковые файлы, соответствующие "short_lang", из "dir".
|
||||||
static void loadLang(const PIString & short_lang, PIString dir = {});
|
static void loadLang(const PIString & short_lang, PIString dir = {});
|
||||||
|
|
||||||
|
//! \~english Loads translations from textual configuration content.
|
||||||
|
//! \~russian Загружает переводы из текстового конфигурационного содержимого.
|
||||||
static void loadConfig(const PIString & content);
|
static void loadConfig(const PIString & content);
|
||||||
|
|
||||||
|
//! \~english Loads translations from binary content in PIP translation format.
|
||||||
|
//! \~russian Загружает переводы из бинарного содержимого в формате переводов PIP.
|
||||||
static bool load(const PIByteArray & content);
|
static bool load(const PIByteArray & content);
|
||||||
|
|
||||||
|
//! \~english Loads translations from file and checks its translation header.
|
||||||
|
//! \~russian Загружает переводы из файла и проверяет его заголовок переводов.
|
||||||
static bool loadFile(const PIString & path);
|
static bool loadFile(const PIString & path);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -59,10 +108,24 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Application
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Context-aware string wrapper that automatically translates strings using PITranslator::tr().
|
||||||
|
//! Helper returned by \a operator""_tr for optional-context translation.
|
||||||
|
//! \~russian Контекстно-зависимая обертка строки, автоматически переводящая строки с помощью PITranslator::tr().
|
||||||
|
//! Вспомогательный тип, возвращаемый \a operator""_tr для перевода с необязательным контекстом.
|
||||||
class PIStringContextTr {
|
class PIStringContextTr {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Stores source string for later translation.
|
||||||
|
//! \~russian Сохраняет исходную строку для последующего перевода.
|
||||||
PIStringContextTr(PIString && s): _s(s) {}
|
PIStringContextTr(PIString && s): _s(s) {}
|
||||||
|
|
||||||
|
//! \~english Translates stored string without explicit context.
|
||||||
|
//! \~russian Переводит сохраненную строку без явного контекста.
|
||||||
operator PIString() const { return PITranslator::tr(_s); }
|
operator PIString() const { return PITranslator::tr(_s); }
|
||||||
|
|
||||||
|
//! \~english Translates stored string in context "ctx".
|
||||||
|
//! \~russian Переводит сохраненную строку в контексте "ctx".
|
||||||
PIString operator()(const PIString & ctx = {}) const { return PITranslator::tr(_s, ctx); }
|
PIString operator()(const PIString & ctx = {}) const { return PITranslator::tr(_s, ctx); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -70,10 +133,24 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Application
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Context-aware string wrapper that preserves original strings without translation (no-op).
|
||||||
|
//! Helper returned by \a operator""_trNoOp that keeps source text unchanged.
|
||||||
|
//! \~russian Контекстно-зависимая обертка строки, сохраняющая оригинальные строки без перевода (заглушка).
|
||||||
|
//! Вспомогательный тип, возвращаемый \a operator""_trNoOp, который сохраняет исходный текст без изменений.
|
||||||
class PIStringContextTrNoOp {
|
class PIStringContextTrNoOp {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Stores source string without translating it.
|
||||||
|
//! \~russian Сохраняет исходную строку без перевода.
|
||||||
PIStringContextTrNoOp(PIString && s): _s(s) {}
|
PIStringContextTrNoOp(PIString && s): _s(s) {}
|
||||||
|
|
||||||
|
//! \~english Returns stored string unchanged.
|
||||||
|
//! \~russian Возвращает сохраненную строку без изменений.
|
||||||
operator PIString() const { return _s; }
|
operator PIString() const { return _s; }
|
||||||
|
|
||||||
|
//! \~english Returns stored string unchanged and ignores "ctx".
|
||||||
|
//! \~russian Возвращает сохраненную строку без изменений и игнорирует "ctx".
|
||||||
PIString operator()(const PIString & ctx = {}) const { return _s; }
|
PIString operator()(const PIString & ctx = {}) const { return _s; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -82,15 +159,17 @@ private:
|
|||||||
|
|
||||||
|
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Translate string with \a PITranslator::tr()
|
//! \~english User-defined literal that defers translation through \a PITranslator::tr().
|
||||||
//! \~russian Перевести строку с помощью \a PITranslator::tr()
|
//! \~russian Пользовательский литерал, откладывающий перевод через \a PITranslator::tr().
|
||||||
|
//! \~\code "hello"_tr \endcode
|
||||||
inline PIStringContextTr operator""_tr(const char * v, size_t sz) {
|
inline PIStringContextTr operator""_tr(const char * v, size_t sz) {
|
||||||
return PIStringContextTr(PIString::fromUTF8(v, sz));
|
return PIStringContextTr(PIString::fromUTF8(v, sz));
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Translate string with \a PITranslator::tr()
|
//! \~english User-defined literal that keeps source text unchanged via \a PITranslator::trNoOp().
|
||||||
//! \~russian Перевести строку с помощью \a PITranslator::tr()
|
//! \~russian Пользовательский литерал, сохраняющий исходный текст без изменений через \a PITranslator::trNoOp().
|
||||||
|
//! \~\code "hello"_trNoOp \endcode
|
||||||
inline PIStringContextTrNoOp operator""_trNoOp(const char * v, size_t sz) {
|
inline PIStringContextTrNoOp operator""_trNoOp(const char * v, size_t sz) {
|
||||||
return PIStringContextTrNoOp(PIString::fromUTF8(v, sz));
|
return PIStringContextTrNoOp(PIString::fromUTF8(v, sz));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piclientserver_client.h
|
//! \~\file piclientserver_client.h
|
||||||
* \ingroup ClientServer
|
//! \~\ingroup ClientServer
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english
|
//! \~english Client-side and server-side client connection classes
|
||||||
* \~russian
|
//! \~russian Классы клиентского подключения и серверного представления клиента
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Ivan Pelipenko peri4ko@yandex.ru
|
Ivan Pelipenko peri4ko@yandex.ru
|
||||||
@@ -33,18 +32,27 @@ namespace PIClientServer {
|
|||||||
|
|
||||||
// ServerClient
|
// ServerClient
|
||||||
|
|
||||||
//! ~english Server-side client implementation
|
//! \~\ingroup ClientServer
|
||||||
//! ~russian Серверная реализация клиента
|
//! \~\brief
|
||||||
|
//! \~english Server-side representation of one accepted client connection.
|
||||||
|
//! \~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 {
|
class PIP_CLIENT_SERVER_EXPORT ServerClient: public ClientBase {
|
||||||
friend class Server;
|
friend class Server;
|
||||||
NO_COPY_CLASS(ServerClient);
|
NO_COPY_CLASS(ServerClient);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an unbound server-side client object.
|
||||||
|
//! \~russian Создает непривязанный объект серверного клиента.
|
||||||
ServerClient() {}
|
ServerClient() {}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//! ~english Called before client destruction
|
//! \~english Called right before the server deletes this client object.
|
||||||
//! ~russian Вызывается перед уничтожением клиента
|
//! \~russian Вызывается непосредственно перед удалением этого объекта сервером.
|
||||||
virtual void aboutDelete() {}
|
virtual void aboutDelete() {}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -54,17 +62,28 @@ private:
|
|||||||
|
|
||||||
// Client
|
// Client
|
||||||
|
|
||||||
//! ~english Client implementation for connecting to servers
|
//! \~\ingroup ClientServer
|
||||||
//! ~russian Клиентская реализация для подключения к серверам
|
//! \~\brief
|
||||||
|
//! \~english Active client connection that initiates a connection to a server.
|
||||||
|
//! \~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 {
|
class PIP_CLIENT_SERVER_EXPORT Client: public ClientBase {
|
||||||
NO_COPY_CLASS(Client);
|
NO_COPY_CLASS(Client);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a client ready to connect to a remote server.
|
||||||
|
//! \~russian Создает клиент, готовый к подключению к удаленному серверу.
|
||||||
Client();
|
Client();
|
||||||
|
//! \~english Destroys the client and closes its connection if needed.
|
||||||
|
//! \~russian Уничтожает клиента и при необходимости закрывает его соединение.
|
||||||
~Client();
|
~Client();
|
||||||
|
|
||||||
//! ~english Connects to specified server address
|
//! \~english Connects to the server at address "addr".
|
||||||
//! ~russian Подключается к указанному адресу сервера
|
//! \~russian Подключается к серверу по адресу "addr".
|
||||||
void connect(PINetworkAddress addr);
|
void connect(PINetworkAddress addr);
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
/*! \file piclientserver_client_base.h
|
//! \~\file piclientserver_client_base.h
|
||||||
* \ingroup ClientServer
|
//! \~\ingroup ClientServer
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english
|
//! \~english Base class for client-server communication
|
||||||
* \~russian
|
//! \~russian Базовый класс для клиент-серверного взаимодействия
|
||||||
*/
|
//! \details
|
||||||
|
//! \~english Provides base functionality for client-server communication with diagnostics support.
|
||||||
|
//! \~russian Обеспечивает базовую функциональность для клиент-серверного взаимодействия с поддержкой диагностики.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Ivan Pelipenko peri4ko@yandex.ru
|
Ivan Pelipenko peri4ko@yandex.ru
|
||||||
@@ -35,77 +37,93 @@ namespace PIClientServer {
|
|||||||
|
|
||||||
class Server;
|
class Server;
|
||||||
|
|
||||||
class ClientInterface {};
|
//! \~\ingroup ClientServer
|
||||||
|
//! \~\brief
|
||||||
//! ~english Base class for client-server communication with diagnostics support
|
//! \~english Base class for client and server-side client communication. Provides TCP connection management, diagnostics, and packet
|
||||||
//! ~russian Базовый класс для клиент-серверного взаимодействия с поддержкой диагностики
|
//! streaming capabilities.
|
||||||
|
//! \~russian Базовый класс для клиентской и серверной коммуникации. Обеспечивает управление TCP-соединением, диагностику и потоковую
|
||||||
|
//! передачу пакетов.
|
||||||
// template<bool EnableDiagnostics = false>
|
// template<bool EnableDiagnostics = false>
|
||||||
class PIP_CLIENT_SERVER_EXPORT ClientBase {
|
class PIP_CLIENT_SERVER_EXPORT ClientBase {
|
||||||
friend class Server;
|
friend class Server;
|
||||||
NO_COPY_CLASS(ClientBase);
|
NO_COPY_CLASS(ClientBase);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a disconnected client connection object.
|
||||||
|
//! \~russian Создает объект клиентского соединения в отключенном состоянии.
|
||||||
ClientBase();
|
ClientBase();
|
||||||
|
|
||||||
|
//! \~english Destroys the client connection and releases owned resources.
|
||||||
|
//! \~russian Уничтожает клиентское соединение и освобождает связанные ресурсы.
|
||||||
virtual ~ClientBase();
|
virtual ~ClientBase();
|
||||||
|
|
||||||
//! ~english Gets underlying TCP connection
|
|
||||||
//! ~russian Возвращает TCP-соединение
|
//! \~english Returns the underlying TCP transport object.
|
||||||
|
//! \~russian Возвращает базовый объект TCP-транспорта.
|
||||||
const PIEthernet * getTCP() const { return tcp; }
|
const PIEthernet * getTCP() const { return tcp; }
|
||||||
|
|
||||||
//! ~english Closes the connection
|
//! \~english Closes the connection immediately.
|
||||||
//! ~russian Закрывает соединение
|
//! \~russian Немедленно закрывает соединение.
|
||||||
void close();
|
void close();
|
||||||
|
|
||||||
//! ~english Gracefully stops and waits for completion
|
//! \~english Stops the connection workflow and waits until shutdown completes.
|
||||||
//! ~russian Плавно останавливает и ожидает завершения
|
//! \~russian Останавливает работу соединения и ждет полного завершения.
|
||||||
void stopAndWait();
|
void stopAndWait();
|
||||||
|
|
||||||
|
|
||||||
//! ~english Writes byte array to the connection
|
//! \~english Sends raw payload bytes through the stream packer.
|
||||||
//! ~russian Записывает массив байтов в соединение
|
//! \~russian Отправляет сырые байты полезной нагрузки через упаковщик потока.
|
||||||
int write(const void * d, const size_t s);
|
int write(const void * d, const size_t s);
|
||||||
|
|
||||||
//! ~english Writes byte array to the connection
|
//! \~english Sends payload stored in "ba".
|
||||||
//! ~russian Записывает массив байтов в соединение
|
//! \~russian Отправляет полезную нагрузку из "ba".
|
||||||
int write(const PIByteArray & ba) { return write(ba.data(), ba.size()); }
|
int write(const PIByteArray & ba) { return write(ba.data(), ba.size()); }
|
||||||
|
|
||||||
|
|
||||||
//! ~english Enables diagnostics collection
|
//! \~english Enables connection diagnostics collection.
|
||||||
//! ~russian Включает сбор диагностики
|
//! \~russian Включает сбор диагностики соединения.
|
||||||
void enableDiagnostics();
|
void enableDiagnostics();
|
||||||
|
|
||||||
//! ~english Gets current diagnostics state
|
//! \~english Returns a snapshot of current diagnostics counters.
|
||||||
//! ~russian Возвращает текущее состояние диагностики
|
//! \~russian Возвращает снимок текущих диагностических счетчиков.
|
||||||
PIDiagnostics::State diagnostics() const;
|
PIDiagnostics::State diagnostics() const;
|
||||||
|
|
||||||
|
|
||||||
//! ~english Gets current received packet bytes already received (all bytes count passed in \a receivePacketStart())
|
//! \~english Returns how many payload bytes of the current packet are already received (all bytes count passed in \a receivePacketStart()).
|
||||||
//! ~russian Возвращает сколько байт принимаемого пакета получено (общее количество передается в \a receivePacketStart())
|
//! \~russian Возвращает, сколько байтов полезной нагрузки текущего пакета уже получено (общее количество передается в \a receivePacketStart()).
|
||||||
int receivePacketProgress() const;
|
int receivePacketProgress() const;
|
||||||
|
|
||||||
|
//! \~english Returns the current packet framing configuration.
|
||||||
|
//! \~russian Возвращает текущую конфигурацию пакетирования.
|
||||||
const PIStreamPackerConfig & configuration() const { return stream.configuration(); }
|
const PIStreamPackerConfig & configuration() const { return stream.configuration(); }
|
||||||
|
|
||||||
|
//! \~english Returns the current packet framing configuration for modification.
|
||||||
|
//! \~russian Возвращает текущую конфигурацию пакетирования для изменения.
|
||||||
PIStreamPackerConfig & configuration() { return stream.configuration(); }
|
PIStreamPackerConfig & configuration() { return stream.configuration(); }
|
||||||
|
|
||||||
|
//! \~english Replaces the packet framing configuration.
|
||||||
|
//! \~russian Заменяет конфигурацию пакетирования.
|
||||||
void setConfiguration(const PIStreamPackerConfig & config) { stream.setConfiguration(config); }
|
void setConfiguration(const PIStreamPackerConfig & config) { stream.setConfiguration(config); }
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//! ~english Called when data is received
|
//! \~english Called when a full payload packet is received.
|
||||||
//! ~russian Вызывается при получении данных
|
//! \~russian Вызывается при получении полного пакета полезной нагрузки.
|
||||||
virtual void readed(PIByteArray data) {}
|
virtual void readed(PIByteArray data) {}
|
||||||
|
|
||||||
//! ~english Called when connection is established
|
//! \~english Called after the TCP connection becomes active.
|
||||||
//! ~russian Вызывается при установке соединения
|
//! \~russian Вызывается после перехода TCP-соединения в активное состояние.
|
||||||
virtual void connected() {}
|
virtual void connected() {}
|
||||||
|
|
||||||
//! ~english Called when connection is closed
|
//! \~english Called after the connection is closed.
|
||||||
//! ~russian Вызывается при закрытии соединения
|
//! \~russian Вызывается после закрытия соединения.
|
||||||
virtual void disconnected() {}
|
virtual void disconnected() {}
|
||||||
|
|
||||||
//! ~english Called when packet receiving starts
|
//! \~english Called when reception of a new packet starts.
|
||||||
//! ~russian Вызывается при начале получения пакета
|
//! \~russian Вызывается при начале приема нового пакета.
|
||||||
virtual void receivePacketStart(int size) {}
|
virtual void receivePacketStart(int size) {}
|
||||||
|
|
||||||
//! ~english Called when packet receiving ends
|
//! \~english Called when reception of the current packet finishes.
|
||||||
//! ~russian Вызывается при завершении получения пакета
|
//! \~russian Вызывается при завершении приема текущего пакета.
|
||||||
virtual void receivePacketEnd() {}
|
virtual void receivePacketEnd() {}
|
||||||
|
|
||||||
void init();
|
void init();
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piclientserver_server.h
|
//! \~\file piclientserver_server.h
|
||||||
* \ingroup ClientServer
|
//! \~\ingroup ClientServer
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english
|
//! \~english TCP Server
|
||||||
* \~russian
|
//! \~russian TCP Сервер
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Ivan Pelipenko peri4ko@yandex.ru
|
Ivan Pelipenko peri4ko@yandex.ru
|
||||||
@@ -38,54 +37,72 @@ namespace PIClientServer {
|
|||||||
|
|
||||||
class ServerClient;
|
class ServerClient;
|
||||||
|
|
||||||
//! ~english TCP server for client-server communication
|
//! \~\ingroup ClientServer
|
||||||
//! ~russian TCP сервер для клиент-серверного взаимодействия
|
//! \~\brief
|
||||||
|
//! \~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 {
|
class PIP_CLIENT_SERVER_EXPORT Server: public PIStreamPackerConfig {
|
||||||
friend class ServerClient;
|
friend class ServerClient;
|
||||||
NO_COPY_CLASS(Server);
|
NO_COPY_CLASS(Server);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a stopped server with default limits.
|
||||||
|
//! \~russian Создает остановленный сервер с ограничениями по умолчанию.
|
||||||
Server();
|
Server();
|
||||||
|
|
||||||
|
//! \~english Stops the server and releases transport resources.
|
||||||
|
//! \~russian Останавливает сервер и освобождает транспортные ресурсы.
|
||||||
virtual ~Server();
|
virtual ~Server();
|
||||||
|
|
||||||
//! ~english Starts listening on specified address
|
//! \~english Starts listening for clients on address "addr".
|
||||||
//! ~russian Начинает прослушивание на указанном адресе
|
//! \~russian Начинает принимать клиентов по адресу "addr".
|
||||||
void listen(PINetworkAddress addr);
|
void listen(PINetworkAddress addr);
|
||||||
|
|
||||||
//! ~english Starts listening on all interfaces
|
//! \~english Starts listening on all interfaces at port "port".
|
||||||
//! ~russian Начинает прослушивание на всех интерфейсах
|
//! \~russian Начинает прослушивание на всех интерфейсах на порту "port".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Equivalent to listen({0, port}), binds to all available network interfaces.
|
||||||
|
//! \~russian Эквивалентно listen({0, port}), привязывается ко всем доступным сетевым интерфейсам.
|
||||||
void listenAll(ushort port) { listen({0, port}); }
|
void listenAll(ushort port) { listen({0, port}); }
|
||||||
|
|
||||||
|
|
||||||
//! ~english Stops the server
|
//! \~english Stops accepting clients and shuts the server down.
|
||||||
//! ~russian Останавливает сервер
|
//! \~russian Прекращает прием клиентов и завершает работу сервера.
|
||||||
void stopServer();
|
void stopServer();
|
||||||
|
|
||||||
//! ~english Closes all client connections
|
//! \~english Closes all currently connected clients.
|
||||||
//! ~russian Закрывает все клиентские соединения
|
//! \~russian Закрывает все текущие клиентские соединения.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Immediately closes all active client connections without stopping the server.
|
||||||
|
//! \~russian Немедленно закрывает все активные клиентские соединения без остановки сервера.
|
||||||
void closeAll();
|
void closeAll();
|
||||||
|
|
||||||
|
|
||||||
//! ~english Gets maximum allowed clients
|
//! \~english Returns the configured maximum number of simultaneous clients.
|
||||||
//! ~russian Возвращает максимальное число клиентов
|
//! \~russian Возвращает настроенный максимум одновременных клиентов.
|
||||||
int getMaxClients() const { return max_clients; }
|
int getMaxClients() const { return max_clients; }
|
||||||
|
|
||||||
//! ~english Sets maximum allowed clients
|
//! \~english Sets the maximum number of simultaneous clients.
|
||||||
//! ~russian Устанавливает максимальное число клиентов
|
//! \~russian Устанавливает максимальное число одновременных клиентов.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the maximum number of concurrent client connections. Default is 1000.
|
||||||
|
//! \~russian Устанавливает максимальное количество одновременных клиентских подключений. По умолчанию 1000.
|
||||||
void setMaxClients(int new_max_clients);
|
void setMaxClients(int new_max_clients);
|
||||||
|
|
||||||
//! ~english Gets current clients count
|
//! \~english Returns the number of currently connected clients.
|
||||||
//! ~russian Возвращает текущее количество клиентов
|
//! \~russian Возвращает текущее количество подключенных клиентов.
|
||||||
int clientsCount() const;
|
int clientsCount() const;
|
||||||
|
|
||||||
|
|
||||||
//! ~english Executes function for each connected client
|
//! \~english Calls "func" for each currently connected client.
|
||||||
//! ~russian Выполняет функцию для каждого подключённого клиента
|
//! \~russian Вызывает "func" для каждого текущего подключенного клиента.
|
||||||
void forEachClient(std::function<void(ServerClient *)> func);
|
void forEachClient(std::function<void(ServerClient *)> func);
|
||||||
|
|
||||||
|
|
||||||
//! ~english Sets factory for creating new client instances
|
//! \~english Sets the factory used to create accepted client objects.
|
||||||
//! ~russian Устанавливает фабрику для создания клиентских экземпляров
|
//! \~russian Устанавливает фабрику, создающую объекты принятых клиентов.
|
||||||
void setClientFactory(std::function<ServerClient *()> f) { client_factory = f; }
|
void setClientFactory(std::function<ServerClient *()> f) { client_factory = f; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
//! \~\file piclientservermodule.h
|
||||||
|
//! \~\ingroup ClientServer
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Umbrella header and module group for TCP client-server helpers
|
||||||
|
//! \~russian Общий заголовок и группа модуля для TCP-клиент-серверных компонентов
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -34,10 +39,10 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides server with clients dispatching for server-side and client for client-side.
|
//! These headers provide a TCP server with server-side client objects and an active client for remote connections.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы предоставляют сервер с диспетчеризацией клиентов для серверной стороны и клиента для клиентской стороны.
|
//! Эти заголовки предоставляют TCP-сервер с серверными объектами клиентов и активного клиента для удаленных подключений.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picloudbase.h
|
//! \~\file picloudbase.h
|
||||||
* \ingroup Cloud
|
//! \~\ingroup Cloud
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Base class for PICloudClient and PICloudServer
|
//! \~english Base class for PICloudClient and PICloudServer.
|
||||||
* \~russian Базовый класс для PICloudClient и PICloudServer
|
//! \~russian Базовый класс для PICloudClient и PICloudServer.
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PICloud Base - Base class for PICloudClient and PICloud Server
|
PICloud Base - Base class for PICloudClient and PICloud Server
|
||||||
@@ -30,11 +29,18 @@
|
|||||||
#include "piethernet.h"
|
#include "piethernet.h"
|
||||||
#include "pistreampacker.h"
|
#include "pistreampacker.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
|
//! \brief
|
||||||
|
//! \~english Base class for cloud client and server.
|
||||||
|
//! \~russian Базовый класс для облачного клиента и сервера.
|
||||||
class PIP_CLOUD_EXPORT PICloudBase {
|
class PIP_CLOUD_EXPORT PICloudBase {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs the shared PICloud transport state.
|
||||||
|
//! \~russian Создает общее транспортное состояние PICloud.
|
||||||
PICloudBase();
|
PICloudBase();
|
||||||
|
|
||||||
|
//! \~english Returns the logical server name configured for the transport.
|
||||||
|
//! \~russian Возвращает логическое имя сервера, настроенное для транспорта.
|
||||||
PIString serverName() const;
|
PIString serverName() const;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picloudclient.h
|
//! \~\file picloudclient.h
|
||||||
* \ingroup Cloud
|
//! \~\ingroup Cloud
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english PICloud Client
|
//! \~english Client-side PICloud device for one named server
|
||||||
* \~russian Клиент PICloud
|
//! \~russian Клиентское устройство PICloud для одного именованного сервера
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PICloud Client
|
PICloud Client
|
||||||
@@ -29,27 +28,61 @@
|
|||||||
#include "picloudbase.h"
|
#include "picloudbase.h"
|
||||||
#include "piconditionvar.h"
|
#include "piconditionvar.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
//! \brief PICloudClient
|
//! \~\brief
|
||||||
|
//! \~english %PIIODevice implementation for a logical PICloud client.
|
||||||
|
//! \~russian Реализация %PIIODevice для логического клиента PICloud.
|
||||||
class PIP_CLOUD_EXPORT PICloudClient
|
class PIP_CLOUD_EXPORT PICloudClient
|
||||||
: public PIIODevice
|
: public PIIODevice
|
||||||
, public PICloudBase {
|
, public PICloudBase {
|
||||||
PIIODEVICE(PICloudClient, "");
|
PIIODEVICE(PICloudClient, "");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a client for transport endpoint "path" and mode "mode".
|
||||||
|
//! \~russian Создает клиент для транспортной точки "path" и режима "mode".
|
||||||
explicit PICloudClient(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
explicit PICloudClient(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the client and closes the underlying transport.
|
||||||
|
//! \~russian Уничтожает клиент и закрывает нижележащий транспорт.
|
||||||
virtual ~PICloudClient();
|
virtual ~PICloudClient();
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Sets the logical server name used during the PICloud handshake.
|
||||||
|
//! \~russian Устанавливает логическое имя сервера, используемое при рукопожатии PICloud.
|
||||||
void setServerName(const PIString & server_name);
|
void setServerName(const PIString & server_name);
|
||||||
|
|
||||||
|
//! \~english Enables or disables automatic reconnect of the underlying TCP link.
|
||||||
|
//! \~russian Включает или выключает автоматическое переподключение нижележащего TCP-соединения.
|
||||||
void setKeepConnection(bool on);
|
void setKeepConnection(bool on);
|
||||||
|
|
||||||
|
//! \~english Returns whether the logical PICloud session is established.
|
||||||
|
//! \~russian Возвращает, установлена ли логическая сессия PICloud.
|
||||||
bool isConnected() const { return is_connected; }
|
bool isConnected() const { return is_connected; }
|
||||||
|
|
||||||
|
//! \~english Returns the number of payload bytes buffered for \a read().
|
||||||
|
//! \~russian Возвращает количество байтов полезной нагрузки, буферизованных для \a read().
|
||||||
ssize_t bytesAvailable() const override { return buff.size(); }
|
ssize_t bytesAvailable() const override { return buff.size(); }
|
||||||
|
|
||||||
|
//! \~english Interrupts pending connection and read waits.
|
||||||
|
//! \~russian Прерывает ожидающие операции подключения и чтения.
|
||||||
void interrupt() override;
|
void interrupt() override;
|
||||||
|
|
||||||
|
|
||||||
|
//! \events
|
||||||
|
//! \{
|
||||||
|
|
||||||
|
//! \fn void connected()
|
||||||
|
//! \~english Raised after the logical PICloud session becomes ready.
|
||||||
|
//! \~russian Вызывается после того, как логическая сессия PICloud готова к работе.
|
||||||
EVENT(connected);
|
EVENT(connected);
|
||||||
|
|
||||||
|
//! \fn void disconnected()
|
||||||
|
//! \~english Raised when the logical PICloud session is closed.
|
||||||
|
//! \~russian Вызывается при закрытии логической сессии PICloud.
|
||||||
EVENT(disconnected);
|
EVENT(disconnected);
|
||||||
|
|
||||||
|
//! \}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
bool openDevice() override;
|
bool openDevice() override;
|
||||||
bool closeDevice() override;
|
bool closeDevice() override;
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file picloudmodule.h
|
||||||
|
* \ingroup Cloud
|
||||||
|
* \~\brief
|
||||||
|
* \~english Umbrella header for the PICloud module
|
||||||
|
* \~russian Зонтичный заголовок модуля PICloud
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public client, server, and low-level transport helpers of the module.
|
||||||
|
* \~russian Подключает публичные клиентские, серверные и низкоуровневые транспортные помощники модуля.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -18,8 +28,8 @@
|
|||||||
*/
|
*/
|
||||||
//! \defgroup Cloud Cloud
|
//! \defgroup Cloud Cloud
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Cloud transport over ethernet
|
//! \~english Named cloud endpoints over an ethernet transport
|
||||||
//! \~russian Облачный транспорт через ethernet
|
//! \~russian Именованные облачные конечные точки поверх Ethernet-транспорта
|
||||||
//!
|
//!
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english \section cmake_module_Cloud Building with CMake
|
//! \~english \section cmake_module_Cloud Building with CMake
|
||||||
@@ -34,10 +44,10 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides server-side and client-side of PICloud transport.
|
//! Includes logical client and server devices together with low-level PICloud framing helpers.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают серверную и клиентскую сторону транспорта PICloud.
|
//! Подключает логические клиентские и серверные устройства вместе с низкоуровневыми помощниками кадрирования PICloud.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picloudserver.h
|
//! \~\file picloudserver.h
|
||||||
* \ingroup Cloud
|
//! \~\ingroup Cloud
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english PICloud Server
|
//! \~english Server-side PICloud device for one named endpoint
|
||||||
* \~russian Сервер PICloud
|
//! \~russian Серверное устройство PICloud для одной именованной конечной точки
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PICloud Server
|
PICloud Server
|
||||||
@@ -29,23 +28,43 @@
|
|||||||
#include "picloudbase.h"
|
#include "picloudbase.h"
|
||||||
#include "piconditionvar.h"
|
#include "piconditionvar.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english %PIIODevice implementation for a logical PICloud server.
|
||||||
|
//! \~russian Реализация %PIIODevice для логического сервера PICloud.
|
||||||
class PIP_CLOUD_EXPORT PICloudServer
|
class PIP_CLOUD_EXPORT PICloudServer
|
||||||
: public PIIODevice
|
: public PIIODevice
|
||||||
, public PICloudBase {
|
, public PICloudBase {
|
||||||
PIIODEVICE(PICloudServer, "");
|
PIIODEVICE(PICloudServer, "");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! PICloudServer
|
//! \~english Constructs a logical server for transport endpoint "path" and mode "mode".
|
||||||
|
//! \~russian Создает логический сервер для транспортной точки "path" и режима "mode".
|
||||||
explicit PICloudServer(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
explicit PICloudServer(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the server and closes all logical clients.
|
||||||
|
//! \~russian Уничтожает сервер и закрывает всех логических клиентов.
|
||||||
virtual ~PICloudServer();
|
virtual ~PICloudServer();
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Per-client %PIIODevice exposed by %PICloudServer.
|
||||||
|
//! \~russian Клиентское %PIIODevice, предоставляемое %PICloudServer.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Instances are created by \a newConnection() and represent one logical cloud client.
|
||||||
|
//! \~russian Экземпляры создаются через \a newConnection() и представляют одного логического облачного клиента.
|
||||||
class Client: public PIIODevice {
|
class Client: public PIIODevice {
|
||||||
PIIODEVICE(PICloudServer::Client, "");
|
PIIODEVICE(PICloudServer::Client, "");
|
||||||
friend class PICloudServer;
|
friend class PICloudServer;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a wrapper for logical client "id" owned by server "srv".
|
||||||
|
//! \~russian Создает обертку для логического клиента "id", принадлежащего серверу "srv".
|
||||||
Client(PICloudServer * srv = nullptr, uint id = 0);
|
Client(PICloudServer * srv = nullptr, uint id = 0);
|
||||||
|
|
||||||
|
//! \~english Destroys the client wrapper.
|
||||||
|
//! \~russian Уничтожает клиентскую обертку.
|
||||||
virtual ~Client();
|
virtual ~Client();
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -67,12 +86,25 @@ public:
|
|||||||
std::atomic_bool is_connected;
|
std::atomic_bool is_connected;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Sets the logical server name announced by this server.
|
||||||
|
//! \~russian Устанавливает логическое имя сервера, объявляемое этим сервером.
|
||||||
void setServerName(const PIString & server_name);
|
void setServerName(const PIString & server_name);
|
||||||
|
|
||||||
|
//! \~english Returns a snapshot of the currently connected logical clients.
|
||||||
|
//! \~russian Возвращает снимок текущих подключенных логических клиентов.
|
||||||
PIVector<PICloudServer::Client *> clients() const;
|
PIVector<PICloudServer::Client *> clients() const;
|
||||||
|
|
||||||
|
|
||||||
|
//! \events
|
||||||
|
//! \{
|
||||||
|
|
||||||
|
//! \fn void newConnection(PICloudServer::Client * client)
|
||||||
|
//! \~english Raised when a new logical client appears for this server name.
|
||||||
|
//! \~russian Вызывается, когда для этого имени сервера появляется новый логический клиент.
|
||||||
EVENT1(newConnection, PICloudServer::Client *, client);
|
EVENT1(newConnection, PICloudServer::Client *, client);
|
||||||
|
|
||||||
|
//! \}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
bool openDevice() override;
|
bool openDevice() override;
|
||||||
bool closeDevice() override;
|
bool closeDevice() override;
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
/*! \file picloudtcp.h
|
//! \~\file picloudtcp.h
|
||||||
* \ingroup Cloud
|
//! \~\ingroup Cloud
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english PICloud TCP transport
|
//! \~english Low-level TCP framing helpers for PICloud
|
||||||
* \~russian TCP слой PICloud
|
//! \~russian Низкоуровневые помощники TCP-кадрирования для PICloud
|
||||||
*/
|
//!
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PICloud TCP transport
|
PICloud TCP transport
|
||||||
@@ -31,50 +31,113 @@
|
|||||||
#include "pistring.h"
|
#include "pistring.h"
|
||||||
|
|
||||||
|
|
||||||
class PIEthernet;
|
|
||||||
class PIStreamPacker;
|
class PIStreamPacker;
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
|
//! \~english Namespace for low-level PICloud transport helpers.
|
||||||
|
//! \~russian Пространство имен для низкоуровневых транспортных помощников PICloud.
|
||||||
namespace PICloud {
|
namespace PICloud {
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Cloud
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Builds and parses PICloud frames on top of %PIStreamPacker.
|
||||||
|
//! \~russian Формирует и разбирает кадры PICloud поверх %PIStreamPacker.
|
||||||
class PIP_CLOUD_EXPORT TCP {
|
class PIP_CLOUD_EXPORT TCP {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Supported PICloud frame versions.
|
||||||
|
//! \~russian Поддерживаемые версии кадров PICloud.
|
||||||
enum Version {
|
enum Version {
|
||||||
Version_1 = 1,
|
Version_1 = 1 /** \~english First protocol version \~russian Первая версия протокола */,
|
||||||
Version_2 = 2,
|
Version_2 = 2 /** \~english Current protocol version \~russian Текущая версия протокола */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Logical destination role of a PICloud frame.
|
||||||
|
//! \~russian Логическая роль получателя кадра PICloud.
|
||||||
enum Role {
|
enum Role {
|
||||||
InvalidRole = 0,
|
InvalidRole = 0 /** \~english Invalid or unknown role \~russian Некорректная или неизвестная роль */,
|
||||||
Server = 1,
|
Server = 1 /** \~english Frame for a logical server \~russian Кадр для логического сервера */,
|
||||||
Client = 2,
|
Client = 2 /** \~english Frame for a logical client \~russian Кадр для логического клиента */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Kind of PICloud frame payload.
|
||||||
|
//! \~russian Вид полезной нагрузки кадра PICloud.
|
||||||
enum Type {
|
enum Type {
|
||||||
InvalidType = 0,
|
InvalidType = 0 /** \~english Invalid or unknown frame \~russian Некорректный или неизвестный кадр */,
|
||||||
Connect = 1,
|
Connect = 1 /** \~english Connect or registration frame \~russian Кадр подключения или регистрации */,
|
||||||
Disconnect = 2,
|
Disconnect = 2 /** \~english Disconnect notification frame \~russian Кадр уведомления об отключении */,
|
||||||
Data = 3,
|
Data = 3 /** \~english Payload data frame \~russian Кадр с полезными данными */,
|
||||||
Ping = 4,
|
Ping = 4 /** \~english Keepalive frame \~russian Кадр поддержания соединения */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Constructs a PICloud frame helper bound to packer "s".
|
||||||
|
//! \~russian Создает помощник кадров PICloud, связанный с упаковщиком "s".
|
||||||
TCP(PIStreamPacker * s);
|
TCP(PIStreamPacker * s);
|
||||||
|
|
||||||
|
//! \~english Sets the logical role written into outgoing frames.
|
||||||
|
//! \~russian Устанавливает логическую роль, записываемую в исходящие кадры.
|
||||||
void setRole(Role r);
|
void setRole(Role r);
|
||||||
|
|
||||||
|
//! \~english Returns the logical role of this helper.
|
||||||
|
//! \~russian Возвращает логическую роль этого помощника.
|
||||||
Role role() const { return (Role)header.role; }
|
Role role() const { return (Role)header.role; }
|
||||||
|
|
||||||
|
//! \~english Sets the logical server name used by connect and keepalive frames.
|
||||||
|
//! \~russian Устанавливает логическое имя сервера, используемое кадрами подключения и поддержания соединения.
|
||||||
void setServerName(const PIString & server_name_);
|
void setServerName(const PIString & server_name_);
|
||||||
|
|
||||||
|
//! \~english Returns the configured logical server name.
|
||||||
|
//! \~russian Возвращает настроенное логическое имя сервера.
|
||||||
PIString serverName() const;
|
PIString serverName() const;
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Sends the initial connect frame for the current server name.
|
||||||
|
//! \~russian Отправляет начальный кадр подключения для текущего имени сервера.
|
||||||
void sendStart();
|
void sendStart();
|
||||||
|
|
||||||
|
//! \~english Sends a connect frame for logical client "client_id".
|
||||||
|
//! \~russian Отправляет кадр подключения для логического клиента "client_id".
|
||||||
void sendConnected(uint client_id);
|
void sendConnected(uint client_id);
|
||||||
|
|
||||||
|
//! \~english Sends a disconnect frame for logical client "client_id".
|
||||||
|
//! \~russian Отправляет кадр отключения для логического клиента "client_id".
|
||||||
void sendDisconnected(uint client_id);
|
void sendDisconnected(uint client_id);
|
||||||
|
|
||||||
|
//! \~english Sends a payload frame for the current logical role.
|
||||||
|
//! \~russian Отправляет кадр с полезными данными для текущей логической роли.
|
||||||
int sendData(const PIByteArray & data);
|
int sendData(const PIByteArray & data);
|
||||||
|
|
||||||
|
//! \~english Sends a payload frame tagged with logical client "client_id".
|
||||||
|
//! \~russian Отправляет кадр с полезными данными, помеченный логическим клиентом "client_id".
|
||||||
int sendData(const PIByteArray & data, uint client_id);
|
int sendData(const PIByteArray & data, uint client_id);
|
||||||
|
|
||||||
|
//! \~english Sends a keepalive frame.
|
||||||
|
//! \~russian Отправляет кадр поддержания соединения.
|
||||||
void sendPing();
|
void sendPing();
|
||||||
|
|
||||||
|
//! \~english Parses frame header and returns its type and destination role.
|
||||||
|
//! \~russian Разбирает заголовок кадра и возвращает его тип и роль получателя.
|
||||||
PIPair<PICloud::TCP::Type, PICloud::TCP::Role> parseHeader(PIByteArray & ba);
|
PIPair<PICloud::TCP::Type, PICloud::TCP::Role> parseHeader(PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Returns whether current role uses direct payload parsing.
|
||||||
|
//! \~russian Возвращает, использует ли текущая роль прямой разбор полезной нагрузки.
|
||||||
bool canParseData(PIByteArray & ba);
|
bool canParseData(PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Extracts logical client identifier and payload from a server-side data frame.
|
||||||
|
//! \~russian Извлекает идентификатор логического клиента и полезную нагрузку из серверного кадра данных.
|
||||||
PIPair<uint, PIByteArray> parseDataServer(PIByteArray & ba);
|
PIPair<uint, PIByteArray> parseDataServer(PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Validates and returns raw connect payload used for server identity exchange.
|
||||||
|
//! \~russian Проверяет и возвращает сырой payload подключения, используемый при обмене идентичностью сервера.
|
||||||
PIByteArray parseConnect_d(PIByteArray & ba);
|
PIByteArray parseConnect_d(PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Extracts logical client identifier from a connect frame.
|
||||||
|
//! \~russian Извлекает идентификатор логического клиента из кадра подключения.
|
||||||
uint parseConnect(PIByteArray & ba);
|
uint parseConnect(PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Extracts logical client identifier from a disconnect frame.
|
||||||
|
//! \~russian Извлекает идентификатор логического клиента из кадра отключения.
|
||||||
uint parseDisconnect(PIByteArray & ba);
|
uint parseDisconnect(PIByteArray & ba);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
/*! \file picodeinfo.h
|
//! \~\file picodeinfo.h
|
||||||
* \ingroup Code
|
//! \~\ingroup Code
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english C++ code info structs. See \ref code_model.
|
//! \~english C++ code info structs. See \ref code_model.
|
||||||
* \~russian Структуры для C++ кода. Подробнее \ref code_model.
|
//! \~russian Структуры для C++ кода. Подробнее \ref code_model.
|
||||||
*/
|
//! \~\details
|
||||||
|
//! \~english Contains structures for code generation and reflection: TypeInfo, FunctionInfo, ClassInfo, EnumInfo, EnumeratorInfo.
|
||||||
|
//! \~russian Содержит структуры для кодогенерации и рефлексии: TypeInfo, FunctionInfo, ClassInfo, EnumInfo, EnumeratorInfo.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
C++ code info structs
|
C++ code info structs
|
||||||
@@ -36,34 +38,49 @@ class PIVariant;
|
|||||||
|
|
||||||
//! \~english Namespace contains structures for code generation. See \ref code_model.
|
//! \~english Namespace contains structures for code generation. See \ref code_model.
|
||||||
//! \~russian Пространство имен содержит структуры для кодогенерации. Подробнее \ref code_model.
|
//! \~russian Пространство имен содержит структуры для кодогенерации. Подробнее \ref code_model.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Provides classes and structures for code introspection, including type information, function details, class metadata, and enum
|
||||||
|
//! information.
|
||||||
|
//! \~russian Предоставляет классы и структуры для интроспекции кода, включая информацию о типах, детали функций, метаданные классов и
|
||||||
|
//! информацию о перечислениях.
|
||||||
namespace PICodeInfo {
|
namespace PICodeInfo {
|
||||||
|
|
||||||
|
|
||||||
//! \~english
|
//! \~english Type modifiers.
|
||||||
//! Type modifiers
|
//! \~russian Модификаторы типа.
|
||||||
//! \~russian
|
|
||||||
//! Модификаторы типа
|
|
||||||
enum TypeFlag {
|
enum TypeFlag {
|
||||||
NoFlag,
|
NoFlag /** \~english No modifiers. \~russian Модификаторы отсутствуют. */,
|
||||||
Const /** const */ = 0x01,
|
Const = 0x01 /** \~english \c const modifier. \~russian Модификатор \c const. */,
|
||||||
Static /** static */ = 0x02,
|
Static = 0x02 /** \~english \c static modifier. \~russian Модификатор \c static. */,
|
||||||
Mutable /** mutable */ = 0x04,
|
Mutable = 0x04 /** \~english \c mutable modifier. \~russian Модификатор \c mutable. */,
|
||||||
Volatile /** volatile */ = 0x08,
|
Volatile = 0x08 /** \~english \c volatile modifier. \~russian Модификатор \c volatile. */,
|
||||||
Inline /** inline */ = 0x10,
|
Inline = 0x10 /** \~english \c inline modifier. \~russian Модификатор \c inline. */,
|
||||||
Virtual /** virtual */ = 0x20,
|
Virtual = 0x20 /** \~english \c virtual modifier. \~russian Модификатор \c virtual. */,
|
||||||
Extern /** extern */ = 0x40
|
Extern = 0x40 /** \~english \c extern modifier. \~russian Модификатор \c extern. */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Bitmask of type modifiers.
|
||||||
|
//! \~russian Битовая маска модификаторов типа.
|
||||||
typedef PIFlags<PICodeInfo::TypeFlag> TypeFlags;
|
typedef PIFlags<PICodeInfo::TypeFlag> TypeFlags;
|
||||||
|
//! \~english Custom metadata map produced by \c PIMETA.
|
||||||
|
//! \~russian Карта пользовательских метаданных, создаваемых \c PIMETA.
|
||||||
typedef PIMap<PIString, PIString> MetaMap;
|
typedef PIMap<PIString, PIString> MetaMap;
|
||||||
|
//! \~english Callback returning serialized member data by member name.
|
||||||
|
//! \~russian Обратный вызов, возвращающий сериализованные данные члена по имени.
|
||||||
typedef PIByteArray (*AccessValueFunction)(const void *, const char *);
|
typedef PIByteArray (*AccessValueFunction)(const void *, const char *);
|
||||||
|
//! \~english Callback returning a member type name by member name.
|
||||||
|
//! \~russian Обратный вызов, возвращающий имя типа члена по его имени.
|
||||||
typedef const char * (*AccessTypeFunction)(const char *);
|
typedef const char * (*AccessTypeFunction)(const char *);
|
||||||
|
//! \~english Callback returning a member offset by member name.
|
||||||
|
//! \~russian Обратный вызов, возвращающий смещение члена по его имени.
|
||||||
typedef int (*AccessOffsetFunction)(const char *);
|
typedef int (*AccessOffsetFunction)(const char *);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Type information
|
//! \~english Type information
|
||||||
//! \~russian Информация о типе
|
//! \~russian Информация о типе
|
||||||
struct PIP_EXPORT TypeInfo {
|
struct PIP_EXPORT TypeInfo {
|
||||||
|
//! \~english Constructs type information for one variable or argument.
|
||||||
|
//! \~russian Создает описание типа для одной переменной или аргумента.
|
||||||
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {
|
TypeInfo(const PIConstChars & n = PIConstChars(), const PIConstChars & t = PIConstChars(), PICodeInfo::TypeFlags f = 0, int b = -1) {
|
||||||
name = n;
|
name = n;
|
||||||
type = t;
|
type = t;
|
||||||
@@ -71,8 +88,8 @@ struct PIP_EXPORT TypeInfo {
|
|||||||
bits = b;
|
bits = b;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns if variable if bitfield
|
//! \~english Returns whether the described variable is a bitfield.
|
||||||
//! \~russian Возвращает битовым ли полем является переменная
|
//! \~russian Возвращает, является ли описываемая переменная битовым полем.
|
||||||
bool isBitfield() const { return bits > 0; }
|
bool isBitfield() const { return bits > 0; }
|
||||||
|
|
||||||
//! \~english Custom PIMETA content
|
//! \~english Custom PIMETA content
|
||||||
@@ -109,7 +126,7 @@ struct PIP_EXPORT FunctionInfo {
|
|||||||
PIConstChars name;
|
PIConstChars name;
|
||||||
|
|
||||||
//! \~english Return type
|
//! \~english Return type
|
||||||
//! \~russian Возвращаемые тип
|
//! \~russian Возвращаемый тип
|
||||||
TypeInfo return_type;
|
TypeInfo return_type;
|
||||||
|
|
||||||
//! \~english Arguments types
|
//! \~english Arguments types
|
||||||
@@ -121,26 +138,28 @@ struct PIP_EXPORT FunctionInfo {
|
|||||||
//! \~english Class or struct information
|
//! \~english Class or struct information
|
||||||
//! \~russian Информация о классе или структуре
|
//! \~russian Информация о классе или структуре
|
||||||
struct PIP_EXPORT ClassInfo {
|
struct PIP_EXPORT ClassInfo {
|
||||||
|
//! \~english Constructs an empty class description.
|
||||||
|
//! \~russian Создает пустое описание класса.
|
||||||
ClassInfo() { is_anonymous = false; }
|
ClassInfo() { is_anonymous = false; }
|
||||||
|
|
||||||
//! \~english Custom PIMETA content
|
//! \~english Custom PIMETA content
|
||||||
//! \~russian Произвольное содержимое PIMETA
|
//! \~russian Произвольное содержимое PIMETA
|
||||||
MetaMap meta;
|
MetaMap meta;
|
||||||
|
|
||||||
//! \~english Anonymous or not
|
//! \~english Indicates that the type was declared without a name
|
||||||
//! \~russian Анонимный или нет
|
//! \~russian Показывает, что тип был объявлен без имени
|
||||||
bool is_anonymous;
|
bool is_anonymous;
|
||||||
|
|
||||||
//! \~english Type
|
//! \~english Declaration kind, for example \c class or \c struct
|
||||||
//! \~russian Тип
|
//! \~russian Вид объявления, например \c class или \c struct
|
||||||
PIConstChars type;
|
PIConstChars type;
|
||||||
|
|
||||||
//! \~english Name
|
//! \~english Name
|
||||||
//! \~russian Имя
|
//! \~russian Имя
|
||||||
PIConstChars name;
|
PIConstChars name;
|
||||||
|
|
||||||
//! \~english Parent names
|
//! \~english Base class names
|
||||||
//! \~russian Имена родителей
|
//! \~russian Имена базовых классов
|
||||||
PIVector<PIConstChars> parents;
|
PIVector<PIConstChars> parents;
|
||||||
|
|
||||||
//! \~english Variables
|
//! \~english Variables
|
||||||
@@ -151,8 +170,8 @@ struct PIP_EXPORT ClassInfo {
|
|||||||
//! \~russian Методы
|
//! \~russian Методы
|
||||||
PIVector<PICodeInfo::FunctionInfo> functions;
|
PIVector<PICodeInfo::FunctionInfo> functions;
|
||||||
|
|
||||||
//! \~english Subclass list
|
//! \~english Registered derived class descriptions
|
||||||
//! \~russian Список наследников
|
//! \~russian Зарегистрированные описания производных классов
|
||||||
PIVector<PICodeInfo::ClassInfo *> children_info;
|
PIVector<PICodeInfo::ClassInfo *> children_info;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -160,10 +179,14 @@ struct PIP_EXPORT ClassInfo {
|
|||||||
//! \~english Enumerator information
|
//! \~english Enumerator information
|
||||||
//! \~russian Информация об элементе перечисления
|
//! \~russian Информация об элементе перечисления
|
||||||
struct PIP_EXPORT EnumeratorInfo {
|
struct PIP_EXPORT EnumeratorInfo {
|
||||||
|
//! \~english Constructs one enum member description.
|
||||||
|
//! \~russian Создает описание одного элемента перечисления.
|
||||||
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {
|
EnumeratorInfo(const PIConstChars & n = PIConstChars(), int v = 0) {
|
||||||
name = n;
|
name = n;
|
||||||
value = v;
|
value = v;
|
||||||
}
|
}
|
||||||
|
//! \~english Converts the enumerator to the %PIVariantTypes representation.
|
||||||
|
//! \~russian Преобразует элемент перечисления в представление %PIVariantTypes.
|
||||||
PIVariantTypes::Enumerator toPIVariantEnumerator() { return PIVariantTypes::Enumerator(value, name.toString()); }
|
PIVariantTypes::Enumerator toPIVariantEnumerator() { return PIVariantTypes::Enumerator(value, name.toString()); }
|
||||||
|
|
||||||
//! \~english Custom PIMETA content
|
//! \~english Custom PIMETA content
|
||||||
@@ -183,16 +206,16 @@ struct PIP_EXPORT EnumeratorInfo {
|
|||||||
//! \~english Enum information
|
//! \~english Enum information
|
||||||
//! \~russian Информация о перечислении
|
//! \~russian Информация о перечислении
|
||||||
struct PIP_EXPORT EnumInfo {
|
struct PIP_EXPORT EnumInfo {
|
||||||
//! \~english Returns member name with value "value"
|
//! \~english Returns the member name for the value \a value.
|
||||||
//! \~russian Возвращает имя элемента со значением "value"
|
//! \~russian Возвращает имя элемента для значения \a value.
|
||||||
PIString memberName(int value) const;
|
PIString memberName(int value) const;
|
||||||
|
|
||||||
//! \~english Returns member value with name "name"
|
//! \~english Returns the member value for the name \a name.
|
||||||
//! \~russian Возвращает значение элемента с именем "name"
|
//! \~russian Возвращает значение элемента для имени \a name.
|
||||||
int memberValue(const PIString & name) const;
|
int memberValue(const PIString & name) const;
|
||||||
|
|
||||||
//! \~english Returns as PIVariantTypes::Enum
|
//! \~english Converts the enum description to %PIVariantTypes::Enum.
|
||||||
//! \~russian Возвращает как PIVariantTypes::Enum
|
//! \~russian Преобразует описание перечисления в %PIVariantTypes::Enum.
|
||||||
PIVariantTypes::Enum toPIVariantEnum();
|
PIVariantTypes::Enum toPIVariantEnum();
|
||||||
|
|
||||||
//! \~english Custom PIMETA content
|
//! \~english Custom PIMETA content
|
||||||
@@ -209,6 +232,8 @@ struct PIP_EXPORT EnumInfo {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Writes a declaration-like view of \a v to \a s.
|
||||||
|
//! \~russian Записывает в \a s представление \a v в стиле объявления.
|
||||||
inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
||||||
if (v.flags[Inline]) s << "inline ";
|
if (v.flags[Inline]) s << "inline ";
|
||||||
if (v.flags[Virtual]) s << "virtual ";
|
if (v.flags[Virtual]) s << "virtual ";
|
||||||
@@ -221,11 +246,15 @@ inline PICout operator<<(PICout s, const PICodeInfo::TypeInfo & v) {
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Writes an enum member description to \a s.
|
||||||
|
//! \~russian Записывает описание элемента перечисления в \a s.
|
||||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumeratorInfo & v) {
|
inline PICout operator<<(PICout s, const PICodeInfo::EnumeratorInfo & v) {
|
||||||
s << v.name << " = " << v.value << " Meta" << v.meta;
|
s << v.name << " = " << v.value << " Meta" << v.meta;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Writes a human-readable class description to \a s.
|
||||||
|
//! \~russian Записывает в \a s человекочитаемое описание класса.
|
||||||
inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
s << "class " << v.name;
|
s << "class " << v.name;
|
||||||
@@ -262,6 +291,8 @@ inline PICout operator<<(PICout s, const PICodeInfo::ClassInfo & v) {
|
|||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Writes a human-readable enum description to \a s.
|
||||||
|
//! \~russian Записывает в \a s человекочитаемое описание перечисления.
|
||||||
inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
inline PICout operator<<(PICout s, const PICodeInfo::EnumInfo & v) {
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
s << "enum " << v.name << " Meta" << v.meta << " {\n";
|
s << "enum " << v.name << " Meta" << v.meta << " {\n";
|
||||||
@@ -296,18 +327,13 @@ private:
|
|||||||
NO_COPY_CLASS(__Storage__)
|
NO_COPY_CLASS(__Storage__)
|
||||||
};
|
};
|
||||||
|
|
||||||
class PIP_EXPORT
|
class PIP_EXPORT __StorageAccess__ {
|
||||||
__StorageAccess__{public:
|
public:
|
||||||
//! \~english Getter for single storage of PICodeInfo::ClassInfo, access by name
|
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes() {
|
||||||
//! \~russian Доступ к единому хранилищу PICodeInfo::ClassInfo, доступ по имени
|
return *(__Storage__::instance()->classesInfo);
|
||||||
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes(){return *(__Storage__::instance()->classesInfo);
|
|
||||||
} // namespace PICodeInfo
|
} // namespace PICodeInfo
|
||||||
|
|
||||||
//! \~english Getter for single storage of PICodeInfo::EnumInfo, access by name
|
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() { return *(__Storage__::instance()->enumsInfo); }
|
||||||
//! \~russian Доступ к единому хранилищу хранилище PICodeInfo::EnumInfo, доступ по имени
|
|
||||||
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() {
|
|
||||||
return *(__Storage__::instance()->enumsInfo);
|
|
||||||
}
|
|
||||||
|
|
||||||
static const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> & accessValueFunctions() {
|
static const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> & accessValueFunctions() {
|
||||||
return *(__Storage__::instance()->accessValueFunctions);
|
return *(__Storage__::instance()->accessValueFunctions);
|
||||||
@@ -320,47 +346,51 @@ static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFun
|
|||||||
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
|
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
|
||||||
return *(__Storage__::instance()->accessOffsetFunctions);
|
return *(__Storage__::instance()->accessOffsetFunctions);
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
;
|
|
||||||
|
|
||||||
|
//! \relatesalso PICodeInfo
|
||||||
|
//! \~english Macro for the global code model registries.
|
||||||
|
//! \~russian Макрос для доступа к глобальным реестрам модели кода.
|
||||||
#define PICODEINFO PICodeInfo::__StorageAccess__
|
#define PICODEINFO PICodeInfo::__StorageAccess__
|
||||||
|
|
||||||
|
|
||||||
class PIP_EXPORT
|
class PIP_EXPORT ClassInfoInterface {
|
||||||
ClassInfoInterface{public: const PIMap<PIConstChars, PICodeInfo::ClassInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::classes()"){
|
public:
|
||||||
|
const PIMap<PIConstChars, PICodeInfo::ClassInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::classes()") {
|
||||||
return __Storage__::instance()->classesInfo;
|
return __Storage__::instance()->classesInfo;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
;
|
|
||||||
static ClassInfoInterface classesInfo;
|
static ClassInfoInterface classesInfo;
|
||||||
|
|
||||||
|
|
||||||
class PIP_EXPORT
|
class PIP_EXPORT EnumsInfoInterface {
|
||||||
EnumsInfoInterface{public: const PIMap<PIConstChars, PICodeInfo::EnumInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::enums()"){
|
public:
|
||||||
|
const PIMap<PIConstChars, PICodeInfo::EnumInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::enums()") {
|
||||||
return __Storage__::instance()->enumsInfo;
|
return __Storage__::instance()->enumsInfo;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
;
|
|
||||||
static EnumsInfoInterface enumsInfo;
|
static EnumsInfoInterface enumsInfo;
|
||||||
|
|
||||||
|
|
||||||
class PIP_EXPORT AccessValueFunctionInterface {
|
class PIP_EXPORT AccessValueFunctionInterface {
|
||||||
public: const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * operator->()
|
public:
|
||||||
const DEPRECATEDM("use PICODEINFO::accessValueFunctions()"){
|
const PIMap<PIConstChars, PICodeInfo::AccessValueFunction> * operator->() const DEPRECATEDM("use PICODEINFO::accessValueFunctions()") {
|
||||||
return __Storage__::instance()->accessValueFunctions;
|
return __Storage__::instance()->accessValueFunctions;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
;
|
|
||||||
static AccessValueFunctionInterface accessValueFunctions;
|
static AccessValueFunctionInterface accessValueFunctions;
|
||||||
|
|
||||||
|
|
||||||
class PIP_EXPORT AccessTypeFunctionInterface {
|
class PIP_EXPORT AccessTypeFunctionInterface {
|
||||||
public: const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * operator->()
|
public:
|
||||||
const DEPRECATEDM("use PICODEINFO::accessTypeFunctions()"){
|
const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> * operator->() const DEPRECATEDM("use PICODEINFO::accessTypeFunctions()") {
|
||||||
return __Storage__::instance()->accessTypeFunctions;
|
return __Storage__::instance()->accessTypeFunctions;
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
;
|
|
||||||
static AccessTypeFunctionInterface accessTypeFunctions;
|
static AccessTypeFunctionInterface accessTypeFunctions;
|
||||||
|
|
||||||
|
|
||||||
@@ -372,6 +402,8 @@ STATIC_INITIALIZER_BEGIN
|
|||||||
STATIC_INITIALIZER_END
|
STATIC_INITIALIZER_END
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns a serialized value of \a member_name from an instance of \a class_name.
|
||||||
|
//! \~russian Возвращает сериализованное значение \a member_name из экземпляра \a class_name.
|
||||||
inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) {
|
inline PIByteArray getMemberValue(const void * p, const char * class_name, const char * member_name) {
|
||||||
if (!p || !class_name || !member_name) return PIByteArray();
|
if (!p || !class_name || !member_name) return PIByteArray();
|
||||||
AccessValueFunction af = PICODEINFO::accessValueFunctions().value(class_name, (AccessValueFunction)0);
|
AccessValueFunction af = PICODEINFO::accessValueFunctions().value(class_name, (AccessValueFunction)0);
|
||||||
@@ -379,6 +411,8 @@ inline PIByteArray getMemberValue(const void * p, const char * class_name, const
|
|||||||
return af(p, member_name);
|
return af(p, member_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns the registered type name of \a member_name in \a class_name.
|
||||||
|
//! \~russian Возвращает зарегистрированное имя типа \a member_name в \a class_name.
|
||||||
inline const char * getMemberType(const char * class_name, const char * member_name) {
|
inline const char * getMemberType(const char * class_name, const char * member_name) {
|
||||||
if (!class_name || !member_name) return "";
|
if (!class_name || !member_name) return "";
|
||||||
AccessTypeFunction af = PICODEINFO::accessTypeFunctions().value(class_name, (AccessTypeFunction)0);
|
AccessTypeFunction af = PICODEINFO::accessTypeFunctions().value(class_name, (AccessTypeFunction)0);
|
||||||
@@ -386,14 +420,20 @@ inline const char * getMemberType(const char * class_name, const char * member_n
|
|||||||
return af(member_name);
|
return af(member_name);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns \a member_name from \a class_name as %PIVariant when accessors are registered.
|
||||||
|
//! \~russian Возвращает \a member_name из \a class_name как %PIVariant, если зарегистрированы функции доступа.
|
||||||
PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
|
PIP_EXPORT PIVariant getMemberAsVariant(const void * p, const char * class_name, const char * member_name);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Serializes assignable values into \a ret through the stream operator.
|
||||||
|
//! \~russian Сериализует присваиваемые значения в \a ret через оператор потока.
|
||||||
template<typename T, typename std::enable_if<std::is_assignable<T &, const T &>::value, int>::type = 0>
|
template<typename T, typename std::enable_if<std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||||
void serialize(PIByteArray & ret, const T & v) {
|
void serialize(PIByteArray & ret, const T & v) {
|
||||||
ret << v;
|
ret << v;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Fallback overload for values that cannot be written to the byte-array stream.
|
||||||
|
//! \~russian Резервная перегрузка для значений, которые нельзя записать в поток массива байт.
|
||||||
template<typename T, typename std::enable_if<!std::is_assignable<T &, const T &>::value, int>::type = 0>
|
template<typename T, typename std::enable_if<!std::is_assignable<T &, const T &>::value, int>::type = 0>
|
||||||
void serialize(PIByteArray & ret, const T & v) {}
|
void serialize(PIByteArray & ret, const T & v) {}
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file picodemodule.h
|
||||||
|
* \ingroup Code
|
||||||
|
* \~\brief
|
||||||
|
* \~english Umbrella header for the code parsing module
|
||||||
|
* \~russian Общий заголовок модуля разбора кода
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public code information and parser headers.
|
||||||
|
* \~russian Подключает публичные заголовки информации о коде и парсера.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -34,12 +44,12 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides parsing C++ code and storage to use results of \a pip_cmg utility.
|
//! This module provides C++ source parsing and the storage types used by the
|
||||||
//! See \ref code_model.
|
//! \a pip_cmg utility. See \ref code_model.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают разбор C++ кода и хранение результатов работы утилиты \a pip_cmg.
|
//! Этот модуль предоставляет разбор исходного кода C++ и типы хранения,
|
||||||
//! Подробнее \ref code_model.
|
//! используемые утилитой \a pip_cmg. Подробнее \ref code_model.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picodeparser.h
|
//! \~\file picodeparser.h
|
||||||
* \ingroup Code
|
//! \~\ingroup Code
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english C++ code parser
|
//! \~english C++ code parser
|
||||||
* \~russian Разбор C++ кода
|
//! \~russian Разбор C++ кода
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
C++ code parser
|
C++ code parser
|
||||||
@@ -37,44 +36,88 @@ inline bool _isCChar(const PIString & c) {
|
|||||||
return _isCChar(c[0]);
|
return _isCChar(c[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~\ingroup Code
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Parser of C/C++ declarations used by the code model tools.
|
||||||
|
//! \~russian Разборщик объявлений C/C++, используемый инструментами модели кода.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Parser for analyzing C++ source files. Extracts information about classes, structures, enums, macros, functions, and members.
|
||||||
|
//! \~russian Парсер для анализа C++ исходных файлов. Извлекает информацию о классах, структурах, перечислениях, макросах, функциях и
|
||||||
|
//! членах.
|
||||||
class PIP_EXPORT PICodeParser {
|
class PIP_EXPORT PICodeParser {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a parser with built-in PIP macro presets.
|
||||||
|
//! \~russian Создает разборщик со встроенными предустановками макросов PIP.
|
||||||
PICodeParser();
|
PICodeParser();
|
||||||
|
|
||||||
|
//! \~english Visibility of a parsed declaration inside the current scope.
|
||||||
|
//! \~russian Видимость разобранного объявления в текущей области.
|
||||||
enum Visibility {
|
enum Visibility {
|
||||||
Global,
|
Global /** \~english Global or namespace-level declaration. \~russian Глобальное объявление или объявление уровня пространства имен.
|
||||||
Public,
|
*/
|
||||||
Protected,
|
,
|
||||||
Private
|
Public /** \~english Public class member. \~russian Открытый член класса. */,
|
||||||
};
|
Protected /** \~english Protected class member. \~russian Защищенный член класса. */,
|
||||||
enum Attribute {
|
Private /** \~english Private class member. \~russian Закрытый член класса. */
|
||||||
NoAttributes = 0x0,
|
|
||||||
Const = 0x01,
|
|
||||||
Static = 0x02,
|
|
||||||
Mutable = 0x04,
|
|
||||||
Volatile = 0x08,
|
|
||||||
Inline = 0x10,
|
|
||||||
Virtual = 0x20,
|
|
||||||
Extern = 0x40
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parsed declaration attributes.
|
||||||
|
//! \~russian Атрибуты разобранного объявления.
|
||||||
|
enum Attribute {
|
||||||
|
NoAttributes = 0x0 /** \~english No attributes. \~russian Атрибуты отсутствуют. */,
|
||||||
|
Const = 0x01 /** \~english \c const declaration. \~russian Объявление с \c const. */,
|
||||||
|
Static = 0x02 /** \~english \c static declaration. \~russian Объявление с \c static. */,
|
||||||
|
Mutable = 0x04 /** \~english \c mutable declaration. \~russian Объявление с \c mutable. */,
|
||||||
|
Volatile = 0x08 /** \~english \c volatile declaration. \~russian Объявление с \c volatile. */,
|
||||||
|
Inline = 0x10 /** \~english \c inline declaration. \~russian Объявление с \c inline. */,
|
||||||
|
Virtual = 0x20 /** \~english \c virtual declaration. \~russian Объявление с \c virtual. */,
|
||||||
|
Extern = 0x40 /** \~english \c extern declaration. \~russian Объявление с \c extern. */
|
||||||
|
};
|
||||||
|
|
||||||
|
//! \~english Bitmask of parsed declaration attributes.
|
||||||
|
//! \~russian Битовая маска атрибутов разобранного объявления.
|
||||||
typedef PIFlags<Attribute> Attributes;
|
typedef PIFlags<Attribute> Attributes;
|
||||||
|
|
||||||
|
//! \~english Preprocessor define name and value.
|
||||||
|
//! \~russian Имя и значение макроса \c define.
|
||||||
typedef PIPair<PIString, PIString> Define;
|
typedef PIPair<PIString, PIString> Define;
|
||||||
|
|
||||||
|
//! \~english Typedef alias and target type.
|
||||||
|
//! \~russian Псевдоним typedef и целевой тип.
|
||||||
typedef PIPair<PIString, PIString> Typedef;
|
typedef PIPair<PIString, PIString> Typedef;
|
||||||
|
|
||||||
|
//! \~english Parsed metadata map.
|
||||||
|
//! \~russian Карта разобранных метаданных.
|
||||||
typedef PIMap<PIString, PIString> MetaMap;
|
typedef PIMap<PIString, PIString> MetaMap;
|
||||||
|
|
||||||
|
//! \~english Parsed function-like macro.
|
||||||
|
//! \~russian Разобранный функциональный макрос.
|
||||||
struct PIP_EXPORT Macro {
|
struct PIP_EXPORT Macro {
|
||||||
Macro(const PIString & n = PIString(), const PIString & v = PIString(), const PIStringList & a = PIStringList()) {
|
Macro(const PIString & n = PIString(), const PIString & v = PIString(), const PIStringList & a = PIStringList()) {
|
||||||
name = n;
|
name = n;
|
||||||
value = v;
|
value = v;
|
||||||
args = a;
|
args = a;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Expands the macro body with arguments from \a args_.
|
||||||
|
//! \~russian Разворачивает тело макроса с аргументами из \a args_.
|
||||||
PIString expand(PIString args_, bool * ok = 0) const;
|
PIString expand(PIString args_, bool * ok = 0) const;
|
||||||
|
|
||||||
|
//! \~english Macro name.
|
||||||
|
//! \~russian Имя макроса.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Macro replacement text.
|
||||||
|
//! \~russian Текст замены макроса.
|
||||||
PIString value;
|
PIString value;
|
||||||
|
|
||||||
|
//! \~english Ordered list of macro argument names.
|
||||||
|
//! \~russian Упорядоченный список имен аргументов макроса.
|
||||||
PIStringList args;
|
PIStringList args;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parsed member declaration or function signature.
|
||||||
|
//! \~russian Разобранное объявление члена или сигнатура функции.
|
||||||
struct PIP_EXPORT Member {
|
struct PIP_EXPORT Member {
|
||||||
Member() {
|
Member() {
|
||||||
visibility = Global;
|
visibility = Global;
|
||||||
@@ -83,20 +126,58 @@ public:
|
|||||||
is_type_ptr = false;
|
is_type_ptr = false;
|
||||||
attributes = NoAttributes;
|
attributes = NoAttributes;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns whether the member is declared as a bitfield.
|
||||||
|
//! \~russian Возвращает, объявлен ли член как битовое поле.
|
||||||
bool isBitfield() const { return bits > 0; }
|
bool isBitfield() const { return bits > 0; }
|
||||||
|
|
||||||
|
//! \~english Parsed metadata attached to the member.
|
||||||
|
//! \~russian Разобранные метаданные, привязанные к члену.
|
||||||
MetaMap meta;
|
MetaMap meta;
|
||||||
|
|
||||||
|
//! \~english Member type or return type.
|
||||||
|
//! \~russian Тип члена или возвращаемый тип.
|
||||||
PIString type;
|
PIString type;
|
||||||
|
|
||||||
|
//! \~english Member name.
|
||||||
|
//! \~russian Имя члена.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Full textual argument declarations.
|
||||||
|
//! \~russian Полные текстовые объявления аргументов.
|
||||||
PIStringList arguments_full;
|
PIStringList arguments_full;
|
||||||
|
|
||||||
|
//! \~english Argument types only.
|
||||||
|
//! \~russian Только типы аргументов.
|
||||||
PIStringList arguments_type;
|
PIStringList arguments_type;
|
||||||
|
|
||||||
|
//! \~english Parsed array dimensions.
|
||||||
|
//! \~russian Разобранные размеры массива.
|
||||||
PIStringList dims;
|
PIStringList dims;
|
||||||
|
|
||||||
|
//! \~english Member visibility.
|
||||||
|
//! \~russian Видимость члена.
|
||||||
Visibility visibility;
|
Visibility visibility;
|
||||||
|
|
||||||
|
//! \~english Member attributes.
|
||||||
|
//! \~russian Атрибуты члена.
|
||||||
Attributes attributes;
|
Attributes attributes;
|
||||||
|
|
||||||
|
//! \~english Indicates that the parsed type is a pointer.
|
||||||
|
//! \~russian Показывает, что разобранный тип является указателем.
|
||||||
bool is_type_ptr;
|
bool is_type_ptr;
|
||||||
|
|
||||||
|
//! \~english Parsed size in bytes when available.
|
||||||
|
//! \~russian Разобранный размер в байтах, если он известен.
|
||||||
int size;
|
int size;
|
||||||
|
|
||||||
|
//! \~english Bit count for bitfields, or \c -1 otherwise.
|
||||||
|
//! \~russian Количество бит для битового поля или \c -1 в остальных случаях.
|
||||||
int bits;
|
int bits;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parsed class, struct or namespace.
|
||||||
|
//! \~russian Разобранный класс, структура или пространство имен.
|
||||||
struct PIP_EXPORT Entity {
|
struct PIP_EXPORT Entity {
|
||||||
Entity() {
|
Entity() {
|
||||||
visibility = Global;
|
visibility = Global;
|
||||||
@@ -104,57 +185,165 @@ public:
|
|||||||
size = 0;
|
size = 0;
|
||||||
parent_scope = 0;
|
parent_scope = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Parsed metadata attached to the entity.
|
||||||
|
//! \~russian Разобранные метаданные, привязанные к сущности.
|
||||||
MetaMap meta;
|
MetaMap meta;
|
||||||
|
|
||||||
|
//! \~english Entity kind, for example \c class, \c struct or \c namespace.
|
||||||
|
//! \~russian Вид сущности, например \c class, \c struct или \c namespace.
|
||||||
PIString type;
|
PIString type;
|
||||||
|
|
||||||
|
//! \~english Entity name.
|
||||||
|
//! \~russian Имя сущности.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Source file where the entity was parsed.
|
||||||
|
//! \~russian Исходный файл, в котором была разобрана сущность.
|
||||||
PIString file;
|
PIString file;
|
||||||
|
|
||||||
|
//! \~english Entity visibility inside its parent scope.
|
||||||
|
//! \~russian Видимость сущности внутри родительской области.
|
||||||
Visibility visibility;
|
Visibility visibility;
|
||||||
|
|
||||||
|
//! \~english Parsed size in bytes when available.
|
||||||
|
//! \~russian Разобранный размер в байтах, если он известен.
|
||||||
int size;
|
int size;
|
||||||
|
|
||||||
|
//! \~english Indicates that the entity was declared without a name.
|
||||||
|
//! \~russian Показывает, что сущность объявлена без имени.
|
||||||
bool is_anonymous;
|
bool is_anonymous;
|
||||||
|
|
||||||
|
//! \~english Immediate containing entity, or \c nullptr for the root scope.
|
||||||
|
//! \~russian Непосредственная содержащая сущность или \c nullptr для корневой области.
|
||||||
Entity * parent_scope;
|
Entity * parent_scope;
|
||||||
|
|
||||||
|
//! \~english Direct base entities.
|
||||||
|
//! \~russian Непосредственные базовые сущности.
|
||||||
PIVector<Entity *> parents;
|
PIVector<Entity *> parents;
|
||||||
|
|
||||||
|
//! \~english Parsed member functions.
|
||||||
|
//! \~russian Разобранные функции-члены.
|
||||||
PIVector<Member> functions;
|
PIVector<Member> functions;
|
||||||
|
|
||||||
|
//! \~english Parsed data members.
|
||||||
|
//! \~russian Разобранные поля данных.
|
||||||
PIVector<Member> members;
|
PIVector<Member> members;
|
||||||
|
|
||||||
|
//! \~english Typedefs declared inside the entity.
|
||||||
|
//! \~russian Typedef-объявления внутри сущности.
|
||||||
PIVector<Typedef> typedefs;
|
PIVector<Typedef> typedefs;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parsed enumerator entry.
|
||||||
|
//! \~russian Разобранный элемент перечисления.
|
||||||
struct PIP_EXPORT EnumeratorInfo {
|
struct PIP_EXPORT EnumeratorInfo {
|
||||||
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {
|
EnumeratorInfo(const PIString & n = PIString(), int v = 0, const MetaMap & m = MetaMap()) {
|
||||||
name = n;
|
name = n;
|
||||||
value = v;
|
value = v;
|
||||||
meta = m;
|
meta = m;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Parsed metadata attached to the enumerator.
|
||||||
|
//! \~russian Разобранные метаданные, привязанные к элементу перечисления.
|
||||||
MetaMap meta;
|
MetaMap meta;
|
||||||
|
|
||||||
|
//! \~english Enumerator name.
|
||||||
|
//! \~russian Имя элемента перечисления.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Enumerator value.
|
||||||
|
//! \~russian Значение элемента перечисления.
|
||||||
int value;
|
int value;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parsed enumeration.
|
||||||
|
//! \~russian Разобранное перечисление.
|
||||||
struct PIP_EXPORT Enum {
|
struct PIP_EXPORT Enum {
|
||||||
Enum(const PIString & n = PIString()) { name = n; }
|
Enum(const PIString & n = PIString()) { name = n; }
|
||||||
|
|
||||||
|
//! \~english Parsed metadata attached to the enum.
|
||||||
|
//! \~russian Разобранные метаданные, привязанные к перечислению.
|
||||||
MetaMap meta;
|
MetaMap meta;
|
||||||
|
|
||||||
|
//! \~english Enum name.
|
||||||
|
//! \~russian Имя перечисления.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Parsed enumerators.
|
||||||
|
//! \~russian Разобранные элементы перечисления.
|
||||||
PIVector<EnumeratorInfo> members;
|
PIVector<EnumeratorInfo> members;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Parses one source file and optionally follows its includes.
|
||||||
|
//! \~russian Разбирает один исходный файл и при необходимости следует по его include-зависимостям.
|
||||||
void parseFile(const PIString & file, bool follow_includes = true);
|
void parseFile(const PIString & file, bool follow_includes = true);
|
||||||
|
|
||||||
|
//! \~english Parses several source files into one parser state.
|
||||||
|
//! \~russian Разбирает несколько исходных файлов в одном состоянии разборщика.
|
||||||
void parseFiles(const PIStringList & files, bool follow_includes = true);
|
void parseFiles(const PIStringList & files, bool follow_includes = true);
|
||||||
|
|
||||||
|
//! \~english Parses source text provided directly in memory.
|
||||||
|
//! \~russian Разбирает исходный текст, переданный напрямую из памяти.
|
||||||
void parseFileContent(PIString fc);
|
void parseFileContent(PIString fc);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Adds a directory to the include search list.
|
||||||
|
//! \~russian Добавляет каталог в список поиска include-файлов.
|
||||||
void includeDirectory(const PIString & dir) { includes << dir; }
|
void includeDirectory(const PIString & dir) { includes << dir; }
|
||||||
|
|
||||||
|
//! \~english Adds a custom preprocessor definition before parsing.
|
||||||
|
//! \~russian Добавляет пользовательское препроцессорное определение перед разбором.
|
||||||
void addDefine(const PIString & def_name, const PIString & def_value) { custom_defines << Define(def_name, def_value); }
|
void addDefine(const PIString & def_name, const PIString & def_value) { custom_defines << Define(def_name, def_value); }
|
||||||
|
|
||||||
|
//! \~english Returns whether an enum with \a name was parsed.
|
||||||
|
//! \~russian Возвращает, было ли разобрано перечисление с именем \a name.
|
||||||
bool isEnum(const PIString & name);
|
bool isEnum(const PIString & name);
|
||||||
|
|
||||||
|
//! \~english Finds a parsed entity by its full name.
|
||||||
|
//! \~russian Ищет разобранную сущность по ее полному имени.
|
||||||
Entity * findEntityByName(const PIString & en);
|
Entity * findEntityByName(const PIString & en);
|
||||||
|
|
||||||
|
//! \~english Returns the set of files already processed by the parser.
|
||||||
|
//! \~russian Возвращает набор файлов, уже обработанных разборщиком.
|
||||||
PIStringList parsedFiles() const { return PIStringList(proc_files.toVector()); }
|
PIStringList parsedFiles() const { return PIStringList(proc_files.toVector()); }
|
||||||
|
|
||||||
|
//! \~english Returns the file detected as the main translation unit.
|
||||||
|
//! \~russian Возвращает файл, определенный как основной единицей трансляции.
|
||||||
PIString mainFile() const { return main_file; }
|
PIString mainFile() const { return main_file; }
|
||||||
|
|
||||||
|
//! \~english Returns the synthetic global scope entity.
|
||||||
|
//! \~russian Возвращает синтетическую сущность глобальной области.
|
||||||
const PICodeParser::Entity * global() const { return &root_; }
|
const PICodeParser::Entity * global() const { return &root_; }
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns the maximum number of macro substitution passes.
|
||||||
|
//! \~russian Возвращает максимальное число проходов подстановки макросов.
|
||||||
int macrosSubstitutionMaxIterations() const { return macros_iter; }
|
int macrosSubstitutionMaxIterations() const { return macros_iter; }
|
||||||
|
|
||||||
|
//! \~english Sets the maximum number of macro substitution passes.
|
||||||
|
//! \~russian Задает максимальное число проходов подстановки макросов.
|
||||||
void setMacrosSubstitutionMaxIterations(int value) { macros_iter = value; }
|
void setMacrosSubstitutionMaxIterations(int value) { macros_iter = value; }
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Parsed \c define directives, including built-in and custom ones.
|
||||||
|
//! \~russian Разобранные директивы \c define, включая встроенные и пользовательские.
|
||||||
PIVector<Define> defines, custom_defines;
|
PIVector<Define> defines, custom_defines;
|
||||||
|
|
||||||
|
//! \~english Parsed function-like macros.
|
||||||
|
//! \~russian Разобранные функциональные макросы.
|
||||||
PIVector<Macro> macros;
|
PIVector<Macro> macros;
|
||||||
|
|
||||||
|
//! \~english Parsed enums from the processed files.
|
||||||
|
//! \~russian Разобранные перечисления из обработанных файлов.
|
||||||
PIVector<Enum> enums;
|
PIVector<Enum> enums;
|
||||||
|
|
||||||
|
//! \~english Parsed top-level typedef declarations.
|
||||||
|
//! \~russian Разобранные typedef-объявления верхнего уровня.
|
||||||
PIVector<Typedef> typedefs;
|
PIVector<Typedef> typedefs;
|
||||||
|
|
||||||
|
//! \~english Parsed entities discovered in the processed files.
|
||||||
|
//! \~russian Разобранные сущности, найденные в обработанных файлах.
|
||||||
PIVector<Entity *> entities;
|
PIVector<Entity *> entities;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,3 +1,12 @@
|
|||||||
|
//! \~\file piconsolemodule.h
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Console module headers
|
||||||
|
//! \~russian Заголовочные файлы модуля консоли
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This file includes all Console module headers providing keyboard input, screen management, and tile-based UI.
|
||||||
|
//! \~russian Этот файл включает все заголовочные файлы модуля консоли, обеспечивающие ввод с клавиатуры, управление экраном и UI на основе
|
||||||
|
//! тайлов.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -18,8 +27,8 @@
|
|||||||
*/
|
*/
|
||||||
//! \defgroup Console Console
|
//! \defgroup Console Console
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Console graphic
|
//! \~english Console screen, input, and terminal utilities
|
||||||
//! \~russian Графика в консоли
|
//! \~russian Средства консольного экрана, ввода и терминала
|
||||||
//!
|
//!
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english \section cmake_module_Console Building with CMake
|
//! \~english \section cmake_module_Console Building with CMake
|
||||||
@@ -34,10 +43,10 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides grab keyboard from console, simple tiling manager and virtual terminal.
|
//! These files provide keyboard capture from the console, a simple tile-based screen API and a virtual terminal.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают захват клавиатуры в консоли, простой тайловый менеджер и виртуальный терминал.
|
//! Эти файлы предоставляют захват клавиатуры из консоли, простой экранный API на тайлах и виртуальный терминал.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pikbdlistener.h
|
//! \~\file pikbdlistener.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Keyboard console input listener
|
//! \~english Console keyboard and mouse input listener
|
||||||
* \~russian Консольный захват клавиатуры
|
//! \~russian Слушатель клавиатурного и мышиного консольного ввода
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Keyboard grabber for console
|
Keyboard grabber for console
|
||||||
@@ -29,6 +28,10 @@
|
|||||||
#include "pithread.h"
|
#include "pithread.h"
|
||||||
#include "pitime.h"
|
#include "pitime.h"
|
||||||
|
|
||||||
|
//! \relatesalso PIKbdListener
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Waits until the active listener captures the configured exit key and then stops it.
|
||||||
|
//! \~russian Ожидает, пока активный слушатель перехватит настроенную клавишу выхода, и затем останавливает его.
|
||||||
#define WAIT_FOR_EXIT \
|
#define WAIT_FOR_EXIT \
|
||||||
while (!PIKbdListener::exiting) \
|
while (!PIKbdListener::exiting) \
|
||||||
piMSleep(PIP_MIN_MSLEEP * 5); \
|
piMSleep(PIP_MIN_MSLEEP * 5); \
|
||||||
@@ -37,87 +40,107 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Console input listener for keyboard and mouse events.
|
||||||
|
//! \~russian Слушатель консольного ввода для событий клавиатуры и мыши.
|
||||||
class PIP_EXPORT PIKbdListener: public PIThread {
|
class PIP_EXPORT PIKbdListener: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PIKbdListener, PIThread);
|
PIOBJECT_SUBCLASS(PIKbdListener, PIThread);
|
||||||
friend class PIConsole;
|
friend class PIConsole;
|
||||||
friend class PITerminal;
|
friend class PITerminal;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! Special keyboard keys
|
//! \~english Keyboard keys reported as non-character codes.
|
||||||
|
//! \~russian Клавиши, передаваемые как несимвольные коды.
|
||||||
enum SpecialKey {
|
enum SpecialKey {
|
||||||
Tab /** Tab key */ = 0x09,
|
Tab = 0x09 /** \~english Tab key \~russian Клавиша Tab */,
|
||||||
Return /** Enter key */ = 0x0a,
|
Return = 0x0a /** \~english Enter key \~russian Клавиша Enter */,
|
||||||
Esc /** Escape key */ = 0x1b,
|
Esc = 0x1b /** \~english Escape key \~russian Клавиша Escape */,
|
||||||
Space /** Space key */ = 0x20,
|
Space = 0x20 /** \~english Space key \~russian Клавиша пробела */,
|
||||||
Backspace /** Backspace key */ = 0x7f,
|
Backspace = 0x7f /** \~english Backspace key \~russian Клавиша Backspace */,
|
||||||
UpArrow /** Up arrow key */ = -1,
|
UpArrow = -1 /** \~english Up arrow key \~russian Стрелка вверх */,
|
||||||
DownArrow /** Down arrow key */ = -2,
|
DownArrow = -2 /** \~english Down arrow key \~russian Стрелка вниз */,
|
||||||
RightArrow /** Right arrow key */ = -3,
|
RightArrow = -3 /** \~english Right arrow key \~russian Стрелка вправо */,
|
||||||
LeftArrow /** Left arrow key */ = -4,
|
LeftArrow = -4 /** \~english Left arrow key \~russian Стрелка влево */,
|
||||||
Home /** Home key */ = -5,
|
Home = -5 /** \~english Home key \~russian Клавиша Home */,
|
||||||
End /** End key */ = -6,
|
End = -6 /** \~english End key \~russian Клавиша End */,
|
||||||
PageUp /** Page up key */ = -7,
|
PageUp = -7 /** \~english Page Up key \~russian Клавиша Page Up */,
|
||||||
PageDown /** Page down key */ = -8,
|
PageDown = -8 /** \~english Page Down key \~russian Клавиша Page Down */,
|
||||||
Insert /** Delete key */ = -9,
|
Insert = -9 /** \~english Insert key \~russian Клавиша Insert */,
|
||||||
Delete /** Delete key */ = -10,
|
Delete = -10 /** \~english Delete key \~russian Клавиша Delete */,
|
||||||
F1 /** F1 key */ = -11,
|
F1 = -11 /** \~english F1 key \~russian Клавиша F1 */,
|
||||||
F2 /** F2 key */ = -12,
|
F2 = -12 /** \~english F2 key \~russian Клавиша F2 */,
|
||||||
F3 /** F3 key */ = -13,
|
F3 = -13 /** \~english F3 key \~russian Клавиша F3 */,
|
||||||
F4 /** F4 key */ = -14,
|
F4 = -14 /** \~english F4 key \~russian Клавиша F4 */,
|
||||||
F5 /** F5 key */ = -15,
|
F5 = -15 /** \~english F5 key \~russian Клавиша F5 */,
|
||||||
F6 /** F6 key */ = -16,
|
F6 = -16 /** \~english F6 key \~russian Клавиша F6 */,
|
||||||
F7 /** F7 key */ = -17,
|
F7 = -17 /** \~english F7 key \~russian Клавиша F7 */,
|
||||||
F8 /** F8 key */ = -18,
|
F8 = -18 /** \~english F8 key \~russian Клавиша F8 */,
|
||||||
F9 /** F9 key */ = -19,
|
F9 = -19 /** \~english F9 key \~russian Клавиша F9 */,
|
||||||
F10 /** F10 key */ = -20,
|
F10 = -20 /** \~english F10 key \~russian Клавиша F10 */,
|
||||||
F11 /** F11 key */ = -21,
|
F11 = -21 /** \~english F11 key \~russian Клавиша F11 */,
|
||||||
F12 /** F12 key */ = -22
|
F12 = -22 /** \~english F12 key \~russian Клавиша F12 */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Keyboard modifiers
|
//! \~english Keyboard modifier bit flags.
|
||||||
|
//! \~russian Битовые флаги модификаторов клавиатуры.
|
||||||
enum KeyModifier {
|
enum KeyModifier {
|
||||||
Ctrl /** Control key */ = 0x1,
|
Ctrl = 0x1 /** \~english Control key \~russian Клавиша Control */,
|
||||||
Shift /** Shift key */ = 0x2,
|
Shift = 0x2 /** \~english Shift key \~russian Клавиша Shift */,
|
||||||
Alt /** Alt key */ = 0x4
|
Alt = 0x4 /** \~english Alt key \~russian Клавиша Alt */,
|
||||||
// Meta /** Meta (windows) key */ = 0x8
|
// Meta = 0x8 /** Meta (windows) key */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Combination of \a KeyModifier flags.
|
||||||
|
//! \~russian Комбинация флагов \a KeyModifier.
|
||||||
typedef PIFlags<KeyModifier> KeyModifiers;
|
typedef PIFlags<KeyModifier> KeyModifiers;
|
||||||
|
|
||||||
//! This struct contains information about pressed keyboard key
|
//! \~english Information about one keyboard event.
|
||||||
|
//! \~russian Информация об одном событии клавиатуры.
|
||||||
struct PIP_EXPORT KeyEvent {
|
struct PIP_EXPORT KeyEvent {
|
||||||
|
//! \~english Constructs an empty event or initializes it with key and modifiers.
|
||||||
|
//! \~russian Создает пустое событие или инициализирует его клавишей и модификаторами.
|
||||||
KeyEvent(int k = 0, KeyModifiers m = 0) {
|
KeyEvent(int k = 0, KeyModifiers m = 0) {
|
||||||
key = k;
|
key = k;
|
||||||
modifiers = m;
|
modifiers = m;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey)
|
//! \~english Pressed key code. It can be a character code or one of \a SpecialKey values.
|
||||||
|
//! \~russian Код нажатой клавиши. Это может быть код символа или одно из значений \a SpecialKey.
|
||||||
int key;
|
int key;
|
||||||
|
|
||||||
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
|
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
|
||||||
|
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
|
||||||
KeyModifiers modifiers;
|
KeyModifiers modifiers;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Mouse buttons
|
//! \~english Mouse button bit flags.
|
||||||
|
//! \~russian Битовые флаги кнопок мыши.
|
||||||
enum MouseButton {
|
enum MouseButton {
|
||||||
MouseLeft /** Left button */ = 0x01,
|
MouseLeft = 0x01 /** \~english Left button \~russian Левая кнопка */,
|
||||||
MouseRight /** Right button */ = 0x02,
|
MouseRight = 0x02 /** \~english Right button \~russian Правая кнопка */,
|
||||||
MouseMiddle /** Middle button */ = 0x04
|
MouseMiddle = 0x04 /** \~english Middle button \~russian Средняя кнопка */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Mouse actions
|
//! \~english Mouse action kind.
|
||||||
|
//! \~russian Вид действия мыши.
|
||||||
enum MouseAction {
|
enum MouseAction {
|
||||||
MouseButtonPress /** Mouse button pressed */,
|
MouseButtonPress /** \~english Mouse button pressed \~russian Нажатие кнопки мыши */,
|
||||||
MouseButtonRelease /** Mouse button released */,
|
MouseButtonRelease /** \~english Mouse button released \~russian Отпускание кнопки мыши */,
|
||||||
MouseButtonDblClick /** Mouse button double click */,
|
MouseButtonDblClick /** \~english Mouse button double-click \~russian Двойной щелчок кнопкой мыши */,
|
||||||
MouseMove /** Mouse moved */,
|
MouseMove /** \~english Mouse moved \~russian Перемещение мыши */,
|
||||||
MouseWheel /** Mouse wheel rotated */
|
MouseWheel /** \~english Mouse wheel rotated \~russian Прокрутка колеса мыши */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Combination of pressed \a MouseButton flags.
|
||||||
|
//! \~russian Комбинация нажатых флагов \a MouseButton.
|
||||||
typedef PIFlags<MouseButton> MouseButtons;
|
typedef PIFlags<MouseButton> MouseButtons;
|
||||||
|
|
||||||
//! This struct contains information about mouse action
|
//! \~english Information about one mouse event.
|
||||||
|
//! \~russian Информация об одном событии мыши.
|
||||||
struct PIP_EXPORT MouseEvent {
|
struct PIP_EXPORT MouseEvent {
|
||||||
|
//! \~english Constructs an event with coordinates at the origin.
|
||||||
|
//! \~russian Создает событие с координатами в начале области.
|
||||||
MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {
|
MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {
|
||||||
x = y = 0;
|
x = y = 0;
|
||||||
action = a;
|
action = a;
|
||||||
@@ -125,107 +148,156 @@ public:
|
|||||||
modifiers = m;
|
modifiers = m;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Event X coordinate in view-space, from 0
|
//! \~english Event X coordinate in screen space, starting from zero.
|
||||||
|
//! \~russian Координата X события в экранном пространстве, начиная с нуля.
|
||||||
int x;
|
int x;
|
||||||
|
|
||||||
//! Event Y coordinate in view-space, from 0
|
//! \~english Event Y coordinate in screen space, starting from zero.
|
||||||
|
//! \~russian Координата Y события в экранном пространстве, начиная с нуля.
|
||||||
int y;
|
int y;
|
||||||
|
|
||||||
//! Mouse action type
|
//! \~english Mouse action kind.
|
||||||
|
//! \~russian Вид действия мыши.
|
||||||
MouseAction action;
|
MouseAction action;
|
||||||
|
|
||||||
//! Pressed buttons. It contains PIKbdListener::MouseButton bitfields
|
//! \~english Pressed mouse buttons as a combination of \a MouseButton flags.
|
||||||
|
//! \~russian Нажатые кнопки мыши как комбинация флагов \a MouseButton.
|
||||||
MouseButtons buttons;
|
MouseButtons buttons;
|
||||||
|
|
||||||
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
|
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
|
||||||
|
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
|
||||||
KeyModifiers modifiers;
|
KeyModifiers modifiers;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! This struct contains information about mouse wheel action
|
//! \~english Information about one mouse wheel event.
|
||||||
|
//! \~russian Информация об одном событии колеса мыши.
|
||||||
struct PIP_EXPORT WheelEvent: public MouseEvent {
|
struct PIP_EXPORT WheelEvent: public MouseEvent {
|
||||||
|
//! \~english Constructs a wheel event with downward direction by default.
|
||||||
|
//! \~russian Создает событие колеса мыши; по умолчанию направление вниз.
|
||||||
WheelEvent(): MouseEvent() { direction = false; }
|
WheelEvent(): MouseEvent() { direction = false; }
|
||||||
|
|
||||||
//! Wheel direction, /b true - up, /b fasle - down
|
//! \~english Wheel direction: \b true for up, \b false for down.
|
||||||
|
//! \~russian Направление прокрутки: \b true вверх, \b false вниз.
|
||||||
bool direction;
|
bool direction;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Callback receiving a key event and user data.
|
||||||
|
//! \~russian Обратный вызов, принимающий событие клавиши и пользовательские данные.
|
||||||
typedef std::function<void(KeyEvent, void *)> KBFunc;
|
typedef std::function<void(KeyEvent, void *)> KBFunc;
|
||||||
|
|
||||||
//! Constructs keyboard listener with external function "slot" and custom data "data"
|
//! \~english Constructs a listener with optional callback, user data, and auto-start mode.
|
||||||
|
//! \~russian Создает слушатель с необязательным обратным вызовом, пользовательскими данными и автозапуском.
|
||||||
explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true);
|
explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true);
|
||||||
|
|
||||||
|
//! \~english Stops the listener and restores the console state.
|
||||||
|
//! \~russian Останавливает слушатель и восстанавливает состояние консоли.
|
||||||
~PIKbdListener();
|
~PIKbdListener();
|
||||||
|
|
||||||
|
|
||||||
//! Returns custom data
|
//! \~english Returns the user data passed back with callbacks and events.
|
||||||
|
//! \~russian Возвращает пользовательские данные, передаваемые обратно в обратные вызовы и события.
|
||||||
void * data() { return kbddata_; }
|
void * data() { return kbddata_; }
|
||||||
|
|
||||||
//! Set custom data to "_data"
|
//! \~english Sets the user data passed back with callbacks and events.
|
||||||
|
//! \~russian Задает пользовательские данные, возвращаемые в обратных вызовах и событиях.
|
||||||
void setData(void * _data) { kbddata_ = _data; }
|
void setData(void * _data) { kbddata_ = _data; }
|
||||||
|
|
||||||
//! Set external function to "slot"
|
//! \~english Sets the callback receiving both key event and user data.
|
||||||
|
//! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные.
|
||||||
void setSlot(KBFunc slot) { ret_func = slot; }
|
void setSlot(KBFunc slot) { ret_func = slot; }
|
||||||
|
|
||||||
//! Set external function to "slot"
|
//! \~english Sets the callback that only receives the key event and ignores user data.
|
||||||
|
//! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные.
|
||||||
void setSlot(std::function<void(KeyEvent)> slot) {
|
void setSlot(std::function<void(KeyEvent)> slot) {
|
||||||
ret_func = [slot](KeyEvent e, void *) { slot(e); };
|
ret_func = [slot](KeyEvent e, void *) { slot(e); };
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns if exit key if awaiting
|
//! \~english Returns whether the exit key is currently being captured.
|
||||||
|
//! \~russian Возвращает, включен ли сейчас перехват клавиши выхода.
|
||||||
bool exitCaptured() const { return exit_enabled; }
|
bool exitCaptured() const { return exit_enabled; }
|
||||||
|
|
||||||
//! Returns exit key, default 'Q'
|
//! \~english Returns the configured exit key. The default is \c 'Q'.
|
||||||
|
//! \~russian Возвращает настроенную клавишу выхода. По умолчанию это \c 'Q'.
|
||||||
int exitKey() const { return exit_key; }
|
int exitKey() const { return exit_key; }
|
||||||
|
|
||||||
|
//! \~english Returns the double-click interval in milliseconds.
|
||||||
|
//! \~russian Возвращает интервал двойного щелчка в миллисекундах.
|
||||||
double doubleClickInterval() const { return dbl_interval; }
|
double doubleClickInterval() const { return dbl_interval; }
|
||||||
|
|
||||||
|
//! \~english Sets the mouse double-click interval in milliseconds.
|
||||||
|
//! \~russian Задает интервал двойного щелчка мыши в миллисекундах.
|
||||||
void setDoubleClickInterval(double v) { dbl_interval = v; }
|
void setDoubleClickInterval(double v) { dbl_interval = v; }
|
||||||
|
|
||||||
|
//! \~english Performs one low-level polling cycle and dispatches decoded input events.
|
||||||
|
//! \~russian Выполняет один цикл низкоуровневого опроса и отправляет декодированные события ввода.
|
||||||
void readKeyboard();
|
void readKeyboard();
|
||||||
|
|
||||||
|
//! \~english Requests listener shutdown and interrupts a pending wait for console input.
|
||||||
|
//! \~russian Запрашивает остановку слушателя и прерывает текущее ожидание консольного ввода.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
|
//! \~english Requests shutdown and waits until console capture is restored or the timeout expires.
|
||||||
|
//! \~russian Запрашивает остановку и ждет восстановления режима консоли до истечения таймаута.
|
||||||
bool stopAndWait(PISystemTime timeout = {});
|
bool stopAndWait(PISystemTime timeout = {});
|
||||||
|
|
||||||
//! Returns if keyboard listening is active (not running!)
|
//! \~english Returns whether low-level console capture is currently enabled.
|
||||||
|
//! \~russian Возвращает, включен ли сейчас низкоуровневый захват консольного ввода.
|
||||||
bool isActive() { return is_active; }
|
bool isActive() { return is_active; }
|
||||||
|
|
||||||
EVENT_HANDLER(void, enableExitCapture) { enableExitCapture('Q'); }
|
|
||||||
EVENT_HANDLER1(void, enableExitCapture, int, key) {
|
|
||||||
exit_enabled = true;
|
|
||||||
exit_key = key;
|
|
||||||
}
|
|
||||||
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
|
|
||||||
EVENT_HANDLER(void, setActive) { setActive(true); }
|
|
||||||
EVENT_HANDLER1(void, setActive, bool, yes);
|
|
||||||
|
|
||||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
|
||||||
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
|
|
||||||
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
|
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void enableExitCapture(int key = 'Q')
|
//! \fn void enableExitCapture(int key = 'Q')
|
||||||
//! \brief Enable exit key "key" awaiting
|
//! \~english Enables capture of exit key \a key.
|
||||||
|
//! \~russian Включает перехват клавиши выхода \a key.
|
||||||
|
EVENT_HANDLER(void, enableExitCapture) { enableExitCapture('Q'); }
|
||||||
|
EVENT_HANDLER1(void, enableExitCapture, int, key) {
|
||||||
|
exit_enabled = true;
|
||||||
|
exit_key = key;
|
||||||
|
}
|
||||||
|
|
||||||
//! \fn void disableExitCapture()
|
//! \fn void disableExitCapture()
|
||||||
//! \brief Disable exit key awaiting
|
//! \~english Disables exit key capture.
|
||||||
|
//! \~russian Выключает перехват клавиши выхода.
|
||||||
|
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
|
||||||
|
|
||||||
//! \fn void setActive(bool yes = true)
|
//! \fn void setActive(bool yes = true)
|
||||||
//! \brief Set keyboard listening is active or not
|
//! \~english Enables or disables low-level console input capture.
|
||||||
|
//! \~russian Включает или выключает низкоуровневый захват консольного ввода.
|
||||||
|
EVENT_HANDLER(void, setActive) { setActive(true); }
|
||||||
|
EVENT_HANDLER1(void, setActive, bool, yes);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
||||||
//! \brief Raise on key "key" pressed, "data" is custom data
|
//! \~english Raised when a key event is decoded. \a data is the user data pointer.
|
||||||
|
//! \~russian Вызывается, когда декодировано событие клавиши. \a data содержит указатель на пользовательские данные.
|
||||||
|
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||||
|
|
||||||
|
//! \fn void mouseEvent(PIKbdListener::MouseEvent mouse, void * data)
|
||||||
|
//! \~english Raised when a mouse button or move event is decoded. \a data is the user data pointer.
|
||||||
|
//! \~russian Вызывается, когда декодировано событие кнопки мыши или перемещения. \a data содержит указатель на пользовательские данные.
|
||||||
|
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
|
||||||
|
|
||||||
|
//! \fn void wheelEvent(PIKbdListener::WheelEvent wheel, void * data)
|
||||||
|
//! \~english Raised when a mouse wheel event is decoded. \a data is the user data pointer.
|
||||||
|
//! \~russian Вызывается, когда декодировано событие колеса мыши. \a data содержит указатель на пользовательские данные.
|
||||||
|
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
static bool exiting;
|
|
||||||
|
//! \~english Returns the listener instance currently registered by the console subsystem.
|
||||||
|
//! \~russian Возвращает экземпляр слушателя, который сейчас зарегистрирован консольной подсистемой.
|
||||||
static PIKbdListener * instance() { return _object; }
|
static PIKbdListener * instance() { return _object; }
|
||||||
|
|
||||||
|
//! \~english Becomes \b true after the configured exit key is captured.
|
||||||
|
//! \~russian Становится \b true после перехвата настроенной клавиши выхода.
|
||||||
|
static bool exiting;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
void begin() override;
|
void begin() override;
|
||||||
void run() override { readKeyboard(); }
|
void run() override { readKeyboard(); }
|
||||||
@@ -268,16 +340,16 @@ private:
|
|||||||
|
|
||||||
|
|
||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Store operator
|
//! \~english Store operator for MouseEvent.
|
||||||
//! \~russian Оператор сохранения
|
//! \~russian Оператор сохранения для MouseEvent.
|
||||||
BINARY_STREAM_WRITE(PIKbdListener::MouseEvent) {
|
BINARY_STREAM_WRITE(PIKbdListener::MouseEvent) {
|
||||||
s << v.x << v.y << v.action << v.buttons << v.modifiers;
|
s << v.x << v.y << v.action << v.buttons << v.modifiers;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Restore operator
|
//! \~english Restore operator for MouseEvent.
|
||||||
//! \~russian Оператор извлечения
|
//! \~russian Оператор извлечения для MouseEvent.
|
||||||
BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
|
BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
|
||||||
s >> v.x >> v.y >> v.action >> v.buttons >> v.modifiers;
|
s >> v.x >> v.y >> v.action >> v.buttons >> v.modifiers;
|
||||||
return s;
|
return s;
|
||||||
@@ -285,16 +357,16 @@ BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
|
|||||||
|
|
||||||
|
|
||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Store operator
|
//! \~english Store operator for WheelEvent.
|
||||||
//! \~russian Оператор сохранения
|
//! \~russian Оператор сохранения для WheelEvent.
|
||||||
BINARY_STREAM_WRITE(PIKbdListener::WheelEvent) {
|
BINARY_STREAM_WRITE(PIKbdListener::WheelEvent) {
|
||||||
s << (*(PIKbdListener::MouseEvent *)&v) << v.direction;
|
s << (*(PIKbdListener::MouseEvent *)&v) << v.direction;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Restore operator
|
//! \~english Restore operator for WheelEvent.
|
||||||
//! \~russian Оператор извлечения
|
//! \~russian Оператор извлечения для WheelEvent.
|
||||||
BINARY_STREAM_READ(PIKbdListener::WheelEvent) {
|
BINARY_STREAM_READ(PIKbdListener::WheelEvent) {
|
||||||
s >> (*(PIKbdListener::MouseEvent *)&v) >> v.direction;
|
s >> (*(PIKbdListener::MouseEvent *)&v) >> v.direction;
|
||||||
return s;
|
return s;
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piscreen.h
|
//! \~\file piscreen.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Console tiling manager
|
//! \~english Console screen manager and tile host
|
||||||
* \~russian Консольный тайловый менеджер
|
//! \~russian Менеджер консольного экрана и контейнер тайлов
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Console GUI
|
Console GUI
|
||||||
@@ -31,6 +30,10 @@
|
|||||||
#include "piscreentile.h"
|
#include "piscreentile.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Console screen manager with tile layout, drawing, and input routing.
|
||||||
|
//! \~russian Менеджер консольного экрана с раскладкой тайлов, отрисовкой и маршрутизацией ввода.
|
||||||
class PIP_CONSOLE_EXPORT PIScreen
|
class PIP_CONSOLE_EXPORT PIScreen
|
||||||
: public PIThread
|
: public PIThread
|
||||||
, public PIScreenTypes::PIScreenBase {
|
, public PIScreenTypes::PIScreenBase {
|
||||||
@@ -38,69 +41,122 @@ class PIP_CONSOLE_EXPORT PIScreen
|
|||||||
class SystemConsole;
|
class SystemConsole;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! Constructs %PIScreen with key handler "slot" and if "startNow" start it
|
//! \~english Constructs a screen with an internal keyboard listener, optional callback, and auto-start mode.
|
||||||
|
//! \~russian Создает экран со встроенным слушателем клавиатуры, необязательным обратным вызовом и режимом автозапуска.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Constructs a new PIScreen instance with optional immediate start.
|
||||||
|
//! \~russian Создает новый экземпляр PIScreen с опциональным немедленным запуском.
|
||||||
|
//! \~\param startNow
|
||||||
|
//! \~english Start immediately if true.
|
||||||
|
//! \~russian Запустить немедленно, если true.
|
||||||
|
//! \~\param slot
|
||||||
|
//! \~english Keyboard handler function.
|
||||||
|
//! \~russian Функция обработчика клавиатуры.
|
||||||
PIScreen(bool startNow = true, PIKbdListener::KBFunc slot = 0);
|
PIScreen(bool startNow = true, PIKbdListener::KBFunc slot = 0);
|
||||||
|
|
||||||
|
//! \~english Destroys PIScreen and cleans up resources.
|
||||||
|
//! \~russian Уничтожает PIScreen и очищает ресурсы.
|
||||||
~PIScreen();
|
~PIScreen();
|
||||||
|
|
||||||
//! Directly call function from \a PIKbdListener
|
//! \~english Enables catching the exit key (default is 'Q') to stop the screen.
|
||||||
|
//! \~russian Включает захват клавиши выхода (по умолчанию 'Q') для остановки экрана.
|
||||||
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
|
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
|
||||||
|
|
||||||
//! Directly call function from \a PIKbdListener
|
//! \~english Disables catching the exit key.
|
||||||
|
//! \~russian Отключает захват клавиши выхода.
|
||||||
void disableExitCapture() { listener->disableExitCapture(); }
|
void disableExitCapture() { listener->disableExitCapture(); }
|
||||||
|
|
||||||
//! Directly call function from \a PIKbdListener
|
//! \~english Returns whether exit key capture is enabled.
|
||||||
|
//! \~russian Возвращает, включен ли перехват клавиши выхода.
|
||||||
bool exitCaptured() const { return listener->exitCaptured(); }
|
bool exitCaptured() const { return listener->exitCaptured(); }
|
||||||
|
|
||||||
//! Directly call function from \a PIKbdListener
|
//! \~english Returns the configured exit key.
|
||||||
|
//! \~russian Возвращает настроенную клавишу выхода.
|
||||||
int exitKey() const { return listener->exitKey(); }
|
int exitKey() const { return listener->exitKey(); }
|
||||||
|
|
||||||
|
//! \~english Returns the current console width in characters.
|
||||||
|
//! \~russian Возвращает текущую ширину консоли в символах.
|
||||||
int windowWidth() const { return console.width; }
|
int windowWidth() const { return console.width; }
|
||||||
|
|
||||||
|
//! \~english Returns the current console height in characters.
|
||||||
|
//! \~russian Возвращает текущую высоту консоли в символах.
|
||||||
int windowHeight() const { return console.height; }
|
int windowHeight() const { return console.height; }
|
||||||
|
|
||||||
|
//! \~english Returns whether mouse hit-testing and routing are enabled.
|
||||||
|
//! \~russian Возвращает, включены ли проверка попадания и маршрутизация событий мыши.
|
||||||
bool isMouseEnabled() const { return mouse_; }
|
bool isMouseEnabled() const { return mouse_; }
|
||||||
|
|
||||||
|
//! \~english Enables or disables mouse routing and tile hit-testing.
|
||||||
|
//! \~russian Включает или выключает маршрутизацию мыши и проверку попадания по тайлам.
|
||||||
void setMouseEnabled(bool on);
|
void setMouseEnabled(bool on);
|
||||||
|
|
||||||
|
//! \~english Returns the root tile covering the whole screen.
|
||||||
|
//! \~russian Возвращает корневой тайл, покрывающий весь экран.
|
||||||
PIScreenTile * rootTile() { return &root; }
|
PIScreenTile * rootTile() { return &root; }
|
||||||
|
|
||||||
|
//! \~english Searches the root tile subtree by object name.
|
||||||
|
//! \~russian Ищет тайл по имени объекта в поддереве корневого тайла.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Tile pointer if found, otherwise nullptr.
|
||||||
|
//! \~russian Указатель на тайл, если найден, иначе nullptr.
|
||||||
PIScreenTile * tileByName(const PIString & name);
|
PIScreenTile * tileByName(const PIString & name);
|
||||||
|
|
||||||
|
//! \~english Sets a dialog tile drawn above the root tree, centered on screen, and focused first. Pass \c nullptr to remove it.
|
||||||
|
//! \~russian Задает диалоговый тайл, рисуемый поверх корневого дерева, центрируемый на экране и первым получающий фокус. Передайте \c
|
||||||
|
//! nullptr, чтобы убрать его.
|
||||||
void setDialogTile(PIScreenTile * t);
|
void setDialogTile(PIScreenTile * t);
|
||||||
|
|
||||||
|
//! \~english Returns the currently active dialog tile or \c nullptr.
|
||||||
|
//! \~russian Возвращает активный диалоговый тайл или \c nullptr.
|
||||||
PIScreenTile * dialogTile() const { return tile_dialog; }
|
PIScreenTile * dialogTile() const { return tile_dialog; }
|
||||||
|
|
||||||
|
//! \~english Returns the drawer used to fill the off-screen cell buffer for the next frame.
|
||||||
|
//! \~russian Возвращает рисовальщик, используемый для заполнения внеэкранного буфера ячеек следующего кадра.
|
||||||
PIScreenDrawer * drawer() { return &drawer_; }
|
PIScreenDrawer * drawer() { return &drawer_; }
|
||||||
|
|
||||||
|
//! \~english Clears the off-screen cell buffer. The terminal is updated on the next draw cycle.
|
||||||
|
//! \~russian Очищает внеэкранный буфер ячеек. Терминал обновится на следующем цикле отрисовки.
|
||||||
void clear() { drawer_.clear(); }
|
void clear() { drawer_.clear(); }
|
||||||
|
|
||||||
|
//! \~english Resizes the internal console buffers used for subsequent frames.
|
||||||
|
//! \~russian Изменяет размер внутренних консольных буферов, используемых в следующих кадрах.
|
||||||
void resize(int w, int h) { console.resize(w, h); }
|
void resize(int w, int h) { console.resize(w, h); }
|
||||||
|
|
||||||
EVENT_HANDLER0(void, waitForFinish);
|
|
||||||
EVENT_HANDLER0(void, start) { start(false); }
|
|
||||||
EVENT_HANDLER1(void, start, bool, wait);
|
|
||||||
EVENT_HANDLER0(void, stop) { stop(false); }
|
|
||||||
EVENT_HANDLER1(void, stop, bool, clear);
|
|
||||||
|
|
||||||
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
|
||||||
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
|
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void waitForFinish()
|
//! \fn void waitForFinish()
|
||||||
//! \brief block until finished (exit key will be pressed)
|
//! \~english Blocks until the captured exit key is pressed and then stops the screen.
|
||||||
|
//! \~russian Блокирует выполнение, пока не будет нажата перехватываемая клавиша выхода, затем останавливает экран.
|
||||||
|
EVENT_HANDLER0(void, waitForFinish);
|
||||||
|
|
||||||
//! \fn void start(bool wait = false)
|
//! \fn void start(bool wait = false)
|
||||||
//! \brief Start console output and if "wait" block until finished (exit key will be pressed)
|
//! \~english Starts the screen thread and optionally waits until the configured exit key is captured.
|
||||||
|
//! \~russian Запускает поток экрана и при необходимости ждет, пока не будет перехвачена настроенная клавиша выхода.
|
||||||
|
EVENT_HANDLER0(void, start) { start(false); }
|
||||||
|
EVENT_HANDLER1(void, start, bool, wait);
|
||||||
|
|
||||||
//! \fn void stop(bool clear = false)
|
//! \fn void stop(bool clear = false)
|
||||||
//! \brief Stop console output and if "clear" clear the screen
|
//! \~english Stops the screen thread, restores console state, and optionally clears the terminal.
|
||||||
|
//! \~russian Останавливает поток экрана, восстанавливает состояние консоли и при необходимости очищает терминал.
|
||||||
|
EVENT_HANDLER0(void, stop) { stop(false); }
|
||||||
|
EVENT_HANDLER1(void, stop, bool, clear);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
|
||||||
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
|
//! \~english Raised when a key was not consumed by focus navigation or the focused tile. \a data is the screen user data pointer.
|
||||||
|
//! \~russian Вызывается, когда клавиша не была поглощена навигацией фокуса или тайлом с фокусом. \a data содержит пользовательский
|
||||||
|
//! указатель экрана.
|
||||||
|
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
|
||||||
|
|
||||||
//! \fn void tileEvent(PIScreenTile * tile, PIScreenTypes::TileEvent e)
|
//! \fn void tileEvent(PIScreenTile * tile, PIScreenTypes::TileEvent e)
|
||||||
//! \brief Raise on some event "e" from tile "tile"
|
//! \~english Raised when a tile reports a custom event \a e.
|
||||||
|
//! \~russian Вызывается, когда тайл сообщает пользовательское событие \a e.
|
||||||
|
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
|
|||||||
@@ -1,82 +0,0 @@
|
|||||||
/*! \file piscreenconsole.h
|
|
||||||
* \ingroup Console
|
|
||||||
* \~\brief
|
|
||||||
* \~english Tile for PIScreen with PIConsole API
|
|
||||||
* \~russian Тайл для PIScreen с API PIConsole
|
|
||||||
*/
|
|
||||||
/*
|
|
||||||
PIP - Platform Independent Primitives
|
|
||||||
Tile for PIScreen with PIConsole API
|
|
||||||
Andrey Bychkov work.a.b@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 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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef PISCREENCONSOLE_H
|
|
||||||
#define PISCREENCONSOLE_H
|
|
||||||
|
|
||||||
#include "pip_console_export.h"
|
|
||||||
#include "piscreentiles.h"
|
|
||||||
|
|
||||||
/// NOTE: incomplete class
|
|
||||||
/// TODO: write TileVars
|
|
||||||
|
|
||||||
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
|
|
||||||
public:
|
|
||||||
TileVars(const PIString & n = PIString());
|
|
||||||
|
|
||||||
protected:
|
|
||||||
struct PIP_CONSOLE_EXPORT Variable {
|
|
||||||
Variable() {
|
|
||||||
nx = ny = type = offset = bitFrom = bitCount = size = 0;
|
|
||||||
format = PIScreenTypes::CellFormat();
|
|
||||||
ptr = 0;
|
|
||||||
}
|
|
||||||
bool isEmpty() const { return (ptr == 0); }
|
|
||||||
PIString name;
|
|
||||||
PIScreenTypes::CellFormat format;
|
|
||||||
int nx;
|
|
||||||
int ny;
|
|
||||||
int type;
|
|
||||||
int offset;
|
|
||||||
int bitFrom;
|
|
||||||
int bitCount;
|
|
||||||
int size;
|
|
||||||
const void * ptr;
|
|
||||||
/*void operator =(const Variable & src) {
|
|
||||||
name = src.name;
|
|
||||||
format = src.format;
|
|
||||||
nx = src.nx;
|
|
||||||
ny = src.ny;
|
|
||||||
type = src.type;
|
|
||||||
offset = src.offset;
|
|
||||||
bitFrom = src.bitFrom;
|
|
||||||
bitCount = src.bitCount;
|
|
||||||
size = src.size;
|
|
||||||
ptr = src.ptr;
|
|
||||||
}*/
|
|
||||||
};
|
|
||||||
PIVector<Variable> variables;
|
|
||||||
PIScreenTypes::Alignment alignment;
|
|
||||||
void sizeHint(int & w, int & h) const override;
|
|
||||||
void drawEvent(PIScreenDrawer * d) override;
|
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
|
|
||||||
public:
|
|
||||||
PIScreenConsoleTile();
|
|
||||||
};
|
|
||||||
|
|
||||||
#endif // PISCREENCONSOLE_H
|
|
||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piscreendrawer.h
|
//! \~\file piscreendrawer.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Drawer for PIScreen
|
//! \~english Drawing helpers for %PIScreen cell buffers
|
||||||
* \~russian Отрисовщик для PIScreen
|
//! \~russian Вспомогательные средства рисования для буферов ячеек %PIScreen
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Drawer for PIScreen
|
Drawer for PIScreen
|
||||||
@@ -30,31 +29,54 @@
|
|||||||
#include "piscreentypes.h"
|
#include "piscreentypes.h"
|
||||||
#include "pistring.h"
|
#include "pistring.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Helper that draws primitives and text into a %PIScreen cell buffer.
|
||||||
|
//! \~russian Вспомогательный класс для рисования примитивов и текста в буфере ячеек %PIScreen.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Provides methods for drawing primitives such as pixels, lines, rectangles, and text on console screen.
|
||||||
|
//! \~russian Предоставляет методы для рисования примитивов, таких как пиксели, линии, прямоугольники и текст на консольном экране.
|
||||||
class PIP_CONSOLE_EXPORT PIScreenDrawer {
|
class PIP_CONSOLE_EXPORT PIScreenDrawer {
|
||||||
friend class PIScreen;
|
friend class PIScreen;
|
||||||
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
|
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Predefined pseudographic and widget-state symbols.
|
||||||
|
//! \~russian Предопределенные псевдографические символы и символы состояний виджетов.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Defines available characters for drawing ASCII art primitives.
|
||||||
|
//! \~russian Определяет доступные символы для рисования ASCII-арта примитивов.
|
||||||
enum ArtChar {
|
enum ArtChar {
|
||||||
LineVertical = 1,
|
LineVertical = 1 /** \~english Vertical line symbol. \~russian Символ вертикальной линии. */,
|
||||||
LineHorizontal,
|
LineHorizontal /** \~english Horizontal line symbol. \~russian Символ горизонтальной линии. */,
|
||||||
Cross,
|
Cross /** \~english Line intersection symbol. \~russian Символ пересечения линий. */,
|
||||||
CornerTopLeft,
|
CornerTopLeft /** \~english Top-left frame corner. \~russian Левый верхний угол рамки. */,
|
||||||
CornerTopRight,
|
CornerTopRight /** \~english Top-right frame corner. \~russian Правый верхний угол рамки. */,
|
||||||
CornerBottomLeft,
|
CornerBottomLeft /** \~english Bottom-left frame corner. \~russian Левый нижний угол рамки. */,
|
||||||
CornerBottomRight,
|
CornerBottomRight /** \~english Bottom-right frame corner. \~russian Правый нижний угол рамки. */,
|
||||||
Unchecked,
|
Unchecked /** \~english Unchecked box symbol. \~russian Символ неотмеченного флажка. */,
|
||||||
Checked
|
Checked /** \~english Checked box symbol. \~russian Символ отмеченного флажка. */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Clears the whole target buffer.
|
||||||
|
//! \~russian Очищает весь целевой буфер.
|
||||||
void clear();
|
void clear();
|
||||||
|
|
||||||
|
//! \~english Clears a rectangular area in the target buffer with spaces.
|
||||||
|
//! \~russian Очищает прямоугольную область целевого буфера пробелами.
|
||||||
void clearRect(int x0, int y0, int x1, int y1) { fillRect(x0, y0, x1, y1, ' '); }
|
void clearRect(int x0, int y0, int x1, int y1) { fillRect(x0, y0, x1, y1, ' '); }
|
||||||
|
|
||||||
|
//! \~english Draws one cell at position `(x, y)`.
|
||||||
|
//! \~russian Рисует одну ячейку в позиции `(x, y)`.
|
||||||
void drawPixel(int x,
|
void drawPixel(int x,
|
||||||
int y,
|
int y,
|
||||||
const PIChar & c,
|
const PIChar & c,
|
||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Draws a line between two points.
|
||||||
|
//! \~russian Рисует линию между двумя точками.
|
||||||
void drawLine(int x0,
|
void drawLine(int x0,
|
||||||
int y0,
|
int y0,
|
||||||
int x1,
|
int x1,
|
||||||
@@ -63,6 +85,9 @@ public:
|
|||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Draws a rectangular outline with the specified symbol.
|
||||||
|
//! \~russian Рисует контур прямоугольника указанным символом.
|
||||||
void drawRect(int x0,
|
void drawRect(int x0,
|
||||||
int y0,
|
int y0,
|
||||||
int x1,
|
int x1,
|
||||||
@@ -71,6 +96,9 @@ public:
|
|||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Draws a frame using predefined art symbols.
|
||||||
|
//! \~russian Рисует рамку предопределенными псевдографическими символами.
|
||||||
void drawFrame(int x0,
|
void drawFrame(int x0,
|
||||||
int y0,
|
int y0,
|
||||||
int x1,
|
int x1,
|
||||||
@@ -78,12 +106,18 @@ public:
|
|||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Draws text starting at `(x, y)`.
|
||||||
|
//! \~russian Рисует текст, начиная с позиции `(x, y)`.
|
||||||
void drawText(int x,
|
void drawText(int x,
|
||||||
int y,
|
int y,
|
||||||
const PIString & s,
|
const PIString & s,
|
||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Transparent,
|
PIScreenTypes::Color col_back = PIScreenTypes::Transparent,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Fills a rectangular area with one symbol and cell format.
|
||||||
|
//! \~russian Заполняет прямоугольную область одним символом и форматом ячейки.
|
||||||
void fillRect(int x0,
|
void fillRect(int x0,
|
||||||
int y0,
|
int y0,
|
||||||
int x1,
|
int x1,
|
||||||
@@ -92,10 +126,17 @@ public:
|
|||||||
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
PIScreenTypes::Color col_char = PIScreenTypes::Default,
|
||||||
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
PIScreenTypes::Color col_back = PIScreenTypes::Default,
|
||||||
PIScreenTypes::CharFlags flags_char = 0);
|
PIScreenTypes::CharFlags flags_char = 0);
|
||||||
|
|
||||||
|
//! \~english Copies a cell matrix into a rectangular area.
|
||||||
|
//! \~russian Копирует матрицу ячеек в прямоугольную область.
|
||||||
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell>> & content);
|
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell>> & content);
|
||||||
|
|
||||||
|
//! \~english Returns a predefined art symbol.
|
||||||
|
//! \~russian Возвращает предопределенный псевдографический символ.
|
||||||
PIChar artChar(const ArtChar type) const { return arts_.value(type, PIChar(' ')); }
|
PIChar artChar(const ArtChar type) const { return arts_.value(type, PIChar(' ')); }
|
||||||
|
|
||||||
|
//! \~english Fills an arbitrary cell buffer with default cells.
|
||||||
|
//! \~russian Заполняет произвольный буфер ячеек значениями по умолчанию.
|
||||||
static void clear(PIVector<PIVector<PIScreenTypes::Cell>> & cells);
|
static void clear(PIVector<PIVector<PIScreenTypes::Cell>> & cells);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piscreentile.h
|
//! \~\file piscreentile.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Basic PIScreen tile
|
//! \~english Basic PIScreen tile
|
||||||
* \~russian Базовый тайл для PIScreen
|
//! \~russian Базовый тайл для PIScreen
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Basic PIScreen tile
|
Basic PIScreen tile
|
||||||
@@ -32,27 +31,74 @@
|
|||||||
|
|
||||||
class PIScreenDrawer;
|
class PIScreenDrawer;
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Base tile in the console screen tree.
|
||||||
|
//! \~russian Базовый тайл в дереве консольного экрана.
|
||||||
|
//! \details
|
||||||
|
//! \~english Base class for all screen tiles providing layout and event handling.
|
||||||
|
//! \~russian Базовый класс для всех экранных тайлов, обеспечивающий компоновку и обработку событий.
|
||||||
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
|
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
|
||||||
friend class PIScreen;
|
friend class PIScreen;
|
||||||
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
|
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a tile with name, child layout direction, and size policy.
|
||||||
|
//! \~russian Создает тайл с именем, направлением раскладки дочерних элементов и политикой размера.
|
||||||
PIScreenTile(const PIString & n = PIString(),
|
PIScreenTile(const PIString & n = PIString(),
|
||||||
PIScreenTypes::Direction d = PIScreenTypes::Vertical,
|
PIScreenTypes::Direction d = PIScreenTypes::Vertical,
|
||||||
PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
|
PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
|
||||||
|
|
||||||
|
//! \~english Destroys the tile and its owned child tiles.
|
||||||
|
//! \~russian Уничтожает тайл и принадлежащие ему дочерние тайлы.
|
||||||
virtual ~PIScreenTile();
|
virtual ~PIScreenTile();
|
||||||
|
|
||||||
|
//! \~english Adds child tile \a t, makes this tile its parent, and attaches the subtree to the same screen bridge.
|
||||||
|
//! \~russian Добавляет дочерний тайл \a t, делает этот тайл его родителем и подключает поддерево к тому же экранному мосту.
|
||||||
void addTile(PIScreenTile * t);
|
void addTile(PIScreenTile * t);
|
||||||
|
|
||||||
|
//! \~english Detaches child tile \a t without deleting it and removes its screen association.
|
||||||
|
//! \~russian Отсоединяет дочерний тайл \a t без удаления и снимает его связь с экраном.
|
||||||
void takeTile(PIScreenTile * t);
|
void takeTile(PIScreenTile * t);
|
||||||
|
|
||||||
|
//! \~english Removes and deletes child tile \a t.
|
||||||
|
//! \~russian Удаляет дочерний тайл \a t и уничтожает его.
|
||||||
void removeTile(PIScreenTile * t);
|
void removeTile(PIScreenTile * t);
|
||||||
|
|
||||||
|
//! \~english Returns the parent tile or \c nullptr for the root.
|
||||||
|
//! \~russian Возвращает родительский тайл или \c nullptr для корня.
|
||||||
PIScreenTile * parentTile() const { return parent; }
|
PIScreenTile * parentTile() const { return parent; }
|
||||||
|
|
||||||
|
//! \~english Returns all descendant tiles. Hidden tiles can be skipped with \a only_visible.
|
||||||
|
//! \~russian Возвращает все дочерние тайлы по дереву. Скрытые тайлы можно пропустить через \a only_visible.
|
||||||
PIVector<PIScreenTile *> children(bool only_visible = false);
|
PIVector<PIScreenTile *> children(bool only_visible = false);
|
||||||
|
|
||||||
|
//! \~english Returns the first visible direct child covering screen point \a x, \a y.
|
||||||
|
//! \~russian Возвращает первый видимый прямой дочерний тайл, покрывающий экранную точку \a x, \a y.
|
||||||
PIScreenTile * childUnderMouse(int x, int y);
|
PIScreenTile * childUnderMouse(int x, int y);
|
||||||
|
|
||||||
|
//! \~english Makes the tile visible for subsequent layout, hit-testing, and drawing passes.
|
||||||
|
//! \~russian Делает тайл видимым для последующих проходов компоновки, проверки попадания и отрисовки.
|
||||||
void show() { visible = true; }
|
void show() { visible = true; }
|
||||||
|
|
||||||
|
//! \~english Hides the tile from layout, hit-testing, and drawing passes.
|
||||||
|
//! \~russian Скрывает тайл из проходов компоновки, проверки попадания и отрисовки.
|
||||||
void hide() { visible = false; }
|
void hide() { visible = false; }
|
||||||
|
|
||||||
|
//! \~english Requests focus for this tile if it is attached to a screen and allows focus.
|
||||||
|
//! \~russian Запрашивает фокус для этого тайла, если он подключен к экрану и допускает получение фокуса.
|
||||||
void setFocus();
|
void setFocus();
|
||||||
|
|
||||||
|
//! \~english Returns whether this tile currently owns focus.
|
||||||
|
//! \~russian Возвращает, принадлежит ли этому тайлу текущий фокус.
|
||||||
bool hasFocus() const { return has_focus; }
|
bool hasFocus() const { return has_focus; }
|
||||||
|
|
||||||
|
//! \~english Sets all margins to \a m cells.
|
||||||
|
//! \~russian Устанавливает все отступы в \a m ячеек.
|
||||||
void setMargins(int m) { marginLeft = marginRight = marginTop = marginBottom = m; }
|
void setMargins(int m) { marginLeft = marginRight = marginTop = marginBottom = m; }
|
||||||
|
|
||||||
|
//! \~english Sets left, right, top, and bottom margins in cells.
|
||||||
|
//! \~russian Устанавливает левый, правый, верхний и нижний отступы в ячейках.
|
||||||
void setMargins(int l, int r, int t, int b) {
|
void setMargins(int l, int r, int t, int b) {
|
||||||
marginLeft = l;
|
marginLeft = l;
|
||||||
marginRight = r;
|
marginRight = r;
|
||||||
@@ -60,52 +106,129 @@ public:
|
|||||||
marginBottom = b;
|
marginBottom = b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns the tile X coordinate in screen space.
|
||||||
|
//! \~russian Возвращает координату X тайла в экранном пространстве.
|
||||||
int x() const { return x_; }
|
int x() const { return x_; }
|
||||||
|
|
||||||
|
//! \~english Returns the tile Y coordinate in screen space.
|
||||||
|
//! \~russian Возвращает координату Y тайла в экранном пространстве.
|
||||||
int y() const { return y_; }
|
int y() const { return y_; }
|
||||||
|
|
||||||
|
//! \~english Returns the current tile width in cells.
|
||||||
|
//! \~russian Возвращает текущую ширину тайла в ячейках.
|
||||||
int width() const { return width_; }
|
int width() const { return width_; }
|
||||||
|
|
||||||
|
//! \~english Returns the current tile height in cells.
|
||||||
|
//! \~russian Возвращает текущую высоту тайла в ячейках.
|
||||||
int height() const { return height_; }
|
int height() const { return height_; }
|
||||||
|
|
||||||
|
//! \~english Direction used to lay out child tiles.
|
||||||
|
//! \~russian Направление раскладки дочерних тайлов.
|
||||||
PIScreenTypes::Direction direction;
|
PIScreenTypes::Direction direction;
|
||||||
|
|
||||||
|
//! \~english Size policy used by the parent during layout.
|
||||||
|
//! \~russian Политика размера, используемая родителем при компоновке.
|
||||||
PIScreenTypes::SizePolicy size_policy;
|
PIScreenTypes::SizePolicy size_policy;
|
||||||
|
|
||||||
|
//! \~english Focus and navigation flags for the tile.
|
||||||
|
//! \~russian Флаги фокуса и навигации для тайла.
|
||||||
PIScreenTypes::FocusFlags focus_flags;
|
PIScreenTypes::FocusFlags focus_flags;
|
||||||
|
|
||||||
|
//! \~english Background format used to prefill the tile area before drawing.
|
||||||
|
//! \~russian Формат фона, которым предварительно заполняется область тайла перед отрисовкой.
|
||||||
PIScreenTypes::CellFormat back_format;
|
PIScreenTypes::CellFormat back_format;
|
||||||
|
|
||||||
|
//! \~english Background symbol used to prefill the tile area before drawing.
|
||||||
|
//! \~russian Символ фона, которым предварительно заполняется область тайла перед отрисовкой.
|
||||||
PIChar back_symbol;
|
PIChar back_symbol;
|
||||||
|
|
||||||
|
//! \~english Minimum size limits accepted during layout.
|
||||||
|
//! \~russian Минимальные ограничения размера, допускаемые при компоновке.
|
||||||
int minimumWidth, minimumHeight;
|
int minimumWidth, minimumHeight;
|
||||||
|
|
||||||
|
//! \~english Maximum size limits accepted during layout.
|
||||||
|
//! \~russian Максимальные ограничения размера, допускаемые при компоновке.
|
||||||
int maximumWidth, maximumHeight;
|
int maximumWidth, maximumHeight;
|
||||||
|
|
||||||
|
//! \~english Outer margins in cells.
|
||||||
|
//! \~russian Внешние отступы в ячейках.
|
||||||
int marginLeft, marginRight, marginTop, marginBottom;
|
int marginLeft, marginRight, marginTop, marginBottom;
|
||||||
|
|
||||||
|
//! \~english Spacing between visible child tiles in cells.
|
||||||
|
//! \~russian Интервал между видимыми дочерними тайлами в ячейках.
|
||||||
int spacing;
|
int spacing;
|
||||||
|
|
||||||
|
//! \~english Whether the tile participates in layout, hit-testing, and drawing.
|
||||||
|
//! \~russian Участвует ли тайл в компоновке, проверке попадания и отрисовке.
|
||||||
bool visible;
|
bool visible;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//! Returns desired tile size in "w" and "h"
|
//! \~english Returns the preferred tile size in \a w and \a h. The base implementation derives it from visible children, spacing, and margins.
|
||||||
|
//! \~russian Возвращает предпочтительный размер тайла в \a w и \a h. Базовая реализация вычисляет его по видимым дочерним тайлам, интервалам и отступам.
|
||||||
virtual void sizeHint(int & w, int & h) const;
|
virtual void sizeHint(int & w, int & h) const;
|
||||||
|
|
||||||
//! Tile has been resized to "w"x"h"
|
//! \~english Called after the tile size changes to \a w by \a h during layout.
|
||||||
|
//! \~russian Вызывается после изменения размера тайла до \a w на \a h во время компоновки.
|
||||||
virtual void resizeEvent(int w, int h) {}
|
virtual void resizeEvent(int w, int h) {}
|
||||||
|
|
||||||
//! Draw tile with drawer "d" in world-space coordinates
|
//! \~english Draws the tile with drawer \a d in screen coordinates.
|
||||||
|
//! \~russian Отрисовывает тайл через рисовальщик \a d в экранных координатах.
|
||||||
virtual void drawEvent(PIScreenDrawer * d) {}
|
virtual void drawEvent(PIScreenDrawer * d) {}
|
||||||
|
|
||||||
//! Return "true" if you process key
|
//! \~english Handles keyboard input and returns \b true when the event is consumed.
|
||||||
|
//! \~russian Обрабатывает клавиатурный ввод и возвращает \b true, если событие поглощено.
|
||||||
virtual bool keyEvent(PIKbdListener::KeyEvent key) { return false; }
|
virtual bool keyEvent(PIKbdListener::KeyEvent key) { return false; }
|
||||||
|
|
||||||
//! Return "true" if you process event
|
//! \~english Handles mouse input and returns \b true when the event is consumed.
|
||||||
|
//! \~russian Обрабатывает событие мыши и возвращает \b true, если событие поглощено.
|
||||||
virtual bool mouseEvent(PIKbdListener::MouseEvent me) { return false; }
|
virtual bool mouseEvent(PIKbdListener::MouseEvent me) { return false; }
|
||||||
|
|
||||||
//! Return "true" if you process wheel
|
//! \~english Handles mouse wheel input and returns \b true when the event is consumed.
|
||||||
|
//! \~russian Обрабатывает колесо мыши и возвращает \b true, если событие поглощено.
|
||||||
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
|
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
|
||||||
|
|
||||||
|
//! \~english Raises tile event
|
||||||
|
//! \~russian Вызывает событие тайла
|
||||||
void raiseEvent(PIScreenTypes::TileEvent e);
|
void raiseEvent(PIScreenTypes::TileEvent e);
|
||||||
|
|
||||||
|
//! \~english Sets screen reference
|
||||||
|
//! \~russian Устанавливает ссылку на экран
|
||||||
void setScreen(PIScreenTypes::PIScreenBase * s);
|
void setScreen(PIScreenTypes::PIScreenBase * s);
|
||||||
|
|
||||||
|
//! \~english Deletes all owned child tiles.
|
||||||
|
//! \~russian Удаляет все принадлежащие дочерние тайлы.
|
||||||
void deleteChildren();
|
void deleteChildren();
|
||||||
|
|
||||||
|
//! \~english Draws background, tile contents, and then child tiles.
|
||||||
|
//! \~russian Отрисовывает фон, содержимое тайла и затем дочерние тайлы.
|
||||||
void drawEventInternal(PIScreenDrawer * d);
|
void drawEventInternal(PIScreenDrawer * d);
|
||||||
|
|
||||||
|
//! \~english Recomputes child geometry according to size hints, margins, and policies.
|
||||||
|
//! \~russian Пересчитывает геометрию дочерних тайлов по предпочтительным размерам, отступам и политикам.
|
||||||
void layout();
|
void layout();
|
||||||
|
|
||||||
|
//! \~english Returns whether this tile should participate in automatic layout. Tiles with policy \a PIScreenTypes::Ignore are skipped.
|
||||||
|
//! \~russian Возвращает, должен ли тайл участвовать в автоматической компоновке. Тайлы с политикой \a PIScreenTypes::Ignore пропускаются.
|
||||||
bool needLayout() { return size_policy != PIScreenTypes::Ignore; }
|
bool needLayout() { return size_policy != PIScreenTypes::Ignore; }
|
||||||
|
|
||||||
|
//! \~english Owned direct child tiles.
|
||||||
|
//! \~russian Принадлежащие прямые дочерние тайлы.
|
||||||
PIVector<PIScreenTile *> tiles;
|
PIVector<PIScreenTile *> tiles;
|
||||||
|
|
||||||
|
//! \~english Parent tile or \c nullptr for the root or detached tiles.
|
||||||
|
//! \~russian Родительский тайл или \c nullptr для корня и отсоединенных тайлов.
|
||||||
PIScreenTile * parent;
|
PIScreenTile * parent;
|
||||||
|
|
||||||
|
//! \~english Screen pointer, receiving tile notifications.
|
||||||
|
//! \~russian Ссылка на экран, принимающий уведомления от тайла.
|
||||||
PIScreenTypes::PIScreenBase * screen;
|
PIScreenTypes::PIScreenBase * screen;
|
||||||
|
|
||||||
|
//! \~english Tile position and size in screen cells.
|
||||||
|
//! \~russian Положение и размер тайла в экранных ячейках.
|
||||||
int x_, y_, width_, height_;
|
int x_, y_, width_, height_;
|
||||||
|
|
||||||
|
//! \~english Whether this tile currently owns focus.
|
||||||
|
//! \~russian Принадлежит ли этому тайлу текущий фокус.
|
||||||
bool has_focus;
|
bool has_focus;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
/*! \file piscreentiles.h
|
//! \~\file piscreentiles.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Various tiles for PIScreen
|
//! \~english Various tiles for PIScreen
|
||||||
* \~russian Различные тайлы для PIScreen
|
//! \~russian Различные тайлы для PIScreen
|
||||||
*/
|
//! \details
|
||||||
|
//! \~english Provides ready-to-use tile implementations for common UI elements.
|
||||||
|
//! \~russian Обеспечивает готовые к использованию реализации тайлов для общих элементов UI.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Various tiles for PIScreen
|
Various tiles for PIScreen
|
||||||
@@ -30,15 +32,36 @@
|
|||||||
#include "piscreentile.h"
|
#include "piscreentile.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Simple text tile with per-row formatting.
|
||||||
|
//! \~russian Простой текстовый тайл с форматированием по строкам.
|
||||||
class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Row text with cell format.
|
||||||
|
//! \~russian Текст строки с форматом ячеек.
|
||||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
||||||
|
|
||||||
|
//! \~english Constructs an empty text tile.
|
||||||
|
//! \~russian Создает пустой текстовый тайл.
|
||||||
TileSimple(const PIString & n = PIString());
|
TileSimple(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Constructs a text tile with one row.
|
||||||
|
//! \~russian Создает текстовый тайл с одной строкой.
|
||||||
TileSimple(const Row & r);
|
TileSimple(const Row & r);
|
||||||
|
|
||||||
|
//! \~english Destroys the text tile.
|
||||||
|
//! \~russian Уничтожает текстовый тайл.
|
||||||
virtual ~TileSimple() {}
|
virtual ~TileSimple() {}
|
||||||
|
|
||||||
|
//! \~english Rows displayed by the tile.
|
||||||
|
//! \~russian Строки, отображаемые тайлом.
|
||||||
PIVector<Row> content;
|
PIVector<Row> content;
|
||||||
|
|
||||||
|
//! \~english Horizontal text alignment inside the tile.
|
||||||
|
//! \~russian Горизонтальное выравнивание текста внутри тайла.
|
||||||
PIScreenTypes::Alignment alignment;
|
PIScreenTypes::Alignment alignment;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -49,19 +72,49 @@ protected:
|
|||||||
|
|
||||||
class TileList;
|
class TileList;
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Scroll bar tile used by list-like widgets.
|
||||||
|
//! \~russian Тайловая полоса прокрутки для списковых виджетов.
|
||||||
class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile);
|
||||||
friend class TileList;
|
friend class TileList;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a scroll bar tile.
|
||||||
|
//! \~russian Создает тайл полосы прокрутки.
|
||||||
TileScrollBar(const PIString & n = PIString());
|
TileScrollBar(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the scroll bar tile.
|
||||||
|
//! \~russian Уничтожает тайл полосы прокрутки.
|
||||||
virtual ~TileScrollBar() {}
|
virtual ~TileScrollBar() {}
|
||||||
|
|
||||||
|
//! \~english Sets the minimum scroll value.
|
||||||
|
//! \~russian Устанавливает минимальное значение прокрутки.
|
||||||
void setMinimum(int v);
|
void setMinimum(int v);
|
||||||
|
|
||||||
|
//! \~english Sets the maximum scroll value.
|
||||||
|
//! \~russian Устанавливает максимальное значение прокрутки.
|
||||||
void setMaximum(int v);
|
void setMaximum(int v);
|
||||||
|
|
||||||
|
//! \~english Sets the current scroll value.
|
||||||
|
//! \~russian Устанавливает текущее значение прокрутки.
|
||||||
void setValue(int v);
|
void setValue(int v);
|
||||||
|
|
||||||
|
//! \~english Returns the minimum scroll value.
|
||||||
|
//! \~russian Возвращает минимальное значение прокрутки.
|
||||||
int minimum() const { return minimum_; }
|
int minimum() const { return minimum_; }
|
||||||
|
|
||||||
|
//! \~english Returns the maximum scroll value.
|
||||||
|
//! \~russian Возвращает максимальное значение прокрутки.
|
||||||
int maximum() const { return maximum_; }
|
int maximum() const { return maximum_; }
|
||||||
|
|
||||||
|
//! \~english Returns the current scroll value.
|
||||||
|
//! \~russian Возвращает текущее значение прокрутки.
|
||||||
int value() const { return value_; }
|
int value() const { return value_; }
|
||||||
|
|
||||||
|
//! \~english Thickness of the drawn bar in cells, perpendicular to the scroll direction.
|
||||||
|
//! \~russian Толщина отрисовываемой полосы в ячейках поперек направления прокрутки.
|
||||||
int thickness;
|
int thickness;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -74,29 +127,68 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Scrollable list tile with optional row selection.
|
||||||
|
//! \~russian Прокручиваемый тайл списка с необязательным выбором строк.
|
||||||
class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileList, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileList, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Selection policy for list rows.
|
||||||
|
//! \~russian Режим выбора строк списка.
|
||||||
enum SelectionMode {
|
enum SelectionMode {
|
||||||
NoSelection,
|
NoSelection /** \~english Rows are not selectable. \~russian Выбор строк отключен. */,
|
||||||
SingleSelection,
|
SingleSelection /** \~english At most one row can be selected. \~russian Можно выбрать не более одной строки. */,
|
||||||
MultiSelection
|
MultiSelection /** \~english Multiple rows can be selected. \~russian Можно выбрать несколько строк. */
|
||||||
};
|
|
||||||
enum EventType {
|
|
||||||
SelectionChanged,
|
|
||||||
RowPressed
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Events emitted by the list tile.
|
||||||
|
//! \~russian События, генерируемые тайлом списка.
|
||||||
|
enum EventType {
|
||||||
|
SelectionChanged /** \~english Selection set changed. \~russian Изменился набор выбранных строк. */,
|
||||||
|
RowPressed /** \~english Current row was activated; event data stores the row index. \~russian Текущая строка была активирована; данные события содержат индекс строки. */
|
||||||
|
};
|
||||||
|
|
||||||
|
//! \~english Constructs a list tile with the specified selection mode.
|
||||||
|
//! \~russian Создает тайл списка с указанным режимом выбора.
|
||||||
TileList(const PIString & n = PIString(), SelectionMode sm = NoSelection);
|
TileList(const PIString & n = PIString(), SelectionMode sm = NoSelection);
|
||||||
|
|
||||||
|
//! \~english Destroys the list tile.
|
||||||
|
//! \~russian Уничтожает тайл списка.
|
||||||
virtual ~TileList() {}
|
virtual ~TileList() {}
|
||||||
|
|
||||||
|
//! \~english Row text with cell format.
|
||||||
|
//! \~russian Текст строки с форматом ячеек.
|
||||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
|
||||||
|
|
||||||
|
//! \~english Rows displayed by the list.
|
||||||
|
//! \~russian Строки, отображаемые списком.
|
||||||
PIDeque<Row> content;
|
PIDeque<Row> content;
|
||||||
|
|
||||||
|
//! \~english Alignment used to draw row text.
|
||||||
|
//! \~russian Выравнивание, используемое при рисовании текста строк.
|
||||||
PIScreenTypes::Alignment alignment;
|
PIScreenTypes::Alignment alignment;
|
||||||
|
|
||||||
|
//! \~english Active row selection mode.
|
||||||
|
//! \~russian Текущий режим выбора строк.
|
||||||
SelectionMode selection_mode;
|
SelectionMode selection_mode;
|
||||||
|
|
||||||
|
//! \~english Indexes of selected rows.
|
||||||
|
//! \~russian Индексы выбранных строк.
|
||||||
PISet<int> selected;
|
PISet<int> selected;
|
||||||
int lhei, cur, offset;
|
|
||||||
|
//! \~english Cached count of visible content rows between the top and bottom scroll markers.
|
||||||
|
//! \~russian Кэшированное количество видимых строк содержимого между верхней и нижней метками прокрутки.
|
||||||
|
int lhei;
|
||||||
|
|
||||||
|
//! \~english Index of the current row used for focus and activation.
|
||||||
|
//! \~russian Индекс текущей строки, используемой для фокуса и активации.
|
||||||
|
int cur;
|
||||||
|
|
||||||
|
//! \~english Index of the first row currently visible in the viewport.
|
||||||
|
//! \~russian Индекс первой строки, видимой в текущей области просмотра.
|
||||||
|
int offset;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
void sizeHint(int & w, int & h) const override;
|
void sizeHint(int & w, int & h) const override;
|
||||||
@@ -110,16 +202,34 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Push button tile.
|
||||||
|
//! \~russian Тайл кнопки.
|
||||||
class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileButton, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileButton, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a button tile.
|
||||||
|
//! \~russian Создает тайл кнопки.
|
||||||
TileButton(const PIString & n = PIString());
|
TileButton(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the button tile.
|
||||||
|
//! \~russian Уничтожает тайл кнопки.
|
||||||
virtual ~TileButton() {}
|
virtual ~TileButton() {}
|
||||||
|
|
||||||
|
//! \~english Events emitted by the button.
|
||||||
|
//! \~russian События, генерируемые кнопкой.
|
||||||
enum EventType {
|
enum EventType {
|
||||||
ButtonClicked
|
ButtonClicked /** \~english Button was activated. \~russian Кнопка была активирована. */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Text format of the button label.
|
||||||
|
//! \~russian Формат текста надписи кнопки.
|
||||||
PIScreenTypes::CellFormat format;
|
PIScreenTypes::CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Button caption.
|
||||||
|
//! \~russian Подпись кнопки.
|
||||||
PIString text;
|
PIString text;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -130,18 +240,42 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Group of selectable buttons arranged in one tile.
|
||||||
|
//! \~russian Группа выбираемых кнопок, размещенных в одном тайле.
|
||||||
class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a button group tile.
|
||||||
|
//! \~russian Создает тайл группы кнопок.
|
||||||
TileButtons(const PIString & n = PIString());
|
TileButtons(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the button group tile.
|
||||||
|
//! \~russian Уничтожает тайл группы кнопок.
|
||||||
virtual ~TileButtons() {}
|
virtual ~TileButtons() {}
|
||||||
|
|
||||||
|
//! \~english Events emitted by the button group.
|
||||||
|
//! \~russian События, генерируемые группой кнопок.
|
||||||
enum EventType {
|
enum EventType {
|
||||||
ButtonSelected
|
ButtonSelected /** \~english A button was selected; event data stores the button index. \~russian Кнопка была выбрана; данные события содержат индекс кнопки. */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Button caption with cell format.
|
||||||
|
//! \~russian Подпись кнопки с форматом ячеек.
|
||||||
typedef PIPair<PIString, PIScreenTypes::CellFormat> Button;
|
typedef PIPair<PIString, PIScreenTypes::CellFormat> Button;
|
||||||
|
|
||||||
|
//! \~english Alignment of the whole button group inside the tile bounds.
|
||||||
|
//! \~russian Выравнивание всей группы кнопок внутри границ тайла.
|
||||||
PIScreenTypes::Alignment alignment;
|
PIScreenTypes::Alignment alignment;
|
||||||
|
|
||||||
|
//! \~english Button definitions shown by the tile.
|
||||||
|
//! \~russian Описания кнопок, отображаемых тайлом.
|
||||||
PIVector<Button> content;
|
PIVector<Button> content;
|
||||||
|
|
||||||
|
//! \~english Index of the currently highlighted button.
|
||||||
|
//! \~russian Индекс текущей подсвеченной кнопки.
|
||||||
int cur;
|
int cur;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -157,17 +291,38 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Check box tile.
|
||||||
|
//! \~russian Тайл флажка.
|
||||||
class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a check box tile.
|
||||||
|
//! \~russian Создает тайл флажка.
|
||||||
TileCheck(const PIString & n = PIString());
|
TileCheck(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the check box tile.
|
||||||
|
//! \~russian Уничтожает тайл флажка.
|
||||||
virtual ~TileCheck() {}
|
virtual ~TileCheck() {}
|
||||||
|
|
||||||
|
//! \~english Events emitted by the check box.
|
||||||
|
//! \~russian События, генерируемые флажком.
|
||||||
enum EventType {
|
enum EventType {
|
||||||
Toggled
|
Toggled /** \~english Check state changed; event data stores the new boolean value. \~russian Состояние флажка изменилось; данные события содержат новое логическое значение. */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Text format of the caption.
|
||||||
|
//! \~russian Формат текста подписи.
|
||||||
PIScreenTypes::CellFormat format;
|
PIScreenTypes::CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Caption displayed after the check mark.
|
||||||
|
//! \~russian Подпись, отображаемая после флажка.
|
||||||
PIString text;
|
PIString text;
|
||||||
|
|
||||||
|
//! \~english Current check state.
|
||||||
|
//! \~russian Текущее состояние флажка.
|
||||||
bool toggled;
|
bool toggled;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -178,16 +333,40 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Progress indicator tile.
|
||||||
|
//! \~russian Тайл индикатора прогресса.
|
||||||
class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a progress tile.
|
||||||
|
//! \~russian Создает тайл прогресса.
|
||||||
TileProgress(const PIString & n = PIString());
|
TileProgress(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the progress tile.
|
||||||
|
//! \~russian Уничтожает тайл прогресса.
|
||||||
virtual ~TileProgress() {}
|
virtual ~TileProgress() {}
|
||||||
|
|
||||||
|
//! \~english Text format used for the overlaid label.
|
||||||
|
//! \~russian Формат текста, используемый для наложенной подписи.
|
||||||
PIScreenTypes::CellFormat format;
|
PIScreenTypes::CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Text shown before the numeric value.
|
||||||
|
//! \~russian Текст, отображаемый перед числовым значением.
|
||||||
PIString prefix;
|
PIString prefix;
|
||||||
|
|
||||||
|
//! \~english Text shown after the numeric value.
|
||||||
|
//! \~russian Текст, отображаемый после числового значения.
|
||||||
PIString suffix;
|
PIString suffix;
|
||||||
|
|
||||||
|
//! \~english Value treated as 100 percent.
|
||||||
|
//! \~russian Значение, принимаемое за 100 процентов.
|
||||||
double maximum;
|
double maximum;
|
||||||
|
|
||||||
|
//! \~english Current progress value.
|
||||||
|
//! \~russian Текущее значение прогресса.
|
||||||
double value;
|
double value;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -196,13 +375,28 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Log view tile backed by the global %PICout buffer.
|
||||||
|
//! \~russian Тайл журнала, использующий глобальный буфер %PICout.
|
||||||
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
|
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
|
||||||
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
|
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a %PICout viewer tile.
|
||||||
|
//! \~russian Создает тайл просмотра %PICout.
|
||||||
TilePICout(const PIString & n = PIString());
|
TilePICout(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the %PICout viewer tile.
|
||||||
|
//! \~russian Уничтожает тайл просмотра %PICout.
|
||||||
virtual ~TilePICout() {}
|
virtual ~TilePICout() {}
|
||||||
|
|
||||||
|
//! \~english Format applied to appended log lines.
|
||||||
|
//! \~russian Формат, применяемый к добавляемым строкам журнала.
|
||||||
PIScreenTypes::CellFormat format;
|
PIScreenTypes::CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Maximum number of lines retained from the %PICout buffer.
|
||||||
|
//! \~russian Максимальное количество строк, сохраняемых из буфера %PICout.
|
||||||
int max_lines;
|
int max_lines;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -211,14 +405,32 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Single-line editable text input tile.
|
||||||
|
//! \~russian Однострочный тайл редактируемого текстового ввода.
|
||||||
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
|
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
|
||||||
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
|
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an input tile.
|
||||||
|
//! \~russian Создает тайл ввода.
|
||||||
TileInput(const PIString & n = PIString());
|
TileInput(const PIString & n = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the input tile.
|
||||||
|
//! \~russian Уничтожает тайл ввода.
|
||||||
virtual ~TileInput() {}
|
virtual ~TileInput() {}
|
||||||
|
|
||||||
|
//! \~english Format of the entered text.
|
||||||
|
//! \~russian Формат вводимого текста.
|
||||||
PIScreenTypes::CellFormat format;
|
PIScreenTypes::CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Current input text.
|
||||||
|
//! \~russian Текущий введенный текст.
|
||||||
PIString text;
|
PIString text;
|
||||||
|
|
||||||
|
//! \~english Maximum input length setting reserved for the tile logic.
|
||||||
|
//! \~russian Параметр максимальной длины ввода, зарезервированный для логики тайла.
|
||||||
int max_length;
|
int max_length;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -1,9 +1,11 @@
|
|||||||
/*! \file piscreentypes.h
|
//! \~\file piscreentypes.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Types for PIScreen
|
//! \~english Types for PIScreen
|
||||||
* \~russian Типы для PIScreen
|
//! \~russian Типы для PIScreen
|
||||||
*/
|
//! \details
|
||||||
|
//! \~english Provides common types used by screen tiles and drawer.
|
||||||
|
//! \~russian Обеспечивает общие типы, используемые тайлами и отрисовщиком экрана.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Types for PIScreen
|
Types for PIScreen
|
||||||
@@ -32,92 +34,160 @@
|
|||||||
|
|
||||||
class PIScreenTile;
|
class PIScreenTile;
|
||||||
|
|
||||||
|
//! \relatesalso PIScreenTile
|
||||||
|
//! \~english Namespace with shared screen cells, layout flags, and tile event types.
|
||||||
|
//! \~russian Пространство имен с общими типами экранных ячеек, флагами компоновки и событиями тайлов.
|
||||||
namespace PIScreenTypes {
|
namespace PIScreenTypes {
|
||||||
|
|
||||||
//! Color for chars or background
|
//! \~english Color for a character or its background.
|
||||||
|
//! \~russian Цвет символа или его фона.
|
||||||
enum Color {
|
enum Color {
|
||||||
Default /** Default */,
|
Default /** \~english Terminal default color \~russian Цвет терминала по умолчанию */,
|
||||||
Black /** Black */,
|
Black /** \~english Black \~russian Черный */,
|
||||||
Red /** Red */,
|
Red /** \~english Red \~russian Красный */,
|
||||||
Green /** Green */,
|
Green /** \~english Green \~russian Зеленый */,
|
||||||
Blue /** Blue */,
|
Blue /** \~english Blue \~russian Синий */,
|
||||||
Cyan /** Cyan */,
|
Cyan /** \~english Cyan \~russian Голубой */,
|
||||||
Magenta /** Magenta */,
|
Magenta /** \~english Magenta \~russian Пурпурный */,
|
||||||
Yellow /** Yellow */,
|
Yellow /** \~english Yellow \~russian Желтый */,
|
||||||
White /** White */,
|
White /** \~english White \~russian Белый */,
|
||||||
Transparent /** Save previous color */
|
Transparent /** \~english Preserve the background already stored in the target cell \~russian Сохранить фон, уже записанный в целевой
|
||||||
|
ячейке */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Flags for chars
|
//! \~english Character formatting flags.
|
||||||
|
//! \~russian Флаги оформления символа.
|
||||||
enum CharFlag {
|
enum CharFlag {
|
||||||
Bold /** Bold or bright */ = 0x1,
|
Bold = 0x1 /** \~english Bold or bright text \~russian Жирный или яркий текст */,
|
||||||
Blink /** Blink text */ = 0x2,
|
Blink = 0x2 /** \~english Blinking text \~russian Мигание текста */,
|
||||||
Underline /** Underline text */ = 0x4,
|
Underline = 0x4 /** \~english Underlined text \~russian Подчеркнутый текст */,
|
||||||
Inverse = 0x08
|
Inverse = 0x08 /** \~english Inverted foreground and background \~russian Инвертированные цвета текста и фона */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Alignment
|
//! \~english Horizontal text alignment inside a tile.
|
||||||
|
//! \~russian Горизонтальное выравнивание текста внутри тайла.
|
||||||
enum Alignment {
|
enum Alignment {
|
||||||
Left /** Left */,
|
Left /** \~english Left alignment \~russian Выравнивание влево */,
|
||||||
Center /** Center */,
|
Center /** \~english Center alignment \~russian Выравнивание по центру */,
|
||||||
Right /** Right */
|
Right /** \~english Right alignment \~russian Выравнивание вправо */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Size policy
|
//! \~english Layout policy used by parent tiles.
|
||||||
|
//! \~russian Политика размера, используемая родительскими тайлами при компоновке.
|
||||||
enum SizePolicy {
|
enum SizePolicy {
|
||||||
Fixed /** Fixed size */,
|
Fixed /** \~english Keep the requested size \~russian Сохранять запрошенный размер */,
|
||||||
Preferred /** Preferred size */,
|
Preferred /** \~english Use preferred size first and share extra space after fixed tiles \~russian Сначала использовать предпочтительный
|
||||||
Expanding /** Maximum available size */,
|
размер и затем делить свободное место после фиксированных тайлов */
|
||||||
Ignore /** Ignore layout logic */
|
,
|
||||||
|
Expanding /** \~english Take extra space before preferred tiles when the parent can grow children \~russian Получать дополнительное
|
||||||
|
пространство раньше тайлов с предпочтительным размером, если родитель может расширять дочерние элементы */
|
||||||
|
,
|
||||||
|
Ignore /** \~english Skip automatic layout; geometry must be managed manually \~russian Не участвовать в автоматической компоновке;
|
||||||
|
геометрию нужно задавать вручную */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Direction
|
//! \~english Child layout direction.
|
||||||
|
//! \~russian Направление раскладки дочерних тайлов.
|
||||||
enum Direction {
|
enum Direction {
|
||||||
Horizontal /** Horizontal */,
|
Horizontal /** \~english Horizontal layout \~russian Горизонтальная раскладка */,
|
||||||
Vertical /** Vertical */
|
Vertical /** \~english Vertical layout \~russian Вертикальная раскладка */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Focus flags
|
//! \~english Focus and navigation flags for tiles.
|
||||||
|
//! \~russian Флаги фокуса и навигации для тайлов.
|
||||||
enum FocusFlag {
|
enum FocusFlag {
|
||||||
CanHasFocus /** Tile can has focus */ = 0x1,
|
CanHasFocus = 0x1 /** \~english Tile can receive focus \~russian Тайл может получать фокус */,
|
||||||
NextByTab /** Focus passed to next tile by tab key */ = 0x2,
|
NextByTab = 0x2 /** \~english Tab moves focus to the next tile \~russian Клавиша Tab переводит фокус к следующему тайлу */,
|
||||||
NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4,
|
NextByArrowsHorizontal = 0x4 /** \~english Left and right arrows move focus \~russian Стрелки влево и вправо переводят фокус */,
|
||||||
NextByArrowsVertical /** Focus passed to next tile by arrow keys up or down */ = 0x8,
|
NextByArrowsVertical = 0x8 /** \~english Up and down arrows move focus \~russian Стрелки вверх и вниз переводят фокус */,
|
||||||
NextByArrowsAll /** Focus passed to next tile by any arrow key */ = NextByArrowsHorizontal | NextByArrowsVertical,
|
NextByArrowsAll /** \~english Any arrow key moves focus \~russian Любая стрелка переводит фокус */ =
|
||||||
FocusOnMouse /** Tile focused on mouse press */ = 0x10,
|
NextByArrowsHorizontal | NextByArrowsVertical,
|
||||||
FocusOnWheel /** Tile focused on wheel */ = 0x20,
|
FocusOnMouse = 0x10 /** \~english Mouse press gives focus to the tile \~russian Нажатие мышью переводит фокус на тайл */,
|
||||||
FocusOnMouseOrWheel /** Tile focused on mouse press or wheel */ = FocusOnMouse | FocusOnWheel
|
FocusOnWheel = 0x20 /** \~english Mouse wheel gives focus to the tile \~russian Колесо мыши переводит фокус на тайл */,
|
||||||
|
FocusOnMouseOrWheel /** \~english Mouse press or wheel gives focus to the tile \~russian Нажатие мышью или колесо переводят фокус на
|
||||||
|
тайл */
|
||||||
|
= FocusOnMouse | FocusOnWheel
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Combination of \a CharFlag values.
|
||||||
|
//! \~russian Комбинация значений \a CharFlag.
|
||||||
typedef PIFlags<CharFlag> CharFlags;
|
typedef PIFlags<CharFlag> CharFlags;
|
||||||
|
|
||||||
|
//! \~english Combination of \a FocusFlag values.
|
||||||
|
//! \~russian Комбинация значений \a FocusFlag.
|
||||||
typedef PIFlags<FocusFlag> FocusFlags;
|
typedef PIFlags<FocusFlag> FocusFlags;
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Packed character formatting used by screen cells.
|
||||||
|
//! \~russian Упакованное описание оформления символа, используемое экранными ячейками.
|
||||||
union PIP_CONSOLE_EXPORT CellFormat {
|
union PIP_CONSOLE_EXPORT CellFormat {
|
||||||
|
//! \~english Constructs a format from the raw packed value.
|
||||||
|
//! \~russian Создает формат из упакованного сырого значения.
|
||||||
CellFormat(ushort f = 0) { raw_format = f; }
|
CellFormat(ushort f = 0) { raw_format = f; }
|
||||||
|
|
||||||
|
//! \~english Constructs a format from foreground color, background color, and character flags.
|
||||||
|
//! \~russian Создает формат из цвета символа, цвета фона и флагов оформления.
|
||||||
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
|
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
|
||||||
color_char = col_char;
|
color_char = col_char;
|
||||||
color_back = col_back;
|
color_back = col_back;
|
||||||
flags = flags_;
|
flags = flags_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Raw packed representation of the format.
|
||||||
|
//! \~russian Сырое упакованное представление формата.
|
||||||
ushort raw_format;
|
ushort raw_format;
|
||||||
struct {
|
struct {
|
||||||
|
//! \~english Foreground color from \a Color.
|
||||||
|
//! \~russian Цвет символа из \a Color.
|
||||||
ushort color_char: 4;
|
ushort color_char: 4;
|
||||||
|
|
||||||
|
//! \~english Background color from \a Color.
|
||||||
|
//! \~russian Цвет фона из \a Color.
|
||||||
ushort color_back: 4;
|
ushort color_back: 4;
|
||||||
|
|
||||||
|
//! \~english Combination of \a CharFlag values.
|
||||||
|
//! \~russian Комбинация значений \a CharFlag.
|
||||||
ushort flags: 8;
|
ushort flags: 8;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Returns \b true when two formats are identical.
|
||||||
|
//! \~russian Возвращает \b true, если два формата совпадают.
|
||||||
bool operator==(const CellFormat & c) const { return raw_format == c.raw_format; }
|
bool operator==(const CellFormat & c) const { return raw_format == c.raw_format; }
|
||||||
|
|
||||||
|
//! \~english Returns \b true when two formats differ.
|
||||||
|
//! \~russian Возвращает \b true, если форматы различаются.
|
||||||
bool operator!=(const CellFormat & c) const { return raw_format != c.raw_format; }
|
bool operator!=(const CellFormat & c) const { return raw_format != c.raw_format; }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english One character cell of the console screen.
|
||||||
|
//! \~russian Одна символьная ячейка консольного экрана.
|
||||||
struct PIP_CONSOLE_EXPORT Cell {
|
struct PIP_CONSOLE_EXPORT Cell {
|
||||||
|
//! \~english Constructs a cell from a symbol and its format.
|
||||||
|
//! \~russian Создает ячейку из символа и его формата.
|
||||||
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {
|
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {
|
||||||
symbol = c;
|
symbol = c;
|
||||||
format = f;
|
format = f;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Cell formatting.
|
||||||
|
//! \~russian Формат ячейки.
|
||||||
CellFormat format;
|
CellFormat format;
|
||||||
|
|
||||||
|
//! \~english Character stored in the cell.
|
||||||
|
//! \~russian Символ, хранимый в ячейке.
|
||||||
PIChar symbol;
|
PIChar symbol;
|
||||||
|
|
||||||
|
//! \~english Returns \b true when symbol and format match.
|
||||||
|
//! \~russian Возвращает \b true, если совпадают символ и формат.
|
||||||
bool operator==(const Cell & c) const { return format == c.format && symbol == c.symbol; }
|
bool operator==(const Cell & c) const { return format == c.format && symbol == c.symbol; }
|
||||||
|
|
||||||
|
//! \~english Returns \b true when symbol or format differs.
|
||||||
|
//! \~russian Возвращает \b true, если символ или формат различаются.
|
||||||
bool operator!=(const Cell & c) const { return format != c.format || symbol != c.symbol; }
|
bool operator!=(const Cell & c) const { return format != c.format || symbol != c.symbol; }
|
||||||
|
|
||||||
|
//! \~english Assigns a cell, preserving the current background when source background is \a Transparent.
|
||||||
|
//! \~russian Присваивает ячейку, сохраняя текущий фон, если у источника фон равен \a Transparent.
|
||||||
Cell & operator=(const Cell & c) {
|
Cell & operator=(const Cell & c) {
|
||||||
symbol = c.symbol;
|
symbol = c.symbol;
|
||||||
if (c.format.color_back == Transparent) {
|
if (c.format.color_back == Transparent) {
|
||||||
@@ -129,18 +199,46 @@ struct PIP_CONSOLE_EXPORT Cell {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english User-defined event raised by a tile.
|
||||||
|
//! \~russian Пользовательское событие, поднимаемое тайлом.
|
||||||
struct PIP_CONSOLE_EXPORT TileEvent {
|
struct PIP_CONSOLE_EXPORT TileEvent {
|
||||||
|
//! \~english Constructs an event with numeric type and optional payload.
|
||||||
|
//! \~russian Создает событие с числовым типом и необязательными данными.
|
||||||
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
|
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
|
||||||
|
|
||||||
|
//! \~english Event type chosen by the tile implementation.
|
||||||
|
//! \~russian Тип события, выбираемый реализацией тайла.
|
||||||
int type;
|
int type;
|
||||||
|
|
||||||
|
//! \~english Optional event payload.
|
||||||
|
//! \~russian Необязательные данные события.
|
||||||
PIVariant data;
|
PIVariant data;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Base interface used by tiles to notify the owning screen about focus, removal, and custom events.
|
||||||
|
//! \~russian Базовый интерфейс, через который тайлы уведомляют владеющий экран о фокусе, удалении и пользовательских событиях.
|
||||||
class PIP_CONSOLE_EXPORT PIScreenBase {
|
class PIP_CONSOLE_EXPORT PIScreenBase {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an empty screen bridge.
|
||||||
|
//! \~russian Создает пустой мост к экрану.
|
||||||
PIScreenBase() {}
|
PIScreenBase() {}
|
||||||
|
|
||||||
|
//! \~english Destroys the screen bridge.
|
||||||
|
//! \~russian Уничтожает мост к экрану.
|
||||||
virtual ~PIScreenBase() {}
|
virtual ~PIScreenBase() {}
|
||||||
|
|
||||||
|
//! \~english Called when a tile raises a custom event.
|
||||||
|
//! \~russian Вызывается, когда тайл поднимает пользовательское событие.
|
||||||
virtual void tileEventInternal(PIScreenTile *, TileEvent) {}
|
virtual void tileEventInternal(PIScreenTile *, TileEvent) {}
|
||||||
|
|
||||||
|
//! \~english Called when a tile is removed from the screen tree.
|
||||||
|
//! \~russian Вызывается при удалении тайла из дерева экрана.
|
||||||
virtual void tileRemovedInternal(PIScreenTile *) {}
|
virtual void tileRemovedInternal(PIScreenTile *) {}
|
||||||
|
|
||||||
|
//! \~english Called when a tile requests focus.
|
||||||
|
//! \~russian Вызывается, когда тайл запрашивает фокус.
|
||||||
virtual void tileSetFocusInternal(PIScreenTile *) {}
|
virtual void tileSetFocusInternal(PIScreenTile *) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piterminal.h
|
//! \~\file piterminal.h
|
||||||
* \ingroup Console
|
//! \~\ingroup Console
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Virtual terminal
|
//! \~english Virtual terminal
|
||||||
* \~russian Виртуальный терминал
|
//! \~russian Виртуальный терминал
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Virtual terminal
|
Virtual terminal
|
||||||
@@ -31,26 +30,65 @@
|
|||||||
#include "piscreentypes.h"
|
#include "piscreentypes.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Console
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Virtual terminal that runs a shell and mirrors its screen into a cell buffer.
|
||||||
|
//! \~russian Виртуальный терминал, который запускает оболочку и отражает ее экран в буфер ячеек.
|
||||||
|
//! \details
|
||||||
|
//! \~english Provides terminal emulation for reading console input and output. Supports ANSI escape sequences for cursor movement, colors,
|
||||||
|
//! and text formatting.
|
||||||
|
//! \~russian Обеспечивает эмуляцию терминала для чтения ввода и вывода консоли. Поддерживает ANSI escape-последовательности для перемещения
|
||||||
|
//! курсора, цветов и форматирования текста.
|
||||||
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
|
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PITerminal, PIThread);
|
PIOBJECT_SUBCLASS(PITerminal, PIThread);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! Constructs %PITerminal
|
//! \~english Constructs %PITerminal.
|
||||||
|
//! \~russian Создает %PITerminal.
|
||||||
PITerminal();
|
PITerminal();
|
||||||
|
|
||||||
|
//! \~english Destroys the terminal and releases backend resources.
|
||||||
|
//! \~russian Уничтожает терминал и освобождает внутренние ресурсы.
|
||||||
~PITerminal();
|
~PITerminal();
|
||||||
|
|
||||||
|
//! \~english Returns terminal width in columns.
|
||||||
|
//! \~russian Возвращает ширину терминала в столбцах.
|
||||||
int columns() const { return size_x; }
|
int columns() const { return size_x; }
|
||||||
|
|
||||||
|
//! \~english Returns terminal height in rows.
|
||||||
|
//! \~russian Возвращает высоту терминала в строках.
|
||||||
int rows() const { return size_y; }
|
int rows() const { return size_y; }
|
||||||
|
|
||||||
|
//! \~english Resizes the terminal viewport and backing cell buffer.
|
||||||
|
//! \~russian Изменяет размер области терминала и связанного буфера ячеек.
|
||||||
bool resize(int cols, int rows);
|
bool resize(int cols, int rows);
|
||||||
|
|
||||||
|
//! \~english Sends raw byte data to the terminal input.
|
||||||
|
//! \~russian Отправляет необработанные байты во входной поток терминала.
|
||||||
void write(const PIByteArray & d);
|
void write(const PIByteArray & d);
|
||||||
|
|
||||||
|
//! \~english Sends a special key with modifiers to the terminal.
|
||||||
|
//! \~russian Отправляет в терминал специальную клавишу с модификаторами.
|
||||||
void write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m);
|
void write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m);
|
||||||
|
|
||||||
|
//! \~english Sends a keyboard event to the terminal.
|
||||||
|
//! \~russian Отправляет событие клавиатуры в терминал.
|
||||||
void write(PIKbdListener::KeyEvent ke);
|
void write(PIKbdListener::KeyEvent ke);
|
||||||
|
|
||||||
|
//! \~english Returns the current terminal screen snapshot, including cursor blink state.
|
||||||
|
//! \~russian Возвращает текущий снимок экрана терминала с учетом состояния мигания курсора.
|
||||||
PIVector<PIVector<PIScreenTypes::Cell>> content();
|
PIVector<PIVector<PIScreenTypes::Cell>> content();
|
||||||
|
|
||||||
|
//! \~english Returns whether key code `k` is handled as a special terminal key.
|
||||||
|
//! \~russian Возвращает, обрабатывается ли код `k` как специальная клавиша терминала.
|
||||||
static bool isSpecialKey(int k);
|
static bool isSpecialKey(int k);
|
||||||
|
|
||||||
|
//! \~english Initializes the terminal backend and starts the polling thread.
|
||||||
|
//! \~russian Инициализирует внутренний терминал и запускает поток опроса.
|
||||||
bool initialize();
|
bool initialize();
|
||||||
|
|
||||||
|
//! \~english Stops the terminal and destroys the internal terminal backend instance.
|
||||||
|
//! \~russian Останавливает терминал и уничтожает внутреннюю реализацию терминала.
|
||||||
void destroy();
|
void destroy();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file picontainers.h
|
//! \~\file picontainers.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Base macros for generic containers
|
//! \~english Base macros for generic containers
|
||||||
//! \~russian Базовые макросы для контейнеров
|
//! \~russian Базовые макросы для контейнеров
|
||||||
@@ -74,17 +74,14 @@ public:
|
|||||||
template<typename T>
|
template<typename T>
|
||||||
class _PIContainerConstants {
|
class _PIContainerConstants {
|
||||||
public:
|
public:
|
||||||
// minimum elements for container
|
|
||||||
static size_t minCountPoT() {
|
static size_t minCountPoT() {
|
||||||
static const size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T));
|
static const size_t ret = _PIContainerConstantsBase::calcMinCountPoT(sizeof(T));
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
// maximum elements for 2^n growth
|
|
||||||
static size_t maxCountForPoT() {
|
static size_t maxCountForPoT() {
|
||||||
static const size_t ret = _PIContainerConstantsBase::calcMaxCountForPoT(sizeof(T));
|
static const size_t ret = _PIContainerConstantsBase::calcMaxCountForPoT(sizeof(T));
|
||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
// add elements after 2^n growth
|
|
||||||
static size_t stepAfterPoT() {
|
static size_t stepAfterPoT() {
|
||||||
static const size_t ret = _PIContainerConstantsBase::calcStepAfterPoT(sizeof(T));
|
static const size_t ret = _PIContainerConstantsBase::calcStepAfterPoT(sizeof(T));
|
||||||
return ret;
|
return ret;
|
||||||
@@ -112,9 +109,6 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \brief
|
|
||||||
//! \~english Template reverse wrapper over any container
|
|
||||||
//! \~russian Шаблонная функция обертки любого контейнера для обратного доступа через итераторы
|
|
||||||
template<typename C>
|
template<typename C>
|
||||||
_PIReverseWrapper<C> PIReverseWrap(C & c) {
|
_PIReverseWrapper<C> PIReverseWrap(C & c) {
|
||||||
return _PIReverseWrapper<C>(c);
|
return _PIReverseWrapper<C>(c);
|
||||||
|
|||||||
@@ -18,8 +18,8 @@
|
|||||||
*/
|
*/
|
||||||
//! \defgroup Containers Containers
|
//! \defgroup Containers Containers
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Various standart containers realization
|
//! \~english Container classes and related helpers
|
||||||
//! \~russian Различные классы контейнеров
|
//! \~russian Классы контейнеров и связанные вспомогательные сущности
|
||||||
//!
|
//!
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english \section cmake_module_Containers Building with CMake
|
//! \~english \section cmake_module_Containers Building with CMake
|
||||||
@@ -58,9 +58,8 @@
|
|||||||
//! \a PIVector2D | Линейный двумерный прямоугольный массив
|
//! \a PIVector2D | Линейный двумерный прямоугольный массив
|
||||||
//!
|
//!
|
||||||
//!
|
//!
|
||||||
//! \~english \section stl_iterators STL-Style Iterators
|
|
||||||
//! \~russian \section stl_iterators Итераторы в стиле STL
|
|
||||||
//! \~english
|
//! \~english
|
||||||
|
//! \section stl_iterators STL-Style Iterators
|
||||||
//! \brief They are compatible with Qt's and STL's generic algorithms and are optimized for speed.
|
//! \brief They are compatible with Qt's and STL's generic algorithms and are optimized for speed.
|
||||||
//! \details
|
//! \details
|
||||||
//! For each container class, there are two STL-style iterator types:
|
//! For each container class, there are two STL-style iterator types:
|
||||||
@@ -114,6 +113,7 @@
|
|||||||
//! can be used on the left side of the assignment operator.
|
//! can be used on the left side of the assignment operator.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
|
//! \section stl_iterators Итераторы в стиле STL
|
||||||
//! \brief Они совместимы с базовыми алгоритмами Qt и STL и оптимизированы по скорости.
|
//! \brief Они совместимы с базовыми алгоритмами Qt и STL и оптимизированы по скорости.
|
||||||
//! \details
|
//! \details
|
||||||
//! Для каждого контейнерного класса есть два типа итераторов в стиле STL:
|
//! Для каждого контейнерного класса есть два типа итераторов в стиле STL:
|
||||||
@@ -167,6 +167,14 @@
|
|||||||
//! Для неконстантных итераторов, возвращаемое значение унарного оператора `*`
|
//! Для неконстантных итераторов, возвращаемое значение унарного оператора `*`
|
||||||
//! может быть использовано с левой стороны от оператора присваивания.
|
//! может быть использовано с левой стороны от оператора присваивания.
|
||||||
//!
|
//!
|
||||||
|
//! \~\file picontainersmodule.h
|
||||||
|
//! \~\ingroup Containers
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Umbrella header for the Containers module.
|
||||||
|
//! \~russian Общий заголовок модуля Containers.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Includes the primary public container headers.
|
||||||
|
//! \~russian Подключает основные публичные заголовки контейнеров.
|
||||||
//!
|
//!
|
||||||
//! \authors
|
//! \authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file pideque.h
|
//! \~\file pideque.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Declares \a PIDeque
|
//! \~english Declares \a PIDeque
|
||||||
//! \~russian Объявление \a PIDeque
|
//! \~russian Объявление \a PIDeque
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file pimap.h
|
//! \~\file pimap.h
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Declares \a PIMap
|
//! \~english Declares \a PIMap
|
||||||
//! \~russian Объявление \a PIMap
|
//! \~russian Объявление \a PIMap
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
@@ -52,32 +52,23 @@ class PIMapIteratorReverse;
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIMap
|
//! \class PIMap
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Associative array.
|
//! \~english Map of unique keys and associated values.
|
||||||
//! \~russian Словарь.
|
//! \~russian Словарь с уникальными ключами и связанными значениями.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! A collection of key/value pairs, from which you retrieve a value using its associated key.
|
//! Stores key/value pairs and keeps keys unique.
|
||||||
//! There is a finite number of keys in the map, and each key has exactly one value associated with it.
|
//! \a value() returns the value for a key or the provided default,
|
||||||
//! \a value() returns value for key and leave map
|
//! while \a operator[] creates a default value for a missing key.
|
||||||
//! unchaged in any case. \a operator [] create entry in map if
|
//! Use \a keys() and \a values() to retrieve map contents,
|
||||||
//! there is no entry for given key. You can retrieve all
|
//! and \a makeIterator() or \a makeReverseIterator() to traverse entries.
|
||||||
//! keys by method \a keys() and all values by methos \a values().
|
|
||||||
//! To iterate all entries use class PIMapIterator, or methods
|
|
||||||
//! \a makeIterator() and \a makeReverseIterator().
|
|
||||||
//! A key in the Map may only occur once.
|
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Словари, в принципе, похожи на обычные, используемые в повседневной жизни.
|
//! Хранит пары ключ/значение и поддерживает уникальность ключей.
|
||||||
//! Они хранят элементы одного и того же типа, индексируемые ключевыми значениями.
|
//! \a value() возвращает значение по ключу или значение по умолчанию,
|
||||||
//! Достоинство словаря в том, что он позволяет быстро получать значение,
|
//! а \a operator[] создает значение по умолчанию для отсутствующего ключа.
|
||||||
//! ассоциированное с заданным ключом.
|
//! Для получения содержимого используйте \a keys() и \a values(),
|
||||||
//! Ключи должны быть уникальными.
|
//! а для обхода элементов - \a makeIterator() или \a makeReverseIterator().
|
||||||
//! Элемент
|
|
||||||
//! В контейнеры этого типа заносятся элементы вместе с ключами,
|
|
||||||
//! по которым их можно найти, которыми могут выступать значения любого типа.
|
|
||||||
//! \a operator [] позволяет получить доступ к элементу по ключу,
|
|
||||||
//! и если такого эелемента не было, то он будет создан.
|
|
||||||
template<typename Key, typename T>
|
template<typename Key, typename T>
|
||||||
class PIMap {
|
class PIMap {
|
||||||
template<typename Key1, typename T1>
|
template<typename Key1, typename T1>
|
||||||
@@ -240,12 +231,11 @@ public:
|
|||||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||||
inline const_iterator end() const { return const_iterator(this, size()); }
|
inline const_iterator end() const { return const_iterator(this, size()); }
|
||||||
|
|
||||||
//! \~english Returns a reverse iterator to the first element of the reversed array.
|
//! \~english Returns a reverse iterator to the last map entry.
|
||||||
//! \~russian Обратный итератор на первый элемент.
|
//! \~russian Обратный итератор на первый элемент.
|
||||||
inline reverse_iterator rbegin() { return reverse_iterator(this, size() - 1); }
|
inline reverse_iterator rbegin() { return reverse_iterator(this, size() - 1); }
|
||||||
|
|
||||||
//! \~english Returns a reverse iterator to the element.
|
//! \~english Returns a reverse iterator to the position before the first map entry.
|
||||||
//! following the last element of the reversed array.
|
|
||||||
//! \~russian Обратный итератор на элемент,
|
//! \~russian Обратный итератор на элемент,
|
||||||
//! следующий за последним элементом.
|
//! следующий за последним элементом.
|
||||||
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
inline reverse_iterator rend() { return reverse_iterator(this, -1); }
|
||||||
@@ -265,13 +255,13 @@ public:
|
|||||||
//! \relatesalso PIMapIteratorReverse
|
//! \relatesalso PIMapIteratorReverse
|
||||||
inline PIMapIteratorReverse<Key, T> makeReverseIterator() { return PIMapIteratorReverse<Key, T>(*this); }
|
inline PIMapIteratorReverse<Key, T> makeReverseIterator() { return PIMapIteratorReverse<Key, T>(*this); }
|
||||||
|
|
||||||
//! \~english Number of elements in the container.
|
//! \~english Number of entries in the map.
|
||||||
//! \~russian Количество элементов массива.
|
//! \~russian Количество элементов в словаре.
|
||||||
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
//! \~\sa \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||||
inline size_t size() const { return pim_content.size(); }
|
inline size_t size() const { return pim_content.size(); }
|
||||||
|
|
||||||
//! \~english Number of elements in the container as signed value.
|
//! \~english Number of entries in the map as a signed value.
|
||||||
//! \~russian Количество элементов массива в виде знакового числа.
|
//! \~russian Количество элементов в словаре в виде знакового числа.
|
||||||
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
//! \~\sa \a size(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||||
inline int size_s() const { return pim_content.size_s(); }
|
inline int size_s() const { return pim_content.size_s(); }
|
||||||
|
|
||||||
@@ -280,19 +270,13 @@ public:
|
|||||||
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
//! \~\sa \a size(), \a size_s(), \a capacity(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||||
inline size_t length() const { return pim_content.size(); }
|
inline size_t length() const { return pim_content.size(); }
|
||||||
|
|
||||||
//! \~english Checks if the container has no elements.
|
//! \~english Checks whether the map is empty.
|
||||||
//! \~russian Проверяет пуст ли массив.
|
//! \~russian Проверяет, пуст ли словарь.
|
||||||
//! \~\return
|
|
||||||
//! \~english **true** if the container is empty, **false** otherwise
|
|
||||||
//! \~russian **true** если массив пуст, **false** иначе.
|
|
||||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||||
inline bool isEmpty() const { return (pim_content.size() == 0); }
|
inline bool isEmpty() const { return (pim_content.size() == 0); }
|
||||||
|
|
||||||
//! \~english Checks if the container has elements.
|
//! \~english Checks whether the map contains entries.
|
||||||
//! \~russian Проверяет не пуст ли массив.
|
//! \~russian Проверяет, содержит ли словарь элементы.
|
||||||
//! \~\return
|
|
||||||
//! \~english **true** if the container is not empty, **false** otherwise
|
|
||||||
//! \~russian **true** если массив не пуст, **false** иначе.
|
|
||||||
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
//! \~\sa \a size(), \a size_s(), \a isEmpty(), \a isNotEmpty(), \a resize(), \a reserve()
|
||||||
inline bool isNotEmpty() const { return (pim_content.size() > 0); }
|
inline bool isNotEmpty() const { return (pim_content.size() > 0); }
|
||||||
|
|
||||||
@@ -304,7 +288,7 @@ public:
|
|||||||
//! the function inserts a default-constructed value into the map with key `key`,
|
//! the function inserts a default-constructed value into the map with key `key`,
|
||||||
//! and returns a reference to it.
|
//! and returns a reference to it.
|
||||||
//! \~russian Если элемента с таким ключом `key` не существует,
|
//! \~russian Если элемента с таким ключом `key` не существует,
|
||||||
//! то он будет создан конструктором по умолчанию и добавлен в массив
|
//! то он будет создан конструктором по умолчанию и добавлен в словарь
|
||||||
//! по ключу `key`, а затем возвращена ссылка на этот новый элемент.
|
//! по ключу `key`, а затем возвращена ссылка на этот новый элемент.
|
||||||
//! \~\code
|
//! \~\code
|
||||||
//! PIMap <PIString, int> m;
|
//! PIMap <PIString, int> m;
|
||||||
@@ -339,8 +323,8 @@ public:
|
|||||||
return _value(i);
|
return _value(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Remove element with key `key` from the array and return it.
|
//! \~english Removes entry with key `key` and returns its value.
|
||||||
//! \~russian Удаляет элемент с ключом `key` из массива и возвращает его.
|
//! \~russian Удаляет элемент с ключом `key` и возвращает его значение.
|
||||||
inline T take(const Key & key, const T & default_ = T()) {
|
inline T take(const Key & key, const T & default_ = T()) {
|
||||||
bool f(false);
|
bool f(false);
|
||||||
const ssize_t i = _find(key, f);
|
const ssize_t i = _find(key, f);
|
||||||
@@ -350,8 +334,8 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Inserts all elements in array `other` to this array with overwrite.
|
//! \~english Inserts all entries from `other`, overwriting existing keys.
|
||||||
//! \~russian Вставляет все элементы `other` этот массив с перезаписью.
|
//! \~russian Добавляет все элементы из `other`, перезаписывая существующие ключи.
|
||||||
inline PIMap<Key, T> & operator<<(const PIMap<Key, T> & other) {
|
inline PIMap<Key, T> & operator<<(const PIMap<Key, T> & other) {
|
||||||
#ifndef NDEBUG
|
#ifndef NDEBUG
|
||||||
if (&other == this) {
|
if (&other == this) {
|
||||||
@@ -375,24 +359,24 @@ public:
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Compare operator with array `m`.
|
//! \~english Compares this map with `m`.
|
||||||
//! \~russian Оператор сравнения с массивом `m`.
|
//! \~russian Сравнивает этот словарь с `m`.
|
||||||
inline bool operator==(const PIMap<Key, T> & m) const { return (pim_content == m.pim_content && pim_index == m.pim_index); }
|
inline bool operator==(const PIMap<Key, T> & m) const { return (pim_content == m.pim_content && pim_index == m.pim_index); }
|
||||||
|
|
||||||
//! \~english Compare operator with array `m`.
|
//! \~english Compares this map with `m`.
|
||||||
//! \~russian Оператор сравнения с массивом `m`.
|
//! \~russian Сравнивает этот словарь с `m`.
|
||||||
inline bool operator!=(const PIMap<Key, T> & m) const { return (pim_content != m.pim_content || pim_index != m.pim_index); }
|
inline bool operator!=(const PIMap<Key, T> & m) const { return (pim_content != m.pim_content || pim_index != m.pim_index); }
|
||||||
|
|
||||||
//! \~english Tests if element with key `key` exists in the array.
|
//! \~english Checks whether the map contains key `key`.
|
||||||
//! \~russian Проверяет наличие элемента с ключом `key` в массиве.
|
//! \~russian Проверяет, содержит ли словарь ключ `key`.
|
||||||
inline bool contains(const Key & key) const {
|
inline bool contains(const Key & key) const {
|
||||||
bool f(false);
|
bool f(false);
|
||||||
_find(key, f);
|
_find(key, f);
|
||||||
return f;
|
return f;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Tests if element with value `value` exists in the array.
|
//! \~english Checks whether the map contains value `value`.
|
||||||
//! \~russian Проверяет наличие элемента со значением `value` в массиве.
|
//! \~russian Проверяет, содержит ли словарь значение `value`.
|
||||||
inline bool containsValue(const T & value) const { return pim_content.contains(value); }
|
inline bool containsValue(const T & value) const { return pim_content.contains(value); }
|
||||||
|
|
||||||
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
//! \~english Attempts to allocate memory for at least `new_size` elements.
|
||||||
@@ -403,8 +387,8 @@ public:
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Remove element with key `key` from the array.
|
//! \~english Removes entry with key `key`.
|
||||||
//! \~russian Удаляет элемент с ключом `key` из массива.
|
//! \~russian Удаляет элемент с ключом `key`.
|
||||||
inline PIMap<Key, T> & remove(const Key & key) {
|
inline PIMap<Key, T> & remove(const Key & key) {
|
||||||
bool f(false);
|
bool f(false);
|
||||||
const ssize_t i = _find(key, f);
|
const ssize_t i = _find(key, f);
|
||||||
@@ -413,7 +397,7 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Remove all elements in the array
|
//! \~english Removes all entries
|
||||||
//! passes the test implemented by the provided function `test`.
|
//! passes the test implemented by the provided function `test`.
|
||||||
//! \~russian Удаляет все элементы, удовлетворяющие условию,
|
//! \~russian Удаляет все элементы, удовлетворяющие условию,
|
||||||
//! заданному в передаваемой функции `test`.
|
//! заданному в передаваемой функции `test`.
|
||||||
@@ -433,8 +417,8 @@ public:
|
|||||||
inline PIMap<Key, T> & erase(const Key & key) { return remove(key); }
|
inline PIMap<Key, T> & erase(const Key & key) { return remove(key); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Clear array, remove all elements.
|
//! \~english Clears the map.
|
||||||
//! \~russian Очищает массив, удаляет все элементы.
|
//! \~russian Очищает словарь.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~\note
|
//! \~\note
|
||||||
//! \~english Reserved memory will not be released.
|
//! \~english Reserved memory will not be released.
|
||||||
@@ -446,8 +430,8 @@ public:
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Swaps array `v` other with this array.
|
//! \~english Swaps this map with `other`.
|
||||||
//! \~russian Меняет местами массив `v` с этим массивом.
|
//! \~russian Меняет местами этот словарь и `other`.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english This operation is very fast and never fails.
|
//! \~english This operation is very fast and never fails.
|
||||||
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
|
//! \~russian Эта операция выполняется мгновенно без копирования памяти и никогда не дает сбоев.
|
||||||
@@ -456,8 +440,8 @@ public:
|
|||||||
pim_index.swap(other.pim_index);
|
pim_index.swap(other.pim_index);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Inserts value `value` with key `key` in the array.
|
//! \~english Inserts value `value` for key `key`.
|
||||||
//! \~russian Вставляет значение `value` с ключом `key` в массив.
|
//! \~russian Вставляет значение `value` по ключу `key`.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english If an element with the key `key` already exists, it will be overwritten with the value `value`.
|
//! \~english If an element with the key `key` already exists, it will be overwritten with the value `value`.
|
||||||
//! \~russian Если элемент с ключом `key` уже существует, то он будет перезаписан на значение `value`.
|
//! \~russian Если элемент с ключом `key` уже существует, то он будет перезаписан на значение `value`.
|
||||||
@@ -485,8 +469,8 @@ public:
|
|||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Inserts value `pair` in the array.
|
//! \~english Inserts entry `pair`.
|
||||||
//! \~russian Вставляет пару `pair` в массив.
|
//! \~russian Вставляет элемент `pair`.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english The first element of the pair is the key, and the second is the value.
|
//! \~english The first element of the pair is the key, and the second is the value.
|
||||||
//! \~russian Первый элемент пары является ключом, а второй значением.
|
//! \~russian Первый элемент пары является ключом, а второй значением.
|
||||||
@@ -526,8 +510,8 @@ public:
|
|||||||
return _value(i);
|
return _value(i);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns an array of values of all elements
|
//! \~english Returns values of all map entries.
|
||||||
//! \~russian Возвращает массив значений всех эелметнов
|
//! \~russian Возвращает значения всех элементов словаря.
|
||||||
inline PIVector<T> values() const { return pim_content; }
|
inline PIVector<T> values() const { return pim_content; }
|
||||||
|
|
||||||
//! \~english Returns the key of the first element
|
//! \~english Returns the key of the first element
|
||||||
@@ -544,8 +528,8 @@ public:
|
|||||||
return default_;
|
return default_;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns an array of keys of all elements
|
//! \~english Returns keys of all map entries.
|
||||||
//! \~russian Возвращает массив ключей всех элементов
|
//! \~russian Возвращает ключи всех элементов словаря.
|
||||||
inline PIVector<Key> keys() const {
|
inline PIVector<Key> keys() const {
|
||||||
PIVector<Key> ret;
|
PIVector<Key> ret;
|
||||||
ret.reserve(pim_index.size());
|
ret.reserve(pim_index.size());
|
||||||
@@ -555,8 +539,8 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Execute function `void f(const Key & key, const T & value)` for every element in array.
|
//! \~english Calls `f` for every map entry.
|
||||||
//! \~russian Выполняет функцию `void f(const Key & key, const T & value)` для каждого элемента массива.
|
//! \~russian Вызывает `f` для каждого элемента словаря.
|
||||||
inline void forEach(std::function<void(const Key & key, const T & value)> f) const {
|
inline void forEach(std::function<void(const Key & key, const T & value)> f) const {
|
||||||
for (int i = 0; i < pim_index.size_s(); ++i) {
|
for (int i = 0; i < pim_index.size_s(); ++i) {
|
||||||
const auto & mi(pim_index[i]);
|
const auto & mi(pim_index[i]);
|
||||||
@@ -564,10 +548,8 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Сreates a new map PIMap<Key2, T2> populated with the results
|
//! \~english Creates a new \a PIMap from results of applying `f` to each map entry.
|
||||||
//! of calling a provided function `PIPair<Key2, T2> f(const Key & key, const T & value)` on every element in the calling array.
|
//! \~russian Создает новый \a PIMap из результатов применения `f` к каждому элементу словаря.
|
||||||
//! \~russian Создаёт новый словарь PIMap<Key2, T2> с результатом вызова указанной функции
|
|
||||||
//! `PIPair<Key2, T2> f(const Key & key, const T & value)` для каждого элемента массива.
|
|
||||||
template<typename Key2, typename T2>
|
template<typename Key2, typename T2>
|
||||||
inline PIMap<Key2, T2> map(std::function<PIPair<Key2, T2>(const Key & key, const T & value)> f) const {
|
inline PIMap<Key2, T2> map(std::function<PIPair<Key2, T2>(const Key & key, const T & value)> f) const {
|
||||||
PIMap<Key2, T2> ret;
|
PIMap<Key2, T2> ret;
|
||||||
@@ -579,10 +561,8 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Сreates a new array PIVector<ST> populated with the results
|
//! \~english Creates a new \a PIVector from results of applying `f` to each map entry.
|
||||||
//! of calling a provided function `ST f(const Key & key, const T & value)` on every element in the calling array.
|
//! \~russian Создает новый \a PIVector из результатов применения `f` к каждому элементу словаря.
|
||||||
//! \~russian Создаёт новый массив PIVector<ST> с результатом вызова указанной функции
|
|
||||||
//! `ST f(const Key & key, const T & value)` для каждого элемента массива.
|
|
||||||
template<typename ST>
|
template<typename ST>
|
||||||
inline PIVector<ST> map(std::function<ST(const Key & key, const T & value)> f) const {
|
inline PIVector<ST> map(std::function<ST(const Key & key, const T & value)> f) const {
|
||||||
PIVector<ST> ret;
|
PIVector<ST> ret;
|
||||||
@@ -594,9 +574,9 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns a new array with all elements
|
//! \~english Returns a new map with all entries
|
||||||
//! that pass the test implemented by the provided function `bool test(const Key & key, const T & value)`.
|
//! that pass the test implemented by the provided function `bool test(const Key & key, const T & value)`.
|
||||||
//! \~russian Возвращает новый массив со всеми элементами,
|
//! \~russian Возвращает новый словарь со всеми элементами,
|
||||||
//! прошедшими проверку, задаваемую в передаваемой функции `bool test(const Key & key, const T & value)`.
|
//! прошедшими проверку, задаваемую в передаваемой функции `bool test(const Key & key, const T & value)`.
|
||||||
inline PIMap<Key, T> filter(std::function<bool(const Key & key, const T & value)> test) const {
|
inline PIMap<Key, T> filter(std::function<bool(const Key & key, const T & value)> test) const {
|
||||||
PIMap<Key, T> ret;
|
PIMap<Key, T> ret;
|
||||||
@@ -688,17 +668,17 @@ private:
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIMapIteratorConst
|
//! \class PIMapIteratorConst
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Java-style iterator for \a PIMap.
|
//! \~english Java-style iterator for \a PIMap.
|
||||||
//! \~russian Итератор Java стиля для \a PIMap.
|
//! \~russian Итератор Java стиля для \a PIMap.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! This class used to easy serial access keys and values in PIMap with read only permitions.
|
//! Provides sequential read-only access to keys and values in \a PIMap.
|
||||||
//! Use constructor to create iterator, or use \a PIMap::makeIterator()
|
//! Use the constructor directly or call \a PIMap::makeIterator().
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря только для чтения.
|
//! Используется для последовательного перебора ключей и значений \a PIMap только для чтения.
|
||||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeIterator().
|
//! Можно использовать конструктор или вызвать \a PIMap::makeIterator().
|
||||||
//! \~
|
//! \~
|
||||||
//! \code
|
//! \code
|
||||||
//! PIMap<int, PIString> m;
|
//! PIMap<int, PIString> m;
|
||||||
@@ -758,17 +738,17 @@ private:
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIMapIteratorConstReverse
|
//! \class PIMapIteratorConstReverse
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Java-style reverse iterator for \a PIMap.
|
//! \~english Java-style reverse iterator for \a PIMap.
|
||||||
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! This class used to easy serial reverse access keys and values in PIMap with read only permitions.
|
//! Provides sequential reverse read-only access to keys and values in \a PIMap.
|
||||||
//! Use constructor to create iterator, or use \a PIMap::makeReverseIterator().
|
//! Use the constructor directly or call \a PIMap::makeReverseIterator().
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря в обратном порядке только для чтения.
|
//! Используется для последовательного обратного перебора ключей и значений \a PIMap только для чтения.
|
||||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeReverseIterator().
|
//! Можно использовать конструктор или вызвать \a PIMap::makeReverseIterator().
|
||||||
//! \~
|
//! \~
|
||||||
//! \code
|
//! \code
|
||||||
//! PIMap<int, PIString> m;
|
//! PIMap<int, PIString> m;
|
||||||
@@ -827,17 +807,17 @@ private:
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIMapIterator
|
//! \class PIMapIterator
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Java-style iterator for \a PIMap.
|
//! \~english Java-style iterator for \a PIMap.
|
||||||
//! \~russian Итератор Java стиля для \a PIMap.
|
//! \~russian Итератор Java стиля для \a PIMap.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! This class used to easy serial access keys and values in PIMap with write permitions.
|
//! Provides sequential access to keys and values in \a PIMap with write access to values.
|
||||||
//! Use constructor to create iterator, or use \a PIMap::makeIterator()
|
//! Use the constructor directly or call \a PIMap::makeIterator().
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря с доступом на запись.
|
//! Используется для последовательного перебора ключей и значений \a PIMap с доступом на запись.
|
||||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeIterator().
|
//! Можно использовать конструктор или вызвать \a PIMap::makeIterator().
|
||||||
//! \~
|
//! \~
|
||||||
//! \code
|
//! \code
|
||||||
//! PIMap<int, PIString> m;
|
//! PIMap<int, PIString> m;
|
||||||
@@ -897,17 +877,17 @@ private:
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIMapIteratorReverse
|
//! \class PIMapIteratorReverse
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Java-style reverse iterator for \a PIMap.
|
//! \~english Java-style reverse iterator for \a PIMap.
|
||||||
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
//! \~russian Итератор Java стиля для \a PIMap в обратном порядке.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! This class used to easy serial reverse access keys and values in PIMap with write permitions.
|
//! Provides sequential reverse access to keys and values in \a PIMap with write access to values.
|
||||||
//! Use constructor to create iterator, or use \a PIMap::makeReverseIterator().
|
//! Use the constructor directly or call \a PIMap::makeReverseIterator().
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Этот класс используется для удобного перебора ключей и значений всего словаря в обратном порядке с доступом на запись.
|
//! Используется для последовательного обратного перебора ключей и значений \a PIMap с доступом на запись.
|
||||||
//! Можно использовать конструктор, в который передаётся словарь, или функцию словаря \a PIMap::makeReverseIterator().
|
//! Можно использовать конструктор или вызвать \a PIMap::makeReverseIterator().
|
||||||
//! \~
|
//! \~
|
||||||
//! \code
|
//! \code
|
||||||
//! PIMap<int, PIString> m;
|
//! PIMap<int, PIString> m;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file pipair.h
|
//! \~\file pipair.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Declares \a PIPair
|
//! \~english Declares \a PIPair
|
||||||
//! \~russian Объявление \a PIPair
|
//! \~russian Объявление \a PIPair
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file piqueue.h
|
//! \~\file piqueue.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Declares \a PIQueue
|
//! \~english Declares \a PIQueue
|
||||||
//! \~russian Объявление \a PIQueue
|
//! \~russian Объявление \a PIQueue
|
||||||
@@ -40,78 +40,76 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \class PIQueue
|
//! \class PIQueue
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english A container class inherited from the \a PIDeque with queue functionality.
|
//! \~english Queue container built on top of \a PIDeque.
|
||||||
//! \~russian Класс контейнера наследованый от \a PIDeque с функциональностью очереди.
|
//! \~russian Контейнер очереди, построенный поверх \a PIDeque.
|
||||||
//! \~\}
|
//! \~\}
|
||||||
//! \details
|
//! \details
|
||||||
//! \~english The container is a array of elements organized according to the FIFO principle (first in, first out).
|
//! \~english Stores elements in FIFO order and adds \a enqueue() and \a dequeue() to \a PIDeque.
|
||||||
//! Adds \a enqueue() and \dequeue() functions to \a PIDeque.
|
//! \~russian Хранит элементы в порядке FIFO и добавляет к \a PIDeque функции \a enqueue() и \a dequeue().
|
||||||
//! \~russian Контейнер представляющий массив элементов, организованных по принципу FIFO (первым пришёл — первым вышел).
|
|
||||||
//! Добавляет к \a PIDeque функции \a enqueue() и \a dequeue().
|
|
||||||
//! \~\sa \a PIDeque
|
//! \~\sa \a PIDeque
|
||||||
template<typename T>
|
template<typename T>
|
||||||
class PIQueue: public PIDeque<T> {
|
class PIQueue: public PIDeque<T> {
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs an empty array.
|
//! \~english Constructs an empty queue.
|
||||||
//! \~russian Создает пустой массив.
|
//! \~russian Создает пустую очередь.
|
||||||
PIQueue() {}
|
PIQueue() {}
|
||||||
|
|
||||||
//! \~english Puts an element on the queue.
|
//! \~english Enqueues `v`.
|
||||||
//! \~russian Кладёт элемент в очередь.
|
//! \~russian Добавляет `v` в очередь.
|
||||||
PIDeque<T> & enqueue(const T & v) {
|
PIDeque<T> & enqueue(const T & v) {
|
||||||
PIDeque<T>::push_front(v);
|
PIDeque<T>::push_front(v);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Move an element on the queue.
|
//! \~english Moves `v` into the queue.
|
||||||
//! \~russian Перемещает элемент в очередь.
|
//! \~russian Перемещает `v` в очередь.
|
||||||
PIDeque<T> & enqueue(T && v) {
|
PIDeque<T> & enqueue(T && v) {
|
||||||
PIDeque<T>::push_front(std::move(v));
|
PIDeque<T>::push_front(std::move(v));
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Retrieves and returns an element from the queue.
|
//! \~english Dequeues and returns the head element.
|
||||||
//! \~russian Забирает и возвращает элемент из очереди.
|
//! \~russian Извлекает и возвращает головной элемент очереди.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \note
|
//! \note
|
||||||
//! \~english This function assumes that the array isn't empty.
|
//! \~english This function assumes that the queue is not empty.
|
||||||
//! Otherwise will be undefined behavior.
|
//! Otherwise behavior is undefined.
|
||||||
//! \~russian Эта функция предполагает, что массив не пустой.
|
//! \~russian Эта функция предполагает, что очередь не пуста.
|
||||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||||
T dequeue() { return PIDeque<T>::take_back(); }
|
T dequeue() { return PIDeque<T>::take_back(); }
|
||||||
|
|
||||||
//! \~english Head element of the queue.
|
//! \~english Returns the head element.
|
||||||
//! \~russian Головной (верхний) элемент очереди.
|
//! \~russian Возвращает головной элемент очереди.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \note
|
//! \note
|
||||||
//! \~english Returns a reference to the head element of the queue.
|
//! \~english Returns a reference to the head element.
|
||||||
//! This function assumes that the array isn't empty.
|
//! This function assumes that the queue is not empty.
|
||||||
//! Otherwise will be undefined behavior.
|
//! Otherwise behavior is undefined.
|
||||||
//! \~russian Возвращает ссылку на головной (верхний) элемент очереди.
|
//! \~russian Возвращает ссылку на головной элемент очереди.
|
||||||
//! Эта функция предполагает, что массив не пустой.
|
//! Эта функция предполагает, что очередь не пуста.
|
||||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||||
T & head() { return PIDeque<T>::back(); }
|
T & head() { return PIDeque<T>::back(); }
|
||||||
const T & head() const { return PIDeque<T>::back(); }
|
const T & head() const { return PIDeque<T>::back(); }
|
||||||
|
|
||||||
//! \~english Tail element of the queue.
|
//! \~english Returns the tail element.
|
||||||
//! \~russian Хвостовой (нижний) элемент очереди.
|
//! \~russian Возвращает хвостовой элемент очереди.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english Returns a reference to the tail element of the queue.
|
//! \~english Returns a reference to the tail element.
|
||||||
//! This function assumes that the array isn't empty.
|
//! This function assumes that the queue is not empty.
|
||||||
//! Otherwise will be undefined behavior.
|
//! Otherwise behavior is undefined.
|
||||||
//! \~russian Возвращает ссылку на хвостовой (нижний) элемент очереди.
|
//! \~russian Возвращает ссылку на хвостовой элемент очереди.
|
||||||
//! Эта функция предполагает, что массив не пустой.
|
//! Эта функция предполагает, что очередь не пуста.
|
||||||
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
//! Иначе это приведёт к неопределённому поведению программы и ошибкам памяти.
|
||||||
T & tail() { return PIDeque<T>::front(); }
|
T & tail() { return PIDeque<T>::front(); }
|
||||||
const T & tail() const { return PIDeque<T>::front(); }
|
const T & tail() const { return PIDeque<T>::front(); }
|
||||||
|
|
||||||
//! \~english Converts \a PIQueue to \a PIVector.
|
//! \~english Returns queue contents as \a PIVector.
|
||||||
//! \~russian Преобразует \a PIQueue в \a PIVector.
|
//! \~russian Возвращает содержимое очереди в виде \a PIVector.
|
||||||
PIVector<T> toVector() const { return PIVector<T>(PIDeque<T>::data(), PIDeque<T>::size()); }
|
PIVector<T> toVector() const { return PIVector<T>(PIDeque<T>::data(), PIDeque<T>::size()); }
|
||||||
|
|
||||||
//! \~english Converts \a PIQueue to \a PIDeque.
|
//! \~english Returns queue contents as \a PIDeque.
|
||||||
//! \~russian Преобразует \a PIQueue в \a PIDeque.
|
//! \~russian Возвращает содержимое очереди в виде \a PIDeque.
|
||||||
PIDeque<T> toDeque() const { return PIDeque<T>(*this); }
|
PIDeque<T> toDeque() const { return PIDeque<T>(*this); }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,10 @@
|
|||||||
/*! \file piset.h
|
//! \addtogroup Containers
|
||||||
* \brief Set container
|
//! \{
|
||||||
*
|
//! \~\file piset.h
|
||||||
* This file declare PISet
|
//! \~\brief
|
||||||
*/
|
//! \~english Declares \a PISet
|
||||||
|
//! \~russian Объявление \a PISet
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Set container
|
Set container
|
||||||
@@ -27,13 +29,33 @@
|
|||||||
|
|
||||||
#include "pimap.h"
|
#include "pimap.h"
|
||||||
|
|
||||||
/*! \brief Set of any type
|
//! \addtogroup Containers
|
||||||
* \details This class used to store collection of unique elements
|
//! \{
|
||||||
* of any type. You can only add values to set with \a operator<< or
|
//! \class PISet
|
||||||
* with function \a insert(). You can discover if value already in
|
//! \~\brief
|
||||||
* set with \a operator[] or with function \a find(). These function
|
//! \~english Set of unique values.
|
||||||
* has logarithmic complexity.
|
//! \~russian Множество уникальных значений.
|
||||||
*/
|
//! \~\}
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! This class is used to store a collection of unique elements of any type.
|
||||||
|
//! You can add values to the set using \a operator<< or the \a insert() function.
|
||||||
|
//! You can check if a value already exists in the set using \a operator[] or the \a contains() function.
|
||||||
|
//! These operations have logarithmic complexity.
|
||||||
|
//! To iterate over all elements, use STL-style iterators \a begin() and \a end().
|
||||||
|
//!
|
||||||
|
//! The set is implemented as a wrapper around \a PIMap, where keys are the elements
|
||||||
|
//! and values are dummy byte values (used only for storage).
|
||||||
|
//! \~russian
|
||||||
|
//! Этот класс используется для хранения коллекции уникальных элементов любого типа.
|
||||||
|
//! Вы можете добавлять значения в множество с помощью \a operator<< или функции \a insert().
|
||||||
|
//! Вы можете проверить, существует ли значение в множестве, используя \a operator[] или функцию \a contains().
|
||||||
|
//! Эти операции имеют логарифмическую сложность.
|
||||||
|
//! Для перебора всех элементов используйте итераторы в стиле STL \a begin() и \a end().
|
||||||
|
//!
|
||||||
|
//! Множество реализовано как обёртка над \a PIMap, где ключами являются элементы,
|
||||||
|
//! а значениями являются фиктивные байтовые значения (используются только для хранения).
|
||||||
|
//! \~\sa \a PIMap, \a PIVector
|
||||||
template<typename T>
|
template<typename T>
|
||||||
class PISet: public PIMap<T, uchar> {
|
class PISet: public PIMap<T, uchar> {
|
||||||
typedef PIMap<T, uchar> _CSet;
|
typedef PIMap<T, uchar> _CSet;
|
||||||
@@ -43,26 +65,31 @@ class PISet: public PIMap<T, uchar> {
|
|||||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PISet<T1> & v);
|
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PISet<T1> & v);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! Contructs an empty set
|
//! \~english Constructs an empty set.
|
||||||
|
//! \~russian Создает пустое множество.
|
||||||
PISet() {}
|
PISet() {}
|
||||||
|
|
||||||
//! Contructs set with one element "value"
|
//! \~english Constructs a set containing `value`.
|
||||||
|
//! \~russian Создает множество, содержащее `value`.
|
||||||
explicit PISet(const T & value) { _CSet::insert(value, 0); }
|
explicit PISet(const T & value) { _CSet::insert(value, 0); }
|
||||||
|
|
||||||
//! Contructs set with elements "v0" and "v1"
|
//! \~english Constructs a set containing `v0` and `v1`.
|
||||||
|
//! \~russian Создает множество, содержащее `v0` и `v1`.
|
||||||
PISet(const T & v0, const T & v1) {
|
PISet(const T & v0, const T & v1) {
|
||||||
_CSet::insert(v0, 0);
|
_CSet::insert(v0, 0);
|
||||||
_CSet::insert(v1, 0);
|
_CSet::insert(v1, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Contructs set with elements "v0", "v1" and "v2"
|
//! \~english Constructs a set containing `v0`, `v1` and `v2`.
|
||||||
|
//! \~russian Создает множество, содержащее `v0`, `v1` и `v2`.
|
||||||
PISet(const T & v0, const T & v1, const T & v2) {
|
PISet(const T & v0, const T & v1, const T & v2) {
|
||||||
_CSet::insert(v0, 0);
|
_CSet::insert(v0, 0);
|
||||||
_CSet::insert(v1, 0);
|
_CSet::insert(v1, 0);
|
||||||
_CSet::insert(v2, 0);
|
_CSet::insert(v2, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Contructs set with elements "v0", "v1", "v2" and "v3"
|
//! \~english Constructs a set containing `v0`, `v1`, `v2` and `v3`.
|
||||||
|
//! \~russian Создает множество, содержащее `v0`, `v1`, `v2` и `v3`.
|
||||||
PISet(const T & v0, const T & v1, const T & v2, const T & v3) {
|
PISet(const T & v0, const T & v1, const T & v2, const T & v3) {
|
||||||
_CSet::insert(v0, 0);
|
_CSet::insert(v0, 0);
|
||||||
_CSet::insert(v1, 0);
|
_CSet::insert(v1, 0);
|
||||||
@@ -71,6 +98,9 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Constant iterator over \a PISet elements.
|
||||||
|
//! \~russian Константный итератор по элементам \a PISet.
|
||||||
class const_iterator {
|
class const_iterator {
|
||||||
friend class PISet<T>;
|
friend class PISet<T>;
|
||||||
|
|
||||||
@@ -86,75 +116,140 @@ public:
|
|||||||
typedef std::ptrdiff_t difference_type;
|
typedef std::ptrdiff_t difference_type;
|
||||||
typedef std::random_access_iterator_tag iterator_category;
|
typedef std::random_access_iterator_tag iterator_category;
|
||||||
|
|
||||||
|
//! \~english Constructs an invalid iterator.
|
||||||
|
//! \~russian Создает недействительный итератор.
|
||||||
inline const_iterator(): parent(0), pos(0) {}
|
inline const_iterator(): parent(0), pos(0) {}
|
||||||
|
|
||||||
|
//! \~english Returns the current element.
|
||||||
|
//! \~russian Возвращает текущий элемент.
|
||||||
inline const T & operator*() const { return parent->pim_index[pos].key; }
|
inline const T & operator*() const { return parent->pim_index[pos].key; }
|
||||||
|
|
||||||
|
//! \~english Provides access to the current element.
|
||||||
|
//! \~russian Предоставляет доступ к текущему элементу.
|
||||||
inline const T & operator->() const { return parent->pim_index[pos].key; }
|
inline const T & operator->() const { return parent->pim_index[pos].key; }
|
||||||
|
|
||||||
|
//! \~english Moves iterator to the next element.
|
||||||
|
//! \~russian Перемещает итератор к следующему элементу.
|
||||||
inline const_iterator & operator++() {
|
inline const_iterator & operator++() {
|
||||||
++pos;
|
++pos;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns iterator before incrementing.
|
||||||
|
//! \~russian Возвращает итератор до увеличения.
|
||||||
inline const_iterator operator++(int) {
|
inline const_iterator operator++(int) {
|
||||||
const auto tmp = *this;
|
const auto tmp = *this;
|
||||||
++*this;
|
++*this;
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Moves iterator to the previous element.
|
||||||
|
//! \~russian Перемещает итератор к предыдущему элементу.
|
||||||
inline const_iterator & operator--() {
|
inline const_iterator & operator--() {
|
||||||
--pos;
|
--pos;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns iterator before decrementing.
|
||||||
|
//! \~russian Возвращает итератор до уменьшения.
|
||||||
inline const_iterator operator--(int) {
|
inline const_iterator operator--(int) {
|
||||||
const auto tmp = *this;
|
const auto tmp = *this;
|
||||||
--*this;
|
--*this;
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Adds offset of iterator `it`.
|
||||||
|
//! \~russian Добавляет смещение итератора `it`.
|
||||||
inline const_iterator & operator+=(const const_iterator & it) {
|
inline const_iterator & operator+=(const const_iterator & it) {
|
||||||
pos += it.pos;
|
pos += it.pos;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Advances iterator by `p` elements.
|
||||||
|
//! \~russian Сдвигает итератор вперед на `p` элементов.
|
||||||
inline const_iterator & operator+=(size_t p) {
|
inline const_iterator & operator+=(size_t p) {
|
||||||
pos += p;
|
pos += p;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Subtracts offset of iterator `it`.
|
||||||
|
//! \~russian Вычитает смещение итератора `it`.
|
||||||
inline const_iterator & operator-=(const const_iterator & it) {
|
inline const_iterator & operator-=(const const_iterator & it) {
|
||||||
pos -= it.pos;
|
pos -= it.pos;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Moves iterator back by `p` elements.
|
||||||
|
//! \~russian Сдвигает итератор назад на `p` элементов.
|
||||||
inline const_iterator & operator-=(size_t p) {
|
inline const_iterator & operator-=(size_t p) {
|
||||||
pos -= p;
|
pos -= p;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns iterator shifted back by `p`.
|
||||||
|
//! \~russian Возвращает итератор, сдвинутый назад на `p`.
|
||||||
friend inline const_iterator operator-(size_t p, const const_iterator & it) { return it - p; }
|
friend inline const_iterator operator-(size_t p, const const_iterator & it) { return it - p; }
|
||||||
|
|
||||||
|
//! \~english Returns iterator shifted back by `p`.
|
||||||
|
//! \~russian Возвращает итератор, сдвинутый назад на `p`.
|
||||||
friend inline const_iterator operator-(const const_iterator & it, size_t p) {
|
friend inline const_iterator operator-(const const_iterator & it, size_t p) {
|
||||||
auto tmp = it;
|
auto tmp = it;
|
||||||
tmp -= p;
|
tmp -= p;
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns distance between iterators.
|
||||||
|
//! \~russian Возвращает расстояние между итераторами.
|
||||||
friend inline std::ptrdiff_t operator-(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; }
|
friend inline std::ptrdiff_t operator-(const const_iterator & it1, const const_iterator & it2) { return it1.pos - it2.pos; }
|
||||||
|
|
||||||
|
//! \~english Returns iterator shifted forward by `p`.
|
||||||
|
//! \~russian Возвращает итератор, сдвинутый вперед на `p`.
|
||||||
friend inline const_iterator operator+(size_t p, const const_iterator & it) { return it + p; }
|
friend inline const_iterator operator+(size_t p, const const_iterator & it) { return it + p; }
|
||||||
|
|
||||||
|
//! \~english Returns iterator shifted forward by `p`.
|
||||||
|
//! \~russian Возвращает итератор, сдвинутый вперед на `p`.
|
||||||
friend inline const_iterator operator+(const const_iterator & it, size_t p) {
|
friend inline const_iterator operator+(const const_iterator & it, size_t p) {
|
||||||
auto tmp = it;
|
auto tmp = it;
|
||||||
tmp += p;
|
tmp += p;
|
||||||
return tmp;
|
return tmp;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Checks iterator equality.
|
||||||
|
//! \~russian Проверяет равенство итераторов.
|
||||||
inline bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
inline bool operator==(const const_iterator & it) const { return (pos == it.pos); }
|
||||||
|
|
||||||
|
//! \~english Checks iterator inequality.
|
||||||
|
//! \~russian Проверяет неравенство итераторов.
|
||||||
inline bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
inline bool operator!=(const const_iterator & it) const { return (pos != it.pos); }
|
||||||
|
|
||||||
|
//! \~english Checks whether `it1` is before `it2`.
|
||||||
|
//! \~russian Проверяет, находится ли `it1` перед `it2`.
|
||||||
friend inline bool operator<(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; }
|
friend inline bool operator<(const const_iterator & it1, const const_iterator & it2) { return it1.pos < it2.pos; }
|
||||||
|
|
||||||
|
//! \~english Checks whether `it1` is before or equal to `it2`.
|
||||||
|
//! \~russian Проверяет, находится ли `it1` перед `it2` или совпадает с ним.
|
||||||
friend inline bool operator<=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; }
|
friend inline bool operator<=(const const_iterator & it1, const const_iterator & it2) { return it1.pos <= it2.pos; }
|
||||||
|
|
||||||
|
//! \~english Checks whether `it1` is after `it2`.
|
||||||
|
//! \~russian Проверяет, находится ли `it1` после `it2`.
|
||||||
friend inline bool operator>(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; }
|
friend inline bool operator>(const const_iterator & it1, const const_iterator & it2) { return it1.pos > it2.pos; }
|
||||||
|
|
||||||
|
//! \~english Checks whether `it1` is after or equal to `it2`.
|
||||||
|
//! \~russian Проверяет, находится ли `it1` после `it2` или совпадает с ним.
|
||||||
friend inline bool operator>=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; }
|
friend inline bool operator>=(const const_iterator & it1, const const_iterator & it2) { return it1.pos >= it2.pos; }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns iterator to the first element.
|
||||||
|
//! \~russian Возвращает итератор на первый элемент.
|
||||||
inline const_iterator begin() const { return const_iterator(this, 0); }
|
inline const_iterator begin() const { return const_iterator(this, 0); }
|
||||||
|
|
||||||
|
//! \~english Returns iterator following the last element.
|
||||||
|
//! \~russian Возвращает итератор на элемент, следующий за последним.
|
||||||
inline const_iterator end() const { return const_iterator(this, _CSet::size()); }
|
inline const_iterator end() const { return const_iterator(this, _CSet::size()); }
|
||||||
|
|
||||||
//! Contructs set from vector of elements
|
//! \~english Constructs a set from vector `values`.
|
||||||
|
//! \~russian Создает множество из вектора `values`.
|
||||||
explicit PISet(const PIVector<T> & values) {
|
explicit PISet(const PIVector<T> & values) {
|
||||||
if (values.isEmpty()) return;
|
if (values.isEmpty()) return;
|
||||||
for (int i = 0; i < values.size_s(); ++i) {
|
for (int i = 0; i < values.size_s(); ++i) {
|
||||||
@@ -162,7 +257,8 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Contructs set from deque of elements
|
//! \~english Constructs a set from deque `values`.
|
||||||
|
//! \~russian Создает множество из дека `values`.
|
||||||
explicit PISet(const PIDeque<T> & values) {
|
explicit PISet(const PIDeque<T> & values) {
|
||||||
if (values.isEmpty()) return;
|
if (values.isEmpty()) return;
|
||||||
for (int i = 0; i < values.size_s(); ++i) {
|
for (int i = 0; i < values.size_s(); ++i) {
|
||||||
@@ -172,65 +268,83 @@ public:
|
|||||||
|
|
||||||
typedef T key_type;
|
typedef T key_type;
|
||||||
|
|
||||||
|
//! \~english Inserts `t` into the set.
|
||||||
|
//! \~russian Добавляет `t` в множество.
|
||||||
PISet<T> & operator<<(const T & t) {
|
PISet<T> & operator<<(const T & t) {
|
||||||
_CSet::insert(t, 0);
|
_CSet::insert(t, 0);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Moves `t` into the set.
|
||||||
|
//! \~russian Перемещает `t` в множество.
|
||||||
PISet<T> & operator<<(T && t) {
|
PISet<T> & operator<<(T && t) {
|
||||||
_CSet::insert(std::move(t), 0);
|
_CSet::insert(std::move(t), 0);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Inserts all elements from `other`.
|
||||||
|
//! \~russian Добавляет все элементы из `other`.
|
||||||
PISet<T> & operator<<(const PISet<T> & other) {
|
PISet<T> & operator<<(const PISet<T> & other) {
|
||||||
(*(_CSet *)this) << *((_CSet *)&other);
|
(*(_CSet *)this) << *((_CSet *)&other);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Tests if element `key` exists in the set.
|
//! \~english Tests whether element `t` exists in the set.
|
||||||
//! \~russian Проверяет наличие элемента `key` в массиве.
|
//! \~russian Проверяет наличие элемента `t` в множестве.
|
||||||
inline bool contains(const T & t) const { return _CSet::contains(t); }
|
inline bool contains(const T & t) const { return _CSet::contains(t); }
|
||||||
|
|
||||||
//! Returns if element "t" exists in this set
|
//! \~english Checks whether element `t` exists in the set.
|
||||||
|
//! \~russian Проверяет наличие элемента `t` в множестве.
|
||||||
bool operator[](const T & t) const { return _CSet::contains(t); }
|
bool operator[](const T & t) const { return _CSet::contains(t); }
|
||||||
|
|
||||||
//! Returns if element "t" exists in this set
|
//! \~english Removes element `t` from the set.
|
||||||
|
//! \~russian Удаляет элемент `t` из множества.
|
||||||
PISet<T> & remove(const T & t) {
|
PISet<T> & remove(const T & t) {
|
||||||
_CSet::remove(t);
|
_CSet::remove(t);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Unite set with "v"
|
//! \~english Unites the set with `v`.
|
||||||
|
//! \~russian Объединяет множество с `v`.
|
||||||
PISet<T> & unite(const PISet<T> & v) {
|
PISet<T> & unite(const PISet<T> & v) {
|
||||||
for (const auto & i: v)
|
for (const auto & i: v)
|
||||||
_CSet::insert(i, 0);
|
_CSet::insert(i, 0);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Subtract set with "v"
|
//! \~english Removes all elements present in `v`.
|
||||||
|
//! \~russian Удаляет все элементы, присутствующие в `v`.
|
||||||
PISet<T> & subtract(const PISet<T> & v) {
|
PISet<T> & subtract(const PISet<T> & v) {
|
||||||
for (const auto & i: v)
|
for (const auto & i: v)
|
||||||
_CSet::remove(i);
|
_CSet::remove(i);
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Intersect set with "v"
|
//! \~english Leaves only elements also present in `v`.
|
||||||
|
//! \~russian Оставляет только элементы, которые есть и в `v`.
|
||||||
PISet<T> & intersect(const PISet<T> & v) {
|
PISet<T> & intersect(const PISet<T> & v) {
|
||||||
_CSet::removeWhere([&v](const T & k, uchar) { return !v.contains(k); });
|
_CSet::removeWhere([&v](const T & k, uchar) { return !v.contains(k); });
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Unite set with "v"
|
//! \~english Same as \a unite().
|
||||||
|
//! \~russian Синоним \a unite().
|
||||||
PISet<T> & operator+=(const PISet<T> & v) { return unite(v); }
|
PISet<T> & operator+=(const PISet<T> & v) { return unite(v); }
|
||||||
|
|
||||||
//! Unite set with "v"
|
//! \~english Same as \a unite().
|
||||||
|
//! \~russian Синоним \a unite().
|
||||||
PISet<T> & operator|=(const PISet<T> & v) { return unite(v); }
|
PISet<T> & operator|=(const PISet<T> & v) { return unite(v); }
|
||||||
|
|
||||||
//! Subtract set with "v"
|
//! \~english Same as \a subtract().
|
||||||
|
//! \~russian Синоним \a subtract().
|
||||||
PISet<T> & operator-=(const PISet<T> & v) { return subtract(v); }
|
PISet<T> & operator-=(const PISet<T> & v) { return subtract(v); }
|
||||||
|
|
||||||
//! Intersect set with "v"
|
//! \~english Same as \a intersect().
|
||||||
|
//! \~russian Синоним \a intersect().
|
||||||
PISet<T> & operator&=(const PISet<T> & v) { return intersect(v); }
|
PISet<T> & operator&=(const PISet<T> & v) { return intersect(v); }
|
||||||
|
|
||||||
//! Returns content of set as PIVector
|
//! \~english Returns set contents as \a PIVector.
|
||||||
|
//! \~russian Возвращает содержимое множества в виде \a PIVector.
|
||||||
PIVector<T> toVector() const {
|
PIVector<T> toVector() const {
|
||||||
PIVector<T> ret;
|
PIVector<T> ret;
|
||||||
for (const auto & i: *this)
|
for (const auto & i: *this)
|
||||||
@@ -238,7 +352,8 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns content of set as PIDeque
|
//! \~english Returns set contents as \a PIDeque.
|
||||||
|
//! \~russian Возвращает содержимое множества в виде \a PIDeque.
|
||||||
PIDeque<T> toDeque() const {
|
PIDeque<T> toDeque() const {
|
||||||
PIDeque<T> ret;
|
PIDeque<T> ret;
|
||||||
for (const auto & i: *this)
|
for (const auto & i: *this)
|
||||||
@@ -248,7 +363,9 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \relatesalso PISet \brief Returns unite of two sets
|
//! \relatesalso PISet
|
||||||
|
//! \~english Returns union of two sets.
|
||||||
|
//! \~russian Возвращает объединение двух множеств.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
||||||
PISet<T> ret(v0);
|
PISet<T> ret(v0);
|
||||||
@@ -256,7 +373,9 @@ PISet<T> operator+(const PISet<T> & v0, const PISet<T> & v1) {
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \relatesalso PISet \brief Returns subtraction of two sets
|
//! \relatesalso PISet
|
||||||
|
//! \~english Returns difference of two sets.
|
||||||
|
//! \~russian Возвращает разность двух множеств.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
||||||
PISet<T> ret(v0);
|
PISet<T> ret(v0);
|
||||||
@@ -264,7 +383,9 @@ PISet<T> operator-(const PISet<T> & v0, const PISet<T> & v1) {
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \relatesalso PISet \brief Returns unite of two sets
|
//! \relatesalso PISet
|
||||||
|
//! \~english Returns union of two sets.
|
||||||
|
//! \~russian Возвращает объединение двух множеств.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
||||||
PISet<T> ret(v0);
|
PISet<T> ret(v0);
|
||||||
@@ -272,7 +393,9 @@ PISet<T> operator|(const PISet<T> & v0, const PISet<T> & v1) {
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \relatesalso PISet \brief Returns intersetion of two sets
|
//! \relatesalso PISet
|
||||||
|
//! \~english Returns intersection of two sets.
|
||||||
|
//! \~russian Возвращает пересечение двух множеств.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
||||||
PISet<T> ret(v0);
|
PISet<T> ret(v0);
|
||||||
@@ -281,6 +404,9 @@ PISet<T> operator&(const PISet<T> & v0, const PISet<T> & v1) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \relatesalso PISet
|
||||||
|
//! \~english Output operator to \a PICout.
|
||||||
|
//! \~russian Оператор вывода в \a PICout.
|
||||||
template<typename Type>
|
template<typename Type>
|
||||||
inline PICout operator<<(PICout s, const PISet<Type> & v) {
|
inline PICout operator<<(PICout s, const PISet<Type> & v) {
|
||||||
s.space();
|
s.space();
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file pistack.h
|
//! \~\file pistack.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Declares \a PIStack
|
//! \~english Declares \a PIStack
|
||||||
//! \~russian Объявление \a PIStack
|
//! \~russian Объявление \a PIStack
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
//! \addtogroup Containers
|
//! \addtogroup Containers
|
||||||
//! \{
|
//! \{
|
||||||
//! \file pivector.h
|
//! \~\file pivector.h
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Declares \a PIVector
|
//! \~english Declares \a PIVector
|
||||||
//! \~russian Объявление \a PIVector
|
//! \~russian Объявление \a PIVector
|
||||||
|
|||||||
@@ -1,8 +1,15 @@
|
|||||||
/*! \file pivector2d.h
|
//! \addtogroup Containers
|
||||||
* \brief 2D wrapper around PIVector
|
//! \{
|
||||||
*
|
//! \~\file pivector2d.h
|
||||||
* This file declares PIVector2D
|
//! \brief
|
||||||
*/
|
//! \~english Declares \a PIVector2D
|
||||||
|
//! \~russian Объявление \a PIVector2D
|
||||||
|
//! \~\authors
|
||||||
|
//! \~english
|
||||||
|
//! Andrey Bychkov work.a.b@yandex.ru;
|
||||||
|
//! \~russian
|
||||||
|
//! Андрей Бычков work.a.b@yandex.ru;
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
2D wrapper around PIVector
|
2D wrapper around PIVector
|
||||||
|
|||||||
@@ -1,17 +1,17 @@
|
|||||||
/*! \file pibase.h
|
//! \addtogroup Core
|
||||||
* \ingroup Core
|
//! \{
|
||||||
* \~\brief
|
//! \~\file pibase.h
|
||||||
* \~english Base types and functions
|
//! \brief
|
||||||
* \~russian Базовые типы и методы
|
//! \~english Base types and functions
|
||||||
*
|
//! \~russian Базовые типы и методы
|
||||||
* \~\details
|
//! \details
|
||||||
* \~english
|
//! \~english
|
||||||
* This file implements first layer above the system and
|
//! This file implements first layer above the system and
|
||||||
* declares some basic useful functions
|
//! declares some basic useful functions
|
||||||
* \~russian
|
//! \~russian
|
||||||
* Этот файл реализует первый слой после системы и объявляет
|
//! Этот файл реализует первый слой после системы и объявляет
|
||||||
* несколько базовых полезных методов
|
//! несколько базовых полезных методов
|
||||||
*/
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Base types and functions
|
Base types and functions
|
||||||
@@ -245,6 +245,9 @@ inline constexpr T piAbs(const T & v) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Templated function return minimum of two values
|
||||||
|
//! \~russian Шаблонный метод, возвращающий минимум из двух значений
|
||||||
template<typename T>
|
template<typename T>
|
||||||
constexpr T piMin(const T & f, const T & s) {
|
constexpr T piMin(const T & f, const T & s) {
|
||||||
return ((f > s) ? s : f);
|
return ((f > s) ? s : f);
|
||||||
@@ -282,6 +285,9 @@ constexpr T piMin(const T & f, const T & s, const Args &... args) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Templated function return maximum of two values
|
||||||
|
//! \~russian Шаблонный метод, возвращающий максимум из двух значений
|
||||||
template<typename T>
|
template<typename T>
|
||||||
constexpr T piMax(const T & f, const T & s) {
|
constexpr T piMax(const T & f, const T & s) {
|
||||||
return ((f < s) ? s : f);
|
return ((f < s) ? s : f);
|
||||||
@@ -509,51 +515,87 @@ inline uint piHashData(const uchar * data, uint len, uint seed = 0) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Generic hash function, returns 0 for unknown types
|
||||||
|
//! \~russian Хэш-функция общего назначения, возвращает 0 для неизвестных типов
|
||||||
template<typename T>
|
template<typename T>
|
||||||
inline uint piHash(const T & v) {
|
inline uint piHash(const T & v) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for char type
|
||||||
|
//! \~russian Специализация хэш-функции для типа char
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const char & v) {
|
inline uint piHash(const char & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for uchar type
|
||||||
|
//! \~russian Специализация хэш-функции для типа uchar
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const uchar & v) {
|
inline uint piHash(const uchar & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for short type
|
||||||
|
//! \~russian Специализация хэш-функции для типа short
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const short & v) {
|
inline uint piHash(const short & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for ushort type
|
||||||
|
//! \~russian Специализация хэш-функции для типа ushort
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const ushort & v) {
|
inline uint piHash(const ushort & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for int type
|
||||||
|
//! \~russian Специализация хэш-функции для типа int
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const int & v) {
|
inline uint piHash(const int & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for uint type
|
||||||
|
//! \~russian Специализация хэш-функции для типа uint
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const uint & v) {
|
inline uint piHash(const uint & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for llong type using piHashData
|
||||||
|
//! \~russian Специализация хэш-функции для типа llong с использованием piHashData
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const llong & v) {
|
inline uint piHash(const llong & v) {
|
||||||
return piHashData((const uchar *)&v, sizeof(v));
|
return piHashData((const uchar *)&v, sizeof(v));
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for ullong type using piHashData
|
||||||
|
//! \~russian Специализация хэш-функции для типа ullong с использованием piHashData
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const ullong & v) {
|
inline uint piHash(const ullong & v) {
|
||||||
return piHashData((const uchar *)&v, sizeof(v));
|
return piHashData((const uchar *)&v, sizeof(v));
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for float type
|
||||||
|
//! \~russian Специализация хэш-функции для типа float
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const float & v) {
|
inline uint piHash(const float & v) {
|
||||||
return (uint)v;
|
return (uint)v;
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for double type using piHashData
|
||||||
|
//! \~russian Специализация хэш-функции для типа double с использованием piHashData
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const double & v) {
|
inline uint piHash(const double & v) {
|
||||||
return piHashData((const uchar *)&v, sizeof(v));
|
return piHashData((const uchar *)&v, sizeof(v));
|
||||||
}
|
}
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Hash function specialization for ldouble type using piHashData
|
||||||
|
//! \~russian Специализация хэш-функции для типа ldouble с использованием piHashData
|
||||||
template<>
|
template<>
|
||||||
inline uint piHash(const ldouble & v) {
|
inline uint piHash(const ldouble & v) {
|
||||||
return piHashData((const uchar *)&v, sizeof(v));
|
return piHashData((const uchar *)&v, sizeof(v));
|
||||||
@@ -736,16 +778,30 @@ struct PIP_EXPORT PINonTriviallyCopyable {
|
|||||||
inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept = default;
|
inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept = default;
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Template struct for extracting function type from callable objects
|
||||||
|
//! \~russian Шаблонная структура для извлечения типа функции из вызываемых объектов
|
||||||
template<typename T>
|
template<typename T>
|
||||||
struct FunctionType {
|
struct FunctionType {
|
||||||
using Type = void;
|
using Type = void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Specialization for member function pointers
|
||||||
|
//! \~russian Специализация для указателей на члены класса
|
||||||
template<typename Ret, typename Class, typename... Args>
|
template<typename Ret, typename Class, typename... Args>
|
||||||
struct FunctionType<Ret (Class::*)(Args...) const> {
|
struct FunctionType<Ret (Class::*)(Args...) const> {
|
||||||
using Type = std::function<Ret(Args...)>;
|
using Type = std::function<Ret(Args...)>;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Convert lambda/functional object to std::function
|
||||||
|
//! \~russian Преобразует лямбду/функциональный объект в std::function
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! Uses FunctionType template to extract the function signature from the callable object
|
||||||
|
//! \~russian
|
||||||
|
//! Использует шаблон FunctionType для извлечения сигнатуры функции из вызываемого объекта
|
||||||
template<typename L>
|
template<typename L>
|
||||||
typename FunctionType<decltype(&L::operator())>::Type toStdFunction(L const & func) {
|
typename FunctionType<decltype(&L::operator())>::Type toStdFunction(L const & func) {
|
||||||
return func;
|
return func;
|
||||||
|
|||||||
@@ -1,15 +1,17 @@
|
|||||||
/*! \file pibase_macros.h
|
//! \addtogroup Core
|
||||||
* \ingroup Core
|
//! \{
|
||||||
* \~\brief
|
//! \~\file pibase_macros.h
|
||||||
* \~english Base macros
|
//! \brief
|
||||||
* \~russian Базовые макросы
|
//! \~english Base macros
|
||||||
*
|
//! \~russian Базовые макросы
|
||||||
* \~\details
|
//! \details
|
||||||
* \~english
|
//! \~english
|
||||||
* This file declares basic useful maros
|
//! This file declares basic useful macros for the PIP library including platform detection,
|
||||||
* \~russian
|
//! compiler-specific configurations, and utility macros for private data handling.
|
||||||
* Этот файл объявляет основные вспомогательные макросы
|
//! \~russian
|
||||||
*/
|
//! Этот файл объявляет основные вспомогательные макросы для библиотеки PIP, включая обнаружение платформы,
|
||||||
|
//! конфигурации, специфичные для компилятора, и служебные макросы для работы с приватными данными.
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Base macros
|
Base macros
|
||||||
@@ -46,151 +48,123 @@
|
|||||||
//! Содержит набор пар ключ=значение, например
|
//! Содержит набор пар ключ=значение, например
|
||||||
//! \~
|
//! \~
|
||||||
//! PIMETA(id=12345,tag="my string")
|
//! PIMETA(id=12345,tag="my string")
|
||||||
|
//! \~\sa PIMETA
|
||||||
#define PIMETA(...)
|
#define PIMETA(...)
|
||||||
|
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Major value of PIP version
|
//! \~english Major value of PIP version
|
||||||
//! \~russian Мажорная версия PIP
|
//! \~russian Мажорная версия PIP
|
||||||
# define PIP_VERSION_MAJOR
|
# define PIP_VERSION_MAJOR
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Minor value of PIP version
|
//! \~english Minor value of PIP version
|
||||||
//! \~russian Минорная версия PIP
|
//! \~russian Минорная версия PIP
|
||||||
# define PIP_VERSION_MINOR
|
# define PIP_VERSION_MINOR
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Revision value of PIP version
|
//! \~english Revision value of PIP version
|
||||||
//! \~russian Ревизия версии PIP
|
//! \~russian Ревизия версии PIP
|
||||||
# define PIP_VERSION_REVISION
|
# define PIP_VERSION_REVISION
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Suffix of PIP version
|
//! \~english Suffix of PIP version
|
||||||
//! \~russian Суффикс версии PIP
|
//! \~russian Суффикс версии PIP
|
||||||
# define PIP_VERSION_SUFFIX
|
# define PIP_VERSION_SUFFIX
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Version of PIP in hex - 0x##(Major)##(Minor)##(Revision)
|
//! \~english Version of PIP in hex - 0x##(Major)##(Minor)##(Revision)
|
||||||
//! \~russian Версия PIP в hex - 0x##(Major)##(Minor)##(Revision)
|
//! \~russian Версия PIP в hex - 0x##(Major)##(Minor)##(Revision)
|
||||||
# define PIP_VERSION
|
# define PIP_VERSION
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when compile-time debug is enabled
|
//! \~english Macro is defined when compile-time debug is enabled
|
||||||
//! \~russian Макрос объявлен когда включена compile-time отладка
|
//! \~russian Макрос объявлен когда включена compile-time отладка
|
||||||
# define PIP_DEBUG
|
# define PIP_DEBUG
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is any Windows
|
//! \~english Macro is defined when operation system is any Windows
|
||||||
//! \~russian Макрос объявлен когда операционная система Windows
|
//! \~russian Макрос объявлен когда операционная система Windows
|
||||||
# define WINDOWS
|
# define WINDOWS
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is QNX or Blackberry
|
//! \~english Macro is defined when operation system is QNX or Blackberry
|
||||||
//! \~russian Макрос объявлен когда операционная система QNX или Blackberry
|
//! \~russian Макрос объявлен когда операционная система QNX или Blackberry
|
||||||
# define QNX
|
# define QNX
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is Blackberry
|
//! \~english Macro is defined when operation system is Blackberry
|
||||||
//! \~russian Макрос объявлен когда операционная система Blackberry
|
//! \~russian Макрос объявлен когда операционная система Blackberry
|
||||||
# define BLACKBERRY
|
# define BLACKBERRY
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is FreeBSD
|
//! \~english Macro is defined when operation system is FreeBSD
|
||||||
//! \~russian Макрос объявлен когда операционная система FreeBSD
|
//! \~russian Макрос объявлен когда операционная система FreeBSD
|
||||||
# define FREE_BSD
|
# define FREE_BSD
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is Mac OS
|
//! \~english Macro is defined when operation system is Mac OS
|
||||||
//! \~russian Макрос объявлен когда операционная система Mac OS
|
//! \~russian Макрос объявлен когда операционная система Mac OS
|
||||||
# define MAC_OS
|
# define MAC_OS
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is Android
|
//! \~english Macro is defined when operation system is Android
|
||||||
//! \~russian Макрос объявлен когда операционная система Android
|
//! \~russian Макрос объявлен когда операционная система Android
|
||||||
# define ANDROID
|
# define ANDROID
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is any Linux
|
//! \~english Macro is defined when operation system is any Linux
|
||||||
//! \~russian Макрос объявлен когда операционная система Linux
|
//! \~russian Макрос объявлен когда операционная система Linux
|
||||||
# define LINUX
|
# define LINUX
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when operation system is FreeRTOS
|
//! \~english Macro is defined when operation system is FreeRTOS
|
||||||
//! \~russian Макрос объявлен когда операционная система FreeRTOS
|
//! \~russian Макрос объявлен когда операционная система FreeRTOS
|
||||||
# define FREERTOS
|
# define FREERTOS
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when compiler is GCC or MinGW
|
//! \~english Macro is defined when compiler is GCC or MinGW
|
||||||
//! \~russian Макрос объявлен когда компилятор GCC или MinGW
|
//! \~russian Макрос объявлен когда компилятор GCC или MinGW
|
||||||
# define CC_GCC
|
# define CC_GCC
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when PIP is decided that host is support language
|
//! \~english Macro is defined when PIP is decided that host is support language
|
||||||
//! \~russian Макрос объявлен когда PIP решил что система поддерживает локализацию
|
//! \~russian Макрос объявлен когда PIP решил что система поддерживает локализацию
|
||||||
# define HAS_LOCALE
|
# define HAS_LOCALE
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when PIP is building for embedded systems
|
//! \~english Macro is defined when PIP is building for embedded systems
|
||||||
//! \~russian Макрос объявлен когда PIP собирается для встраиваемых систем
|
//! \~russian Макрос объявлен когда PIP собирается для встраиваемых систем
|
||||||
# define MICRO_PIP
|
# define MICRO_PIP
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when compiler is Visual Studio
|
//! \~english Macro is defined when compiler is Visual Studio
|
||||||
//! \~russian Макрос объявлен когда компилятор Visual Studio
|
//! \~russian Макрос объявлен когда компилятор Visual Studio
|
||||||
# define CC_VC
|
# define CC_VC
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when compiler is AVR GCC
|
//! \~english Macro is defined when compiler is AVR GCC
|
||||||
//! \~russian Макрос объявлен когда компилятор AVR GCC
|
//! \~russian Макрос объявлен когда компилятор AVR GCC
|
||||||
# define CC_AVR_GCC
|
# define CC_AVR_GCC
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro is defined when compiler is unknown
|
//! \~english Macro is defined when compiler is unknown
|
||||||
//! \~russian Макрос объявлен когда компилятор неизвестен
|
//! \~russian Макрос объявлен когда компилятор неизвестен
|
||||||
# define CC_OTHER
|
# define CC_OTHER
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to declare private section, "export" is optional
|
//! \~english Macro to declare private section, "export" is optional
|
||||||
//! \~russian Макрос для объявления частной секции, "export" необязателен
|
//! \~russian Макрос для объявления частной секции, "export" необязателен
|
||||||
# define PRIVATE_DECLARATION(export)
|
# define PRIVATE_DECLARATION(export)
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to start definition of private section
|
//! \~english Macro to start definition of private section
|
||||||
//! \~russian Макрос для начала реализации частной секции
|
//! \~russian Макрос для начала реализации частной секции
|
||||||
# define PRIVATE_DEFINITION_START(Class)
|
# define PRIVATE_DEFINITION_START(Class)
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to end definition of private section
|
//! \~english Macro to end definition of private section
|
||||||
//! \~russian Макрос для окончания реализации частной секции
|
//! \~russian Макрос для окончания реализации частной секции
|
||||||
# define PRIVATE_DEFINITION_END(Class)
|
# define PRIVATE_DEFINITION_END(Class)
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to access private section by pointer
|
//! \~english Macro to access private section by pointer
|
||||||
//! \~russian Макрос для доступа к частной секции
|
//! \~russian Макрос для доступа к частной секции
|
||||||
# define PRIVATE
|
# define PRIVATE
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Macro to access private section by pointer without braces ()
|
||||||
//! \~english Macro to access private section by pointer without brakes ()
|
|
||||||
//! \~russian Макрос для доступа к частной секции без обрамляющих скобок ()
|
//! \~russian Макрос для доступа к частной секции без обрамляющих скобок ()
|
||||||
# define PRIVATEWB
|
# define PRIVATEWB
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to start static initializer
|
//! \~english Macro to start static initializer
|
||||||
//! \~russian Макрос для начала статической инициализации
|
//! \~russian Макрос для начала статической инициализации
|
||||||
# define STATIC_INITIALIZER_BEGIN
|
# define STATIC_INITIALIZER_BEGIN
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to end static initializer
|
//! \~english Macro to end static initializer
|
||||||
//! \~russian Макрос для окончания статической инициализации
|
//! \~russian Макрос для окончания статической инициализации
|
||||||
# define STATIC_INITIALIZER_END
|
# define STATIC_INITIALIZER_END
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to remove class copy availability
|
//! \~english Macro to remove class copy availability
|
||||||
//! \~russian Макрос для запрета копирования класса
|
//! \~russian Макрос для запрета копирования класса
|
||||||
# define NO_COPY_CLASS(Class)
|
# define NO_COPY_CLASS(Class)
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro to supress compiler warning about unused variable
|
//! \~english Macro to supress compiler warning about unused variable
|
||||||
//! \~russian Макрос для подавления предупреждения компилятора о неиспользуемой переменной
|
//! \~russian Макрос для подавления предупреждения компилятора о неиспользуемой переменной
|
||||||
# define NO_UNUSED(x)
|
# define NO_UNUSED(x)
|
||||||
@@ -320,6 +294,9 @@ typedef long long ssize_t;
|
|||||||
// Private data macros
|
// Private data macros
|
||||||
#ifndef DOXYGEN
|
#ifndef DOXYGEN
|
||||||
|
|
||||||
|
//! \~english Macro to declare private section, "export" is optional
|
||||||
|
//! \~russian Макрос для объявления частной секции, "export" необязателен
|
||||||
|
//! \~sa PRIVATE PRIVATEWB
|
||||||
# define PRIVATE_DECLARATION(e) \
|
# define PRIVATE_DECLARATION(e) \
|
||||||
struct __Private__; \
|
struct __Private__; \
|
||||||
friend struct __Private__; \
|
friend struct __Private__; \
|
||||||
@@ -332,10 +309,20 @@ typedef long long ssize_t;
|
|||||||
}; \
|
}; \
|
||||||
__PrivateInitializer__ __privateinitializer__;
|
__PrivateInitializer__ __privateinitializer__;
|
||||||
|
|
||||||
|
//! \~english Macro to start definition of private section
|
||||||
|
//! \~russian Макрос для начала реализации частной секции
|
||||||
|
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||||
# define PRIVATE_DEFINITION_START(c) struct c::__Private__ {
|
# define PRIVATE_DEFINITION_START(c) struct c::__Private__ {
|
||||||
|
//! \~english Macro to end definition of private section without initialization
|
||||||
|
//! \~russian Макрос для окончания реализации частной секции без инициализации
|
||||||
|
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_START PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||||
# define PRIVATE_DEFINITION_END_NO_INITIALIZE(c) \
|
# define PRIVATE_DEFINITION_END_NO_INITIALIZE(c) \
|
||||||
} \
|
} \
|
||||||
;
|
;
|
||||||
|
|
||||||
|
//! \~english Macro to initialize private section
|
||||||
|
//! \~russian Макрос для инициализации частной секции
|
||||||
|
//! \~sa PRIVATE_DEFINITION_END PRIVATE_DEFINITION_START PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE PRIVATEWB
|
||||||
# define PRIVATE_DEFINITION_INITIALIZE(c) \
|
# define PRIVATE_DEFINITION_INITIALIZE(c) \
|
||||||
c::__PrivateInitializer__::__PrivateInitializer__() { \
|
c::__PrivateInitializer__::__PrivateInitializer__() { \
|
||||||
p = new c::__Private__(); \
|
p = new c::__Private__(); \
|
||||||
@@ -351,31 +338,51 @@ typedef long long ssize_t;
|
|||||||
p = new c::__Private__(); \
|
p = new c::__Private__(); \
|
||||||
return *this; \
|
return *this; \
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Macro to end definition of private section with initialization
|
||||||
|
//! \~russian Макрос для окончания реализации частной секции с инициализацией
|
||||||
|
//! \~sa PRIVATE_DEFINITION_END_NO_INITIALIZE PRIVATE_DEFINITION_START PRIVATE_DEFINITION_INITIALIZE PRIVATE PRIVATEWB
|
||||||
# define PRIVATE_DEFINITION_END(c) \
|
# define PRIVATE_DEFINITION_END(c) \
|
||||||
PRIVATE_DEFINITION_END_NO_INITIALIZE \
|
PRIVATE_DEFINITION_END_NO_INITIALIZE \
|
||||||
(c) PRIVATE_DEFINITION_INITIALIZE(c)
|
(c) PRIVATE_DEFINITION_INITIALIZE(c)
|
||||||
|
|
||||||
|
//! \~english Macro to access private section by pointer
|
||||||
|
//! \~russian Макрос для доступа к частной секции
|
||||||
|
//! \~sa PRIVATEWB
|
||||||
# define PRIVATE (__privateinitializer__.p)
|
# define PRIVATE (__privateinitializer__.p)
|
||||||
|
|
||||||
|
//! \~english Macro to access private section by pointer without braces ()
|
||||||
|
//! \~russian Макрос для доступа к частной секции без обрамляющих скобок ()
|
||||||
|
//! \~sa PRIVATE
|
||||||
# define PRIVATEWB __privateinitializer__.p
|
# define PRIVATEWB __privateinitializer__.p
|
||||||
|
|
||||||
#endif // DOXYGEN
|
#endif // DOXYGEN
|
||||||
|
|
||||||
|
//! \~english Macro to remove class copy availability
|
||||||
|
//! \~russian Макрос для запрета копирования класса
|
||||||
#define NO_COPY_CLASS(name) \
|
#define NO_COPY_CLASS(name) \
|
||||||
name(const name &) = delete; \
|
name(const name &) = delete; \
|
||||||
name & operator=(const name &) = delete;
|
name & operator=(const name &) = delete;
|
||||||
|
|
||||||
|
//! \~english Counter macro for unique identifier generation
|
||||||
|
//! \~russian Макрос счетчика для генерации уникальных идентификаторов
|
||||||
#define _PIP_ADD_COUNTER_WS(a, cnt, line) a##cnt##_##line
|
#define _PIP_ADD_COUNTER_WS(a, cnt, line) a##cnt##_##line
|
||||||
#define _PIP_ADD_COUNTER_WF(a, cnt, line) _PIP_ADD_COUNTER_WS(a, cnt, line)
|
#define _PIP_ADD_COUNTER_WF(a, cnt, line) _PIP_ADD_COUNTER_WS(a, cnt, line)
|
||||||
#define _PIP_ADD_COUNTER(a) _PIP_ADD_COUNTER_WF(a, __COUNTER__, __LINE__)
|
#define _PIP_ADD_COUNTER(a) _PIP_ADD_COUNTER_WF(a, __COUNTER__, __LINE__)
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Macro to start static initializer
|
||||||
|
//! \~russian Макрос для начала статической инициализации
|
||||||
|
//! \~sa STATIC_INITIALIZER_END
|
||||||
#define STATIC_INITIALIZER_BEGIN \
|
#define STATIC_INITIALIZER_BEGIN \
|
||||||
class { \
|
class { \
|
||||||
class _Initializer_ { \
|
class _Initializer_ { \
|
||||||
public: \
|
public: \
|
||||||
_Initializer_() {
|
_Initializer_() {
|
||||||
|
//! \~english Macro to end static initializer
|
||||||
|
//! \~russian Макрос для окончания статической инициализации
|
||||||
|
//! \~sa STATIC_INITIALIZER_BEGIN
|
||||||
#define STATIC_INITIALIZER_END \
|
#define STATIC_INITIALIZER_END \
|
||||||
} \
|
} \
|
||||||
} \
|
} \
|
||||||
@@ -384,12 +391,12 @@ typedef long long ssize_t;
|
|||||||
_PIP_ADD_COUNTER(_pip_initializer_);
|
_PIP_ADD_COUNTER(_pip_initializer_);
|
||||||
|
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Minimal sleep in milliseconds for internal PIP using
|
//! \~english Minimal sleep in milliseconds for internal PIP using
|
||||||
//! \~russian Минимальное значание задержки в милисекундах для внутреннего использования в библиотеке PIP
|
//! \~russian Минимальное значание задержки в милисекундах для внутреннего использования в библиотеке PIP
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english Using in \a piMinSleep(), \a PIThread, \a PITimer::Pool. By default 1ms.
|
//! \~english Using in \a piMinSleep(), \a PIThread, \a PITimer::Pool. By default 1ms.
|
||||||
//! \~russian Используется в \a piMinSleep(), \a PIThread, \a PITimer::Pool. По умолчанию равна 1мс.
|
//! \~russian Используется в \a piMinSleep(), \a PIThread, \a PITimer::Pool. По умолчанию равна 1мс.
|
||||||
|
//! \~\sa PIP_MIN_MSLEEP
|
||||||
#ifndef PIP_MIN_MSLEEP
|
#ifndef PIP_MIN_MSLEEP
|
||||||
# ifndef MICRO_PIP
|
# ifndef MICRO_PIP
|
||||||
# define PIP_MIN_MSLEEP 1.
|
# define PIP_MIN_MSLEEP 1.
|
||||||
@@ -399,19 +406,26 @@ typedef long long ssize_t;
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro used for infinite loop
|
//! \~english Macro used for infinite loop
|
||||||
//! \~russian Макрос для бесконечного цикла
|
//! \~russian Макрос для бесконечного цикла
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Expands to \c for(;;) infinite loop construct
|
||||||
|
//! \~russian Раскрывается в конструкцию бесконечного цикла \c for(;;)
|
||||||
#define FOREVER for (;;)
|
#define FOREVER for (;;)
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro used for infinite wait
|
//! \~english Macro used for infinite wait
|
||||||
//! \~russian Макрос для бесконечного ожидания
|
//! \~russian Макрос для бесконечного ожидания
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Expands to infinite loop with periodic sleep calls for CPU-friendly waiting
|
||||||
|
//! \~russian Раскрывается в бесконечный цикл с периодическими вызовами sleep для экономии ресурсов CPU
|
||||||
#define FOREVER_WAIT FOREVER piMinSleep();
|
#define FOREVER_WAIT FOREVER piMinSleep();
|
||||||
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english Macro used for infinite wait
|
//! \~english Macro used for infinite wait
|
||||||
//! \~russian Макрос для бесконечного ожидания
|
//! \~russian Макрос для бесконечного ожидания
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Expands to infinite loop with periodic sleep calls for CPU-friendly waiting
|
||||||
|
//! \~russian Раскрывается в бесконечный цикл с периодическими вызовами sleep для экономии ресурсов CPU
|
||||||
|
//! \~\sa FOREVER_WAIT
|
||||||
#define WAIT_FOREVER FOREVER piMinSleep();
|
#define WAIT_FOREVER FOREVER piMinSleep();
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,13 @@
|
|||||||
/*! \file picollection.h
|
//! \addtogroup Core
|
||||||
* \ingroup Core
|
//! \{
|
||||||
* \~\brief
|
//! \~\file picollection.h
|
||||||
* \~english Unique classes collection
|
//! \brief
|
||||||
* \~russian Коллекция уникальных классов
|
//! \~english Unique classes collection
|
||||||
*/
|
//! \~russian Коллекция уникальных классов
|
||||||
|
//! \details
|
||||||
|
//! \~english Helper module to collect and retrieve classes into groups using macros for automatic registration.
|
||||||
|
//! \~russian Модуль-помощник для сбора и получения классов в группы с помощью макросов для автоматической регистрации.
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Peer - named I/O ethernet node, forming self-organized peering network
|
Peer - named I/O ethernet node, forming self-organized peering network
|
||||||
@@ -30,10 +34,10 @@
|
|||||||
|
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
//! \~\relatesalso PICollection
|
//! \relatesalso PICollection
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Add existing element "object" in group with name "group"
|
//! \~english Adds existing object to group "group".
|
||||||
//! \~russian Добавляет существующий элемент "object" в группу с именем "group"
|
//! \~russian Добавляет существующий объект в группу "group".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! If this is no group with name "group" it will be created.
|
//! If this is no group with name "group" it will be created.
|
||||||
@@ -46,21 +50,21 @@
|
|||||||
//! то ничего не изменится. \n "object" должен быть наследником \a PIObject.
|
//! то ничего не изменится. \n "object" должен быть наследником \a PIObject.
|
||||||
# define ADD_TO_COLLECTION(group, object)
|
# define ADD_TO_COLLECTION(group, object)
|
||||||
|
|
||||||
//! \~\relatesalso PICollection
|
//! \relatesalso PICollection
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Add existing element "object" in group with name "group" and set its name to "name"
|
//! \~english Adds existing object to group "group" and assigns name "name".
|
||||||
//! \~russian Добавляет существующий элемент "object" в группу с именем "group" и присваивает объекту имя "name"
|
//! \~russian Добавляет существующий объект в группу "group" и присваивает ему имя "name".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! Similar to \a ADD_TO_COLLECTION(group, object) but set object name to "name"
|
//! Similar to \a ADD_TO_COLLECTION(group, object), but also sets object name.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Аналогично \a ADD_TO_COLLECTION(group, object), но присваивает имя объекту "name"
|
//! Аналогично \a ADD_TO_COLLECTION(group, object), но дополнительно задает имя объекта.
|
||||||
# define ADD_TO_COLLECTION_WITH_NAME(group, object, name)
|
# define ADD_TO_COLLECTION_WITH_NAME(group, object, name)
|
||||||
|
|
||||||
//! \~\relatesalso PICollection
|
//! \relatesalso PICollection
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Add new element of class "class" in group with name "group"
|
//! \~english Creates and adds new object of class "class" to group "group".
|
||||||
//! \~russian Добавляет новый элемент класса "class" в группу с именем "group"
|
//! \~russian Создает и добавляет новый объект класса "class" в группу "group".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! If this is no group with name "group" it will be created.
|
//! If this is no group with name "group" it will be created.
|
||||||
@@ -73,15 +77,17 @@
|
|||||||
//! то ничего не изменится. \n "class" должен быть любым классом, наследным от \a PIObject.
|
//! то ничего не изменится. \n "class" должен быть любым классом, наследным от \a PIObject.
|
||||||
# define ADD_NEW_TO_COLLECTION(group, class)
|
# define ADD_NEW_TO_COLLECTION(group, class)
|
||||||
|
|
||||||
//! \~\relatesalso PICollection
|
//! \relatesalso PICollection
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Add new element of class "class" in group with name "group" and set its name to "name"
|
//! \~english Creates and adds new object of class "class" to group "group"
|
||||||
//! \~russian Добавляет новый элемент класса "class" в группу с именем "group" и присваивает объекту имя "name"
|
//! and assigns name "name".
|
||||||
|
//! \~russian Создает и добавляет новый объект класса "class" в группу "group"
|
||||||
|
//! и присваивает ему имя "name".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! Similar to \a ADD_NEW_TO_COLLECTION(group, class) but set object name to "name"
|
//! Similar to \a ADD_NEW_TO_COLLECTION(group, class), but also sets object name.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Аналогично \a ADD_NEW_TO_COLLECTION(group, class), но присваивает имя объекту "name"
|
//! Аналогично \a ADD_NEW_TO_COLLECTION(group, class), но дополнительно задает имя объекта.
|
||||||
# define ADD_NEW_TO_COLLECTION_WITH_NAME(group, class, name)
|
# define ADD_NEW_TO_COLLECTION_WITH_NAME(group, class, name)
|
||||||
|
|
||||||
#else
|
#else
|
||||||
@@ -100,28 +106,40 @@
|
|||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Helper to collect and retrieve classes to groups.
|
//! \~english Global collection of %PIObject-based instances grouped by name.
|
||||||
//! \~russian Помощник для создания и получения классов в группы.
|
//! \~russian Глобальная коллекция экземпляров на базе %PIObject, сгруппированных по имени.
|
||||||
class PIP_EXPORT PICollection {
|
class PIP_EXPORT PICollection {
|
||||||
friend class __PICollectionInitializer;
|
friend class __PICollectionInitializer;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs collection helper.
|
||||||
|
//! \~russian Создает вспомогательный объект коллекции.
|
||||||
PICollection() { ; }
|
PICollection() { ; }
|
||||||
|
|
||||||
//! \~english Returns all existing groups by their names
|
//! \~english Returns names of all existing groups.
|
||||||
//! \~russian Возвращает имена всех групп
|
//! \~russian Возвращает имена всех существующих групп.
|
||||||
static PIStringList groups();
|
static PIStringList groups();
|
||||||
|
|
||||||
//! \~english Returns all elements of group "group"
|
//! \~english Returns all elements stored in group "group".
|
||||||
//! \~russian Возвращает все элементы группы "group"
|
//! \~russian Возвращает все элементы, хранящиеся в группе "group".
|
||||||
static PIVector<const PIObject *> groupElements(const PIString & group);
|
static PIVector<const PIObject *> groupElements(const PIString & group);
|
||||||
|
|
||||||
|
//! \~english Adds object to group "group" if that group has no object of the
|
||||||
|
//! same runtime class.
|
||||||
|
//! \~russian Добавляет объект в группу "group", если в группе еще нет объекта
|
||||||
|
//! того же класса времени выполнения.
|
||||||
static bool addToGroup(const PIString & group, const PIObject * element);
|
static bool addToGroup(const PIString & group, const PIObject * element);
|
||||||
|
|
||||||
|
//! \~\ingroup Core
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Helper that registers object in collection during static initialization.
|
||||||
|
//! \~russian Вспомогательный класс, регистрирующий объект в коллекции при статической инициализации.
|
||||||
class PIP_EXPORT CollectionAdder {
|
class PIP_EXPORT CollectionAdder {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Registers object in group and optionally assigns object name.
|
||||||
|
//! \~russian Регистрирует объект в группе и при необходимости задает имя объекта.
|
||||||
CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false);
|
CollectionAdder(const PIString & group, const PIObject * element, const PIString & name = PIString(), bool own = false);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file picoremodule.h
|
||||||
|
* \ingroup Core
|
||||||
|
* \~\brief
|
||||||
|
* \~english Umbrella header for the Core module
|
||||||
|
* \~russian Агрегирующий заголовок модуля Core
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public chunk stream, collection, JSON, object, property storage, and time headers.
|
||||||
|
* \~russian Подключает публичные заголовки потоков чанков, коллекций, JSON, объектов, хранилища свойств и времени.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -34,10 +44,12 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides platform abstraction, useful macros, methods and classes
|
//! These headers provide platform abstraction, common macros, utility functions
|
||||||
|
//! and base classes.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают абстракцию операционной системы, полезные макросы, методы и классы
|
//! Эти заголовки предоставляют абстракцию платформы, общие макросы,
|
||||||
|
//! вспомогательные функции и базовые классы.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
/*! \file picout.h
|
//! \addtogroup Core
|
||||||
* \ingroup Core
|
//! \{
|
||||||
* \~\brief
|
//! \~\file picout.h
|
||||||
* \~english Universal output to console class
|
//! \brief
|
||||||
* \~russian Универсальный вывод в консоль
|
//! \~english Universal output to console class
|
||||||
*/
|
//! \~russian Универсальный вывод в консоль
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Universal output to console class
|
Universal output to console class
|
||||||
@@ -116,8 +117,8 @@ enum PICoutFormat {
|
|||||||
Dec /*! \~english Decimal representation of integers \~russian Десятичное представление для целых чисел */ = 0x04,
|
Dec /*! \~english Decimal representation of integers \~russian Десятичное представление для целых чисел */ = 0x04,
|
||||||
Hex /*! \~english Hexadecimal representation of integers \~russian Шестнадцатеричное представление для целых чисел */ = 0x08,
|
Hex /*! \~english Hexadecimal representation of integers \~russian Шестнадцатеричное представление для целых чисел */ = 0x08,
|
||||||
Bold /*! \~english Bold \~russian Жирный */ = 0x10,
|
Bold /*! \~english Bold \~russian Жирный */ = 0x10,
|
||||||
Faint /*! \~english \~russian */ = 0x20,
|
Faint /*! \~english Faint \~russian Тусклый */ = 0x20,
|
||||||
Italic /*! \~english \~russian */ = 0x40,
|
Italic /*! \~english Italic \~russian Курсив */ = 0x40,
|
||||||
Underline /*! \~english Underline \~russian Подчеркнутый */ = 0x80,
|
Underline /*! \~english Underline \~russian Подчеркнутый */ = 0x80,
|
||||||
Blink /*! \~english Blink \~russian Мигающий */ = 0x100,
|
Blink /*! \~english Blink \~russian Мигающий */ = 0x100,
|
||||||
Black /*! \~english Black font \~russian Чёрный */ = 0x400,
|
Black /*! \~english Black font \~russian Чёрный */ = 0x400,
|
||||||
@@ -153,10 +154,15 @@ enum class PICoutStdStream {
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Universal output to console class.
|
//! \~english Universal output to console class.
|
||||||
//! \~russian Универсальный вывод в консоль.
|
//! \~russian Универсальный вывод в консоль.
|
||||||
|
//! \details
|
||||||
|
//! \~english This class provides a universal output interface with support for various data types, formatting options, and multiple output
|
||||||
|
//! devices (console, buffer).
|
||||||
|
//! \~russian Данный класс предоставляет универсальный интерфейс вывода с поддержкой различных типов данных, опций форматирования и
|
||||||
|
//! нескольких устройств вывода (консоль, буфер).
|
||||||
class PIP_EXPORT PICout {
|
class PIP_EXPORT PICout {
|
||||||
public:
|
public:
|
||||||
//! \~english Default constructor with default features (AddSpaces and AddNewLine)
|
//! \~english Default constructor with default features (AddSpaces and AddNewLine)
|
||||||
@@ -178,10 +184,16 @@ public:
|
|||||||
public:
|
public:
|
||||||
//! \~english Singleton access to %PICout::Notifier
|
//! \~english Singleton access to %PICout::Notifier
|
||||||
//! \~russian Синглтон класса %PICout::Notifier
|
//! \~russian Синглтон класса %PICout::Notifier
|
||||||
|
//! \details
|
||||||
|
//! \~english Returns the singleton instance of the Notifier class used for emitting PICout events.
|
||||||
|
//! \~russian Возвращает синглтон-экземпляр класса Notifier, используемого для посылки событий PICout.
|
||||||
static Notifier * instance();
|
static Notifier * instance();
|
||||||
|
|
||||||
//! \~english Object that emit events from %PICout
|
//! \~english Object that emit events from %PICout
|
||||||
//! \~russian Объект, который посылает события от %PICout
|
//! \~russian Объект, который посылает события от %PICout
|
||||||
|
//! \details
|
||||||
|
//! \~english Returns the PIObject instance that emits events when PICout with external buffer is destroyed.
|
||||||
|
//! \~russian Возвращает экземпляр PIObject, который посылает события при уничтожении PICout с внешним буфером.
|
||||||
static PIObject * object();
|
static PIObject * object();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -234,26 +246,51 @@ public:
|
|||||||
|
|
||||||
//! \~english Output operator for <tt>"int"</tt> values
|
//! \~english Output operator for <tt>"int"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"int"</tt> значений
|
//! \~russian Оператор вывода для <tt>"int"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs an integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||||
|
//! \~russian Выводит целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal, hexadecimal).
|
||||||
PICout & operator<<(int v);
|
PICout & operator<<(int v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"unsigned int"</tt> values
|
//! \~english Output operator for <tt>"unsigned int"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"unsigned int"</tt> значений
|
//! \~russian Оператор вывода для <tt>"unsigned int"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs an unsigned integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||||
|
//! \~russian Выводит беззнаковое целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal,
|
||||||
|
//! hexadecimal).
|
||||||
PICout & operator<<(uint v);
|
PICout & operator<<(uint v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"long"</tt> values
|
//! \~english Output operator for <tt>"long"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"long"</tt> значений
|
//! \~russian Оператор вывода для <tt>"long"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs a long integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||||
|
//! \~russian Выводит длинное целочисленное значение в настроенный поток с опциональным форматированием (binary, octal, decimal,
|
||||||
|
//! hexadecimal).
|
||||||
PICout & operator<<(long v);
|
PICout & operator<<(long v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"unsigned long"</tt> values
|
//! \~english Output operator for <tt>"unsigned long"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"unsigned long"</tt> значений
|
//! \~russian Оператор вывода для <tt>"unsigned long"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs an unsigned long integer value to the configured stream with optional format (binary, octal, decimal,
|
||||||
|
//! hexadecimal).
|
||||||
|
//! \~russian Выводит беззнаковое длинное целочисленное значение в настроенный поток с опциональным форматированием (binary, octal,
|
||||||
|
//! decimal, hexadecimal).
|
||||||
PICout & operator<<(ulong v);
|
PICout & operator<<(ulong v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"long long"</tt> values
|
//! \~english Output operator for <tt>"long long"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"long long"</tt> значений
|
//! \~russian Оператор вывода для <tt>"long long"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs a long long integer value to the configured stream with optional format (binary, octal, decimal, hexadecimal).
|
||||||
|
//! \~russian Выводит длинное long long целочисленное значение в настроенный поток с опциональным форматированием (binary, octal,
|
||||||
|
//! decimal, hexadecimal).
|
||||||
PICout & operator<<(llong v);
|
PICout & operator<<(llong v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"unsigned long long"</tt> values
|
//! \~english Output operator for <tt>"unsigned long long"</tt> values
|
||||||
//! \~russian Оператор вывода для <tt>"unsigned long long"</tt> значений
|
//! \~russian Оператор вывода для <tt>"unsigned long long"</tt> значений
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs an unsigned long long integer value to the configured stream with optional format (binary, octal, decimal,
|
||||||
|
//! hexadecimal).
|
||||||
|
//! \~russian Выводит беззнаковое длинное long long целочисленное значение в настроенный поток с опциональным форматированием (binary,
|
||||||
|
//! octal, decimal, hexadecimal).
|
||||||
PICout & operator<<(ullong v);
|
PICout & operator<<(ullong v);
|
||||||
|
|
||||||
//! \~english Output operator for <tt>"float"</tt> values
|
//! \~english Output operator for <tt>"float"</tt> values
|
||||||
@@ -270,10 +307,16 @@ public:
|
|||||||
|
|
||||||
//! \~english Output operator for pointers
|
//! \~english Output operator for pointers
|
||||||
//! \~russian Оператор вывода для указателей
|
//! \~russian Оператор вывода для указателей
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs a pointer address to the configured stream in hexadecimal format.
|
||||||
|
//! \~russian Выводит адрес указателя в настроенный поток в шестнадцатеричном формате.
|
||||||
PICout & operator<<(const void * v);
|
PICout & operator<<(const void * v);
|
||||||
|
|
||||||
//! \~english Output operator for PIObject and ancestors
|
//! \~english Output operator for PIObject and ancestors
|
||||||
//! \~russian Оператор вывода для PIObject и наследников
|
//! \~russian Оператор вывода для PIObject и наследников
|
||||||
|
//! \details
|
||||||
|
//! \~english Outputs a PIObject or its descendants to the configured stream, including class name and object name.
|
||||||
|
//! \~russian Выводит PIObject или его наследников в настроенный поток, включая имя класса и имя объекта.
|
||||||
PICout & operator<<(const PIObject * v);
|
PICout & operator<<(const PIObject * v);
|
||||||
|
|
||||||
//! \~english Output operator for \a PICoutSpecialChar values
|
//! \~english Output operator for \a PICoutSpecialChar values
|
||||||
@@ -282,10 +325,18 @@ public:
|
|||||||
|
|
||||||
//! \~english Output operator for \a PIFlags<PICoutFormat> values
|
//! \~english Output operator for \a PIFlags<PICoutFormat> values
|
||||||
//! \~russian Оператор вывода для \a PIFlags<PICoutFormat>
|
//! \~russian Оператор вывода для \a PIFlags<PICoutFormat>
|
||||||
|
//! \details
|
||||||
|
//! \~english Sets output format flags (binary, octal, decimal, hexadecimal, bold, colors) for subsequent integer output.
|
||||||
|
//! \~russian Устанавливает флаги форматирования вывода (binary, octal, decimal, hexadecimal, bold, colors) для последующего вывода
|
||||||
|
//! целых чисел.
|
||||||
PICout & operator<<(PIFlags<PICoutManipulators::PICoutFormat> v);
|
PICout & operator<<(PIFlags<PICoutManipulators::PICoutFormat> v);
|
||||||
|
|
||||||
//! \~english Output operator for \a PICoutFormat values
|
//! \~english Output operator for \a PICoutFormat values
|
||||||
//! \~russian Оператор вывода для \a PICoutFormat
|
//! \~russian Оператор вывода для \a PICoutFormat
|
||||||
|
//! \details
|
||||||
|
//! \~english Sets output format flag (binary, octal, decimal, hexadecimal, bold, colors) for subsequent integer output.
|
||||||
|
//! \~russian Устанавливает флаг форматирования вывода (binary, octal, decimal, hexadecimal, bold, colors) для последующего вывода целых
|
||||||
|
//! чисел.
|
||||||
PICout & operator<<(PICoutManipulators::PICoutFormat v);
|
PICout & operator<<(PICoutManipulators::PICoutFormat v);
|
||||||
|
|
||||||
//! \~english Do some action
|
//! \~english Do some action
|
||||||
@@ -301,45 +352,72 @@ public:
|
|||||||
PICout & setControls(PICoutManipulators::PICoutControls c);
|
PICout & setControls(PICoutManipulators::PICoutControls c);
|
||||||
|
|
||||||
//! \~english Exec \a saveControls() and set control flags to "c"
|
//! \~english Exec \a saveControls() and set control flags to "c"
|
||||||
//! \~russian Иыполнить \a saveControls() и Установить флаги "c"
|
//! \~russian Выполнить \a saveControls() и установить флаги "c"
|
||||||
PICout & saveAndSetControls(PICoutManipulators::PICoutControls c);
|
PICout & saveAndSetControls(PICoutManipulators::PICoutControls c);
|
||||||
|
|
||||||
//! \~english Save control flags to internal stack
|
//! \~english Save control flags to internal stack
|
||||||
//! \~russian Сохраняет состояние флагов во внутренний стек
|
//! \~russian Сохраняет состояние флагов во внутренний стек
|
||||||
//! \~\sa \a restoreControl()
|
//! \details
|
||||||
|
//! \~english Saves the current control flags to an internal stack for later restoration using restoreControls().
|
||||||
|
//! \~russian Сохраняет текущие флаги управления во внутренний стек для последующего восстановления с помощью restoreControls().
|
||||||
|
//! \~\sa \a restoreControls()
|
||||||
PICout & saveControls();
|
PICout & saveControls();
|
||||||
|
|
||||||
//! \~english Restore control flags from internal stack
|
//! \~english Restore control flags from internal stack
|
||||||
//! \~russian Восстанавливает состояние флагов из внутреннего стека
|
//! \~russian Восстанавливает состояние флагов из внутреннего стека
|
||||||
//! \~\sa \a saveControl()
|
//! \details
|
||||||
|
//! \~english Restores the control flags from the internal stack that were previously saved using saveControls().
|
||||||
|
//! \~russian Восстанавливает флаги управления из внутреннего стека, которые были ранее сохранены с помощью saveControls().
|
||||||
|
//! \~\sa \a saveControls()
|
||||||
PICout & restoreControls();
|
PICout & restoreControls();
|
||||||
|
|
||||||
//! \~english Conditional put space character to output
|
//! \~english Conditional put space character to output
|
||||||
//! \~russian Условно добавляет пробел
|
//! \~russian Условно добавляет пробел
|
||||||
|
//! \details
|
||||||
|
//! \~english Conditionally adds a space character to the output if the AddSpaces control flag is enabled.
|
||||||
|
//! \~russian Условно добавляет пробел в вывод, если включен флаг управления AddSpaces.
|
||||||
PICout & space();
|
PICout & space();
|
||||||
|
|
||||||
//! \~english Conditional put quote character to output
|
//! \~english Conditional put quote character to output
|
||||||
//! \~russian Условно добавляет кавычки
|
//! \~russian Условно добавляет кавычки
|
||||||
|
//! \details
|
||||||
|
//! \~english Conditionally adds quote characters to the output if the AddQuotes control flag is enabled.
|
||||||
|
//! \~russian Условно добавляет кавычки в вывод, если включен флаг управления AddQuotes.
|
||||||
PICout & quote();
|
PICout & quote();
|
||||||
|
|
||||||
//! \~english Conditional put new line character to output
|
//! \~english Conditional put new line character to output
|
||||||
//! \~russian Условно добавляет новую строку
|
//! \~russian Условно добавляет новую строку
|
||||||
|
//! \details
|
||||||
|
//! \~english Conditionally adds a newline character to the output if the AddNewLine control flag is enabled.
|
||||||
|
//! \~russian Условно добавляет символ новой строки в вывод, если включен флаг управления AddNewLine.
|
||||||
PICout & newLine();
|
PICout & newLine();
|
||||||
|
|
||||||
//! \~english Write char
|
//! \~english Write char
|
||||||
//! \~russian Пишет символ
|
//! \~russian Пишет символ
|
||||||
|
//! \details
|
||||||
|
//! \~english Writes a single character directly to the output stream without any formatting.
|
||||||
|
//! \~russian Записывает один символ непосредственно в поток вывода без какого-либо форматирования.
|
||||||
PICout & write(char c);
|
PICout & write(char c);
|
||||||
|
|
||||||
//! \~english Write raw data
|
//! \~english Write raw data
|
||||||
//! \~russian Пишет сырые символы
|
//! \~russian Пишет сырые символы
|
||||||
|
//! \details
|
||||||
|
//! \~english Writes raw C-style string data directly to the output stream without any formatting.
|
||||||
|
//! \~russian Записывает сырые данные C-строки непосредственно в поток вывода без какого-либо форматирования.
|
||||||
PICout & write(const char * str);
|
PICout & write(const char * str);
|
||||||
|
|
||||||
//! \~english Write raw data
|
//! \~english Write raw data
|
||||||
//! \~russian Пишет сырые символы
|
//! \~russian Пишет сырые символы
|
||||||
|
//! \details
|
||||||
|
//! \~english Writes raw data of specified length directly to the output stream without any formatting.
|
||||||
|
//! \~russian Записывает сырые данные указанной длины непосредственно в поток вывода без какого-либо форматирования.
|
||||||
PICout & write(const char * str, int len);
|
PICout & write(const char * str, int len);
|
||||||
|
|
||||||
//! \~english Write raw \a PIString
|
//! \~english Write raw \a PIString
|
||||||
//! \~russian Пишет сырой \a PIString
|
//! \~russian Пишет сырой \a PIString
|
||||||
|
//! \details
|
||||||
|
//! \~english Writes raw PIString data directly to the output stream without any formatting.
|
||||||
|
//! \~russian Записывает сырые данные PIString непосредственно в поток вывода без какого-либо форматирования.
|
||||||
PICout & write(const PIString & s);
|
PICout & write(const PIString & s);
|
||||||
|
|
||||||
//! \~english Output \a PIString to stdout
|
//! \~english Output \a PIString to stdout
|
||||||
@@ -386,11 +464,19 @@ public:
|
|||||||
|
|
||||||
//! \~english Construct with external buffer.
|
//! \~english Construct with external buffer.
|
||||||
//! \~russian Конструктор с внешним буфером.
|
//! \~russian Конструктор с внешним буфером.
|
||||||
|
//! \details
|
||||||
|
//! \~english Creates a PICout instance that outputs to an external PIString buffer with specified control flags.
|
||||||
|
//! \~russian Создает экземпляр PICout, который выводит данные во внешний буфер PIString с указанными флагами управления.
|
||||||
static PICout withExternalBuffer(PIString * buffer,
|
static PICout withExternalBuffer(PIString * buffer,
|
||||||
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces);
|
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::AddSpaces);
|
||||||
|
|
||||||
//! \~english Construct with external buffer and ID "id". See \a Notifier for details
|
//! \~english Construct with external buffer and ID "id". See \a Notifier for details
|
||||||
//! \~russian Конструктор с внешним буфером и ID "id". Подробнее \a Notifier
|
//! \~russian Конструктор с внешним буфером и ID "id". Подробнее \a Notifier
|
||||||
|
//! \details
|
||||||
|
//! \~english Creates a PICout instance with external buffer and notification ID. When the last copy is destroyed, it emits a finished()
|
||||||
|
//! event via Notifier.
|
||||||
|
//! \~russian Создает экземпляр PICout с внешним буфером и идентификатором уведомления. При уничтожении последней копии посылается
|
||||||
|
//! событие finished() через Notifier.
|
||||||
static PICout withExternalBufferAndID(PIString * buffer,
|
static PICout withExternalBufferAndID(PIString * buffer,
|
||||||
int id,
|
int id,
|
||||||
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::DefaultControls);
|
PIFlags<PICoutManipulators::PICoutControl> controls = PICoutManipulators::DefaultControls);
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/*! \file piincludes.h
|
/*! \file piincludes.h
|
||||||
* \ingroup Core
|
* \ingroup Core
|
||||||
* \~\brief
|
* \~\brief
|
||||||
* \~english Minimal PIP includes
|
* \~english Core includes and low-level helper functions
|
||||||
* \~russian Минимально-необходимые инклюды PIP
|
* \~russian Базовые включения и низкоуровневые вспомогательные функции
|
||||||
*/
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
@@ -50,27 +50,42 @@ class PIWaitEvent;
|
|||||||
|
|
||||||
struct lconv;
|
struct lconv;
|
||||||
|
|
||||||
|
//! \~\ingroup Core
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Pointer to current C locale numeric settings
|
||||||
|
//! \~russian Указатель на текущие числовые настройки C locale
|
||||||
extern PIP_EXPORT lconv * currentLocale;
|
extern PIP_EXPORT lconv * currentLocale;
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Return readable error description in format "code <number> - <description>"
|
//! \~english Returns readable description of the last system error in format
|
||||||
//! \~russian Возвращает читаемое описание ошибки в формате "code <номер> - <описание>"
|
//! "code <number> - <description>"
|
||||||
|
//! \~russian Возвращает читаемое описание последней системной ошибки в формате
|
||||||
|
//! "code <номер> - <описание>"
|
||||||
PIP_EXPORT PIString errorString();
|
PIP_EXPORT PIString errorString();
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Reset last error
|
//! \~english Clears the last system error
|
||||||
//! \~russian Сброс последней ошибки
|
//! \~russian Сбрасывает последнюю системную ошибку
|
||||||
PIP_EXPORT void errorClear();
|
PIP_EXPORT void errorClear();
|
||||||
|
|
||||||
|
//! \~\ingroup Core
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Seeds the global pseudo-random generator
|
||||||
|
//! \~russian Инициализирует глобальный генератор псевдослучайных чисел
|
||||||
PIP_EXPORT void randomize();
|
PIP_EXPORT void randomize();
|
||||||
|
|
||||||
|
//! \~\ingroup Core
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Returns next value from the global pseudo-random generator
|
||||||
|
//! \~russian Возвращает следующее значение глобального генератора псевдослучайных чисел
|
||||||
PIP_EXPORT int randomi();
|
PIP_EXPORT int randomi();
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Return readable version of PIP
|
//! \~english Returns readable PIP version string
|
||||||
//! \~russian Возвращает читаемую версию PIP
|
//! \~russian Возвращает строку версии PIP
|
||||||
PIP_EXPORT PIString PIPVersion();
|
PIP_EXPORT PIString PIPVersion();
|
||||||
|
|
||||||
#endif // PIINCLUDES_H
|
#endif // PIINCLUDES_H
|
||||||
|
|||||||
@@ -1,9 +1,12 @@
|
|||||||
/*! \file piinit.h
|
//! \~\ingroup Core
|
||||||
* \ingroup Core
|
//! \~\file piinit.h
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Library initialization
|
//! \~english Library initialization
|
||||||
* \~russian Инициализация библиотеки
|
//! \~russian Инициализация библиотеки
|
||||||
*/
|
//! \details
|
||||||
|
//! \~english This file provides initialization and build information for the PIP library.
|
||||||
|
//! \~russian Этот файл предоставляет инициализацию и информацию о сборке для библиотеки PIP.//! \}
|
||||||
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Initialization
|
Initialization
|
||||||
@@ -36,7 +39,6 @@
|
|||||||
class PIFile;
|
class PIFile;
|
||||||
class PIStringList;
|
class PIStringList;
|
||||||
|
|
||||||
|
|
||||||
class PIP_EXPORT __PIInit_Initializer__ {
|
class PIP_EXPORT __PIInit_Initializer__ {
|
||||||
public:
|
public:
|
||||||
__PIInit_Initializer__();
|
__PIInit_Initializer__();
|
||||||
@@ -47,7 +49,10 @@ public:
|
|||||||
|
|
||||||
static __PIInit_Initializer__ __piinit_initializer__;
|
static __PIInit_Initializer__ __piinit_initializer__;
|
||||||
|
|
||||||
|
//! \~\ingroup Core
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Library initialization singleton and build information access point.
|
||||||
|
//! \~russian Синглтон инициализации библиотеки и точка доступа к сведениям о сборке.
|
||||||
class PIP_EXPORT PIInit {
|
class PIP_EXPORT PIInit {
|
||||||
friend class __PIInit_Initializer__;
|
friend class __PIInit_Initializer__;
|
||||||
friend class PIFile;
|
friend class PIFile;
|
||||||
@@ -55,9 +60,9 @@ class PIP_EXPORT PIInit {
|
|||||||
public:
|
public:
|
||||||
~PIInit();
|
~PIInit();
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~english Build options which PIP library was built
|
//! \~english Build options enabled in the current PIP library
|
||||||
//! \~russian Опции, с которыми был собран PIP
|
//! \~russian Опции, включенные в текущей сборке библиотеки PIP
|
||||||
enum BuildOption {
|
enum BuildOption {
|
||||||
boICU /*! \~english Unicode support by ICU \~russian Поддержка юникода через ICU */ = 0x01,
|
boICU /*! \~english Unicode support by ICU \~russian Поддержка юникода через ICU */ = 0x01,
|
||||||
boUSB /*! \~english USB support \~russian Поддержка USB */ = 0x02,
|
boUSB /*! \~english USB support \~russian Поддержка USB */ = 0x02,
|
||||||
@@ -69,16 +74,19 @@ public:
|
|||||||
boCloud /*! \~english PICloud transport support \~russian Поддержка облачного транспорта PICloud */ = 0x200,
|
boCloud /*! \~english PICloud transport support \~russian Поддержка облачного транспорта PICloud */ = 0x200,
|
||||||
boConsole /*! \~english Console graphics support \~russian Поддержка графики в консоли */ = 0x400,
|
boConsole /*! \~english Console graphics support \~russian Поддержка графики в консоли */ = 0x400,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Returns current global %PIInit instance.
|
||||||
|
//! \~russian Возвращает текущий глобальный экземпляр %PIInit.
|
||||||
static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
|
static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~english Returns if build option was enabled
|
//! \~english Returns whether build option was enabled
|
||||||
//! \~russian Возвращает была ли включена опция при сборке
|
//! \~russian Возвращает, была ли опция включена при сборке
|
||||||
static bool isBuildOptionEnabled(BuildOption o);
|
static bool isBuildOptionEnabled(BuildOption o);
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~english Returns build options as stringlist
|
//! \~english Returns enabled build options as string list
|
||||||
//! \~russian Возвращает опции сборки как список строк
|
//! \~russian Возвращает включенные опции сборки в виде списка строк
|
||||||
static PIStringList buildOptions();
|
static PIStringList buildOptions();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,15 @@
|
|||||||
/*! \file pimemoryblock.h
|
//! \~\ingroup Core
|
||||||
* \ingroup Core
|
|
||||||
* \~\brief
|
//! \~\file pimemoryblock.h
|
||||||
* \~english Base types and functions
|
//! \brief
|
||||||
* \~russian Базовые типы и методы
|
//! \~english Memory block helper struct for data storage and binary stream operations
|
||||||
*/
|
//! \~russian Вспомогательная структура памяти для хранения данных и операций с двоичным потоком
|
||||||
|
//! \details
|
||||||
|
//! \~english The PIMemoryBlock struct provides a lightweight wrapper to store and restore custom blocks of data to/from PIBinaryStream. It
|
||||||
|
//! holds a pointer to data and its size in bytes.
|
||||||
|
//! \~russian Структура PIMemoryBlock предоставляет легковесный wrapper для сохранения и извлечения произвольных блоков данных в/из
|
||||||
|
//! PIBinaryStream. Она содержит указатель на данные и их размер в байтах.
|
||||||
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Base types and functions
|
Base types and functions
|
||||||
@@ -27,49 +33,52 @@
|
|||||||
#define PIMEMORYBLOCK_H
|
#define PIMEMORYBLOCK_H
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup Core
|
|
||||||
//! \include pimemoryblock.h
|
//! \~\brief
|
||||||
//! \brief
|
//! \~english Helper struct to store and restore custom blocks of data to/from PIBinaryStream
|
||||||
//! \~english Help struct to store/restore custom blocks of data to/from PIBinaryStream
|
//! \~russian Вспомогательная структура для сохранения и извлечения произвольных блоков данных в/из PIBinaryStream
|
||||||
//! \~russian Вспомогательная структура для сохранения/извлечения произвольного блока данных в/из PIBinaryStream
|
|
||||||
struct PIMemoryBlock {
|
struct PIMemoryBlock {
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs data block
|
//! \~english Constructs empty memory block.
|
||||||
//! \~russian Создает блок данных
|
//! \~russian Создает пустой блок памяти.
|
||||||
PIMemoryBlock() {}
|
PIMemoryBlock() {}
|
||||||
|
|
||||||
//! \~english Constructs data block
|
//! \~english Constructs memory block from pointer and size.
|
||||||
//! \~russian Создает блок данных
|
//! \~russian Создает блок памяти из указателя и размера.
|
||||||
PIMemoryBlock(const void * data_, const int size_) {
|
PIMemoryBlock(const void * data_, const int size_) {
|
||||||
d = const_cast<void *>(data_);
|
d = const_cast<void *>(data_);
|
||||||
s = size_;
|
s = size_;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Copy constructor.
|
||||||
|
//! \~russian Конструктор копирования.
|
||||||
PIMemoryBlock(const PIMemoryBlock & o) {
|
PIMemoryBlock(const PIMemoryBlock & o) {
|
||||||
d = o.d;
|
d = o.d;
|
||||||
s = o.s;
|
s = o.s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Copy assignment operator.
|
||||||
|
//! \~russian Оператор присваивания копированием.
|
||||||
PIMemoryBlock & operator=(const PIMemoryBlock & o) {
|
PIMemoryBlock & operator=(const PIMemoryBlock & o) {
|
||||||
d = o.d;
|
d = o.d;
|
||||||
s = o.s;
|
s = o.s;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Pointer to data
|
//! \~english Returns pointer to block data.
|
||||||
//! \~russian Указатель на данные
|
//! \~russian Возвращает указатель на данные блока.
|
||||||
void * data() { return d; }
|
void * data() { return d; }
|
||||||
|
|
||||||
//! \~english Pointer to data
|
//! \~english Returns pointer to block data.
|
||||||
//! \~russian Указатель на данные
|
//! \~russian Возвращает указатель на данные блока.
|
||||||
const void * data() const { return d; }
|
const void * data() const { return d; }
|
||||||
|
|
||||||
//! \~english Size of data in bytes
|
//! \~english Returns block size in bytes.
|
||||||
//! \~russian Размер данных в байтах
|
//! \~russian Возвращает размер блока в байтах.
|
||||||
int size() const { return s; }
|
int size() const { return s; }
|
||||||
|
|
||||||
//! \~english Returns if this block points to nothing
|
//! \~english Returns `true` when the block stores a non-null pointer.
|
||||||
//! \~russian Возвращает пустой ли указатель на данные
|
//! \~russian Возвращает `true`, когда блок хранит ненулевой указатель.
|
||||||
bool isNull() const { return d; }
|
bool isNull() const { return d; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -77,8 +86,10 @@ private:
|
|||||||
int s = 0;
|
int s = 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Returns PIMemoryBlock from pointer to variable "ptr" with type "T"
|
//! \~\ingroup Core
|
||||||
//! \~russian Возвращает PIMemoryBlock из указателя "ptr" типа "T"
|
//! \~\brief
|
||||||
|
//! \~english Creates %PIMemoryBlock for object pointed by "ptr".
|
||||||
|
//! \~russian Создает %PIMemoryBlock для объекта, на который указывает "ptr".
|
||||||
template<typename T>
|
template<typename T>
|
||||||
PIMemoryBlock createMemoryBlock(const T * ptr) {
|
PIMemoryBlock createMemoryBlock(const T * ptr) {
|
||||||
return PIMemoryBlock(ptr, sizeof(T));
|
return PIMemoryBlock(ptr, sizeof(T));
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piobject.h
|
//! \~\ingroup Core
|
||||||
* \ingroup Core
|
//! \~\file piobject.h
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Base object
|
//! \~english Base object class providing event -> handler mechanism
|
||||||
* \~russian Базовый класс
|
//! \~russian Базовый класс объектов, обеспечивающий механизм событий -> обработчиков
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Object, base class of some PIP classes, provide EVENT -> EVENT_HANDLER mechanism
|
Object, base class of some PIP classes, provide EVENT -> EVENT_HANDLER mechanism
|
||||||
@@ -34,10 +33,26 @@
|
|||||||
#include "pivariant.h"
|
#include "pivariant.h"
|
||||||
#include "pivariantsimple.h"
|
#include "pivariantsimple.h"
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english This is base class for any classes which use events -> handlers mechanism.
|
//! \~english Base class for objects that declare events, event handlers and registered methods.
|
||||||
//! \~russian Этот класс является базовым для использования механизма события -> обработчики.
|
//! \~russian Базовый класс для объектов, которые объявляют события, обработчики событий и зарегистрированные методы.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! PIObject is the base class for all PIP classes that need event-driven communication.
|
||||||
|
//! It provides signal-slot mechanism, property system, and object lifetime management.
|
||||||
|
//! %PIObject stores named properties, keeps connection state and exposes a
|
||||||
|
//! small metaobject table used by \a CONNECTU(), \a execute() and related APIs.
|
||||||
|
//! Queued delivery runs on the performer object and requires explicit draining
|
||||||
|
//! through \a callQueuedEvents() or \a maybeCallQueuedEvents().
|
||||||
|
//! \~russian
|
||||||
|
//! PIObject является базовым классом для всех классов PIP, которым необходима событийная коммуникация.
|
||||||
|
//! Он обеспечивает механизм сигналов-слотов, систему свойств и управление жизненным циклом объектов.
|
||||||
|
//! %PIObject хранит именованные свойства, состояние соединений и небольшую
|
||||||
|
//! метаобъектную таблицу, которую используют \a CONNECTU(), \a execute() и
|
||||||
|
//! связанные методы. Отложенная доставка выполняется на объекте-исполнителе и
|
||||||
|
//! требует явного опустошения очереди через \a callQueuedEvents() или
|
||||||
|
//! \a maybeCallQueuedEvents().
|
||||||
class PIP_EXPORT PIObject {
|
class PIP_EXPORT PIObject {
|
||||||
#ifndef MICRO_PIP
|
#ifndef MICRO_PIP
|
||||||
friend class PIObjectManager;
|
friend class PIObjectManager;
|
||||||
@@ -50,16 +65,18 @@ class PIP_EXPORT PIObject {
|
|||||||
public:
|
public:
|
||||||
NO_COPY_CLASS(PIObject);
|
NO_COPY_CLASS(PIObject);
|
||||||
|
|
||||||
//! \~english Contructs %PIObject with name "name"
|
//! \~english Constructs an object and initializes its \c name property.
|
||||||
//! \~russian Создает %PIObject с именем "name"
|
//! \~russian Создает объект и инициализирует его свойство \c name.
|
||||||
explicit PIObject(const PIString & name = PIString());
|
explicit PIObject(const PIString & name = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the object, raises \a deleted() and disconnects it from the event graph.
|
||||||
|
//! \~russian Уничтожает объект, вызывает \a deleted() и отключает его от событийного графа.
|
||||||
virtual ~PIObject();
|
virtual ~PIObject();
|
||||||
|
|
||||||
//! \ingroup Core
|
//! \~\ingroup Core
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Helper class for obtain info about if connection successful and disconnect single connection.
|
//! \~english Handle of one connection between a source object and a destination object or functor.
|
||||||
//! \~russian Вспомогательный класс для получения информации об успешности соединения и возможности его разрыва.
|
//! \~russian Дескриптор одного соединения между объектом-источником и объектом-приемником либо функтором.
|
||||||
class PIP_EXPORT Connection {
|
class PIP_EXPORT Connection {
|
||||||
friend class PIObject;
|
friend class PIObject;
|
||||||
Connection(void * sl,
|
Connection(void * sl,
|
||||||
@@ -93,28 +110,31 @@ public:
|
|||||||
int args_count;
|
int args_count;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs invalid %Connection
|
//! \~english Constructs an invalid connection handle.
|
||||||
//! \~russian Создает недействительный %Connection
|
//! \~russian Создает недействительный дескриптор соединения.
|
||||||
Connection();
|
Connection();
|
||||||
|
|
||||||
//! \~english Returns if %Connection is valid
|
//! \~english Returns \c true when the connection was created successfully.
|
||||||
//! \~russian Возвращает успешен ли %Connection
|
//! \~russian Возвращает \c true, если соединение было успешно создано.
|
||||||
bool isValid() const { return signal; }
|
bool isValid() const { return signal; }
|
||||||
|
|
||||||
//! \~english Returns source object
|
//! \~english Returns the source object that emits the event.
|
||||||
//! \~russian Возвращает объект-источник
|
//! \~russian Возвращает объект-источник, который испускает событие.
|
||||||
PIObject * sourceObject() const { return src_o; }
|
PIObject * sourceObject() const { return src_o; }
|
||||||
|
|
||||||
//! \~english Returns destination object or "nullptr" if this is lambda connection
|
//! \~english Returns the destination object, or \c nullptr for a lambda connection.
|
||||||
//! \~russian Возвращает объект-приемник или "nullptr" если это соединение на лямбда-функцию
|
//! \~russian Возвращает объект-приемник, либо \c nullptr для соединения с лямбда-функцией.
|
||||||
PIObject * destinationObject() const { return dest_o; }
|
PIObject * destinationObject() const { return dest_o; }
|
||||||
|
|
||||||
//! \~english Returns performer object or "nullptr" if this is non-queued connection
|
//! \~english Returns the performer object, or \c nullptr for direct delivery.
|
||||||
//! \~russian Возвращает объект-исполнитель или "nullptr" если это соединение не отложенное
|
//! \~russian Возвращает объект-исполнитель, либо \c nullptr для прямой доставки.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Queued delivery runs only when the performer drains its queue.
|
||||||
|
//! \~russian Отложенная доставка выполняется только когда исполнитель обрабатывает свою очередь.
|
||||||
PIObject * performerObject() const { return performer; }
|
PIObject * performerObject() const { return performer; }
|
||||||
|
|
||||||
//! \~english Disconnect this %Connection, returns if operation successful
|
//! \~english Disconnects this single connection.
|
||||||
//! \~russian Разрывает этот %Connection, возвращает успешен ли разрыв
|
//! \~russian Разрывает только это соединение.
|
||||||
bool disconnect() const;
|
bool disconnect() const;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -122,14 +142,16 @@ private:
|
|||||||
uint _signature_;
|
uint _signature_;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Returns object name
|
//! \~english Returns the \c name property of this object.
|
||||||
//! \~russian Возвращает имя объекта
|
//! \~russian Возвращает свойство \c name этого объекта.
|
||||||
PIString name() const { return property("name").toString(); }
|
PIString name() const { return property("name").toString(); }
|
||||||
|
|
||||||
//! \~english Returns object class name
|
//! \~english Returns the registered class name of this object.
|
||||||
//! \~russian Возвращает имя класса объекта
|
//! \~russian Возвращает зарегистрированное имя класса этого объекта.
|
||||||
virtual const char * className() const { return "PIObject"; }
|
virtual const char * className() const { return "PIObject"; }
|
||||||
|
|
||||||
|
//! \~english Returns the hash of \a className().
|
||||||
|
//! \~russian Возвращает хэш от \a className().
|
||||||
virtual uint classNameID() const {
|
virtual uint classNameID() const {
|
||||||
static uint ret = PIStringAscii("PIObject").hash();
|
static uint ret = PIStringAscii("PIObject").hash();
|
||||||
return ret;
|
return ret;
|
||||||
@@ -141,51 +163,87 @@ public:
|
|||||||
return ret;
|
return ret;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns parent class name
|
//! \~english Returns the registered parent class name, or an empty string for the root.
|
||||||
//! \~russian Возвращает имя родительского класса
|
//! \~russian Возвращает зарегистрированное имя родительского класса, либо пустую строку для корня.
|
||||||
virtual const char * parentClassName() const { return ""; }
|
virtual const char * parentClassName() const { return ""; }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Return if \a piCoutObj of this object is active
|
//! \~english Returns whether \a piCoutObj output is enabled for this object.
|
||||||
//! \~russian Возвращает включен ли вывод \a piCoutObj для этого объекта
|
//! \~russian Возвращает, включен ли вывод \a piCoutObj для этого объекта.
|
||||||
bool debug() const { return property("debug").toBool(); }
|
bool debug() const { return property("debug").toBool(); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Set object name
|
//! \~english Sets the \c name property of this object.
|
||||||
//! \~russian Устанавливает имя объекта
|
//! \~russian Устанавливает свойство \c name этого объекта.
|
||||||
void setName(const PIString & name) { setProperty("name", name); }
|
void setName(const PIString & name) { setProperty("name", name); }
|
||||||
|
|
||||||
//! \~english Set object \a piCoutObj active
|
//! \~english Enables or disables \a piCoutObj output for this object.
|
||||||
//! \~russian Включает или отключает вывод \a piCoutObj для этого объекта
|
//! \~russian Включает или отключает вывод \a piCoutObj для этого объекта.
|
||||||
void setDebug(bool debug) { setProperty("debug", debug); }
|
void setDebug(bool debug) { setProperty("debug", debug); }
|
||||||
|
|
||||||
//! \~english Returns property with name "name"
|
//! \~english Returns the property with name "name".
|
||||||
//! \~russian Возвращает свойство объекта по имени "name"
|
//! \~russian Возвращает свойство объекта по имени "name".
|
||||||
PIVariant property(const char * name) const { return properties_.value(piHashData((const uchar *)name, strlen(name))); }
|
PIVariant property(const char * name) const { return properties_.value(piHashData((const uchar *)name, strlen(name))); }
|
||||||
|
|
||||||
//! \~english Set property with name "name" to "value". If there is no such property in object it will be added
|
//! \~english Sets the property "name" to "value" and creates it if needed.
|
||||||
//! \~russian Устанавливает у объекта свойство по имени "name" в "value". Если такого свойства нет, оно добавляется
|
//! \~russian Устанавливает свойство "name" в значение "value" и создаёт его при необходимости.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Calls \a propertyChanged() after updating the stored value.
|
||||||
|
//! \~russian После обновления сохранённого значения вызывает \a propertyChanged().
|
||||||
void setProperty(const char * name, const PIVariant & value) {
|
void setProperty(const char * name, const PIVariant & value) {
|
||||||
properties_[piHashData((const uchar *)name, strlen(name))] = value;
|
properties_[piHashData((const uchar *)name, strlen(name))] = value;
|
||||||
propertyChanged(name);
|
propertyChanged(name);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns if property with name "name" exists
|
//! \~english Returns whether the property "name" exists.
|
||||||
//! \~russian Возвращает присутствует ли свойство по имени "name"
|
//! \~russian Возвращает, существует ли свойство "name".
|
||||||
bool isPropertyExists(const char * name) const { return properties_.contains(piHashData((const uchar *)name, strlen(name))); }
|
bool isPropertyExists(const char * name) const { return properties_.contains(piHashData((const uchar *)name, strlen(name))); }
|
||||||
|
|
||||||
|
//! \~english Enables or disables the internal object mutex during handler execution.
|
||||||
|
//! \~russian Включает или отключает внутренний мьютекс объекта во время выполнения обработчиков.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This flag affects direct and queued handler invocation for this object, but does not describe full thread-safety of the
|
||||||
|
//! class.
|
||||||
|
//! \~russian Этот флаг влияет на прямой и отложенный вызов обработчиков для данного объекта, но не описывает полную потокобезопасность
|
||||||
|
//! класса.
|
||||||
void setThreadSafe(bool yes) { thread_safe_ = yes; }
|
void setThreadSafe(bool yes) { thread_safe_ = yes; }
|
||||||
|
//! \~english Returns whether the internal object mutex is enabled for handler execution.
|
||||||
|
//! \~russian Возвращает, включен ли внутренний мьютекс объекта для выполнения обработчиков.
|
||||||
bool isThreadSafe() const { return thread_safe_; }
|
bool isThreadSafe() const { return thread_safe_; }
|
||||||
|
|
||||||
|
//! \~english Executes a registered method or handler method by name with the supplied arguments.
|
||||||
|
//! \~russian Выполняет зарегистрированный метод или метод-обработчик по имени с переданными аргументами.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! This helper works only with the registered-method table built from
|
||||||
|
//! \a EVENT_HANDLER*() and \a EVENT*() declarations. It does not provide
|
||||||
|
//! arbitrary reflection or complex overload resolution: the implementation
|
||||||
|
//! selects a suitable registered method by name and argument count.
|
||||||
|
//! \~russian
|
||||||
|
//! Этот вспомогательный метод работает только с таблицей зарегистрированных
|
||||||
|
//! методов, построенной из объявлений \a EVENT_HANDLER*() и \a EVENT*().
|
||||||
|
//! Он не предоставляет произвольную рефлексию и сложное разрешение
|
||||||
|
//! перегрузок: реализация выбирает подходящий зарегистрированный метод по
|
||||||
|
//! имени и числу аргументов.
|
||||||
bool execute(const PIString & method, const PIVector<PIVariantSimple> & vl);
|
bool execute(const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||||
|
//! \~english Overload of \a execute() for a method without arguments.
|
||||||
|
//! \~russian Перегрузка \a execute() для метода без аргументов.
|
||||||
bool execute(const PIString & method) { return execute(method, PIVector<PIVariantSimple>()); }
|
bool execute(const PIString & method) { return execute(method, PIVector<PIVariantSimple>()); }
|
||||||
|
//! \~english Overload of \a execute() for one argument.
|
||||||
|
//! \~russian Перегрузка \a execute() для одного аргумента.
|
||||||
bool execute(const PIString & method, const PIVariantSimple & v0) { return execute(method, PIVector<PIVariantSimple>() << v0); }
|
bool execute(const PIString & method, const PIVariantSimple & v0) { return execute(method, PIVector<PIVariantSimple>() << v0); }
|
||||||
|
//! \~english Overload of \a execute() for two arguments.
|
||||||
|
//! \~russian Перегрузка \a execute() для двух аргументов.
|
||||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1);
|
return execute(method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a execute() for three arguments.
|
||||||
|
//! \~russian Перегрузка \a execute() для трёх аргументов.
|
||||||
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
bool execute(const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a execute() for four arguments.
|
||||||
|
//! \~russian Перегрузка \a execute() для четырёх аргументов.
|
||||||
bool execute(const PIString & method,
|
bool execute(const PIString & method,
|
||||||
const PIVariantSimple & v0,
|
const PIVariantSimple & v0,
|
||||||
const PIVariantSimple & v1,
|
const PIVariantSimple & v1,
|
||||||
@@ -194,16 +252,36 @@ public:
|
|||||||
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
return execute(method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Queues execution of a registered method on the performer object.
|
||||||
|
//! \~russian Ставит выполнение зарегистрированного метода в очередь объекта-исполнителя.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! Delivery happens only when "performer" later calls \a callQueuedEvents()
|
||||||
|
//! or \a maybeCallQueuedEvents(). Argument values are transported through
|
||||||
|
//! \a PIVariantSimple, so queued arguments should be representable there.
|
||||||
|
//! \~russian
|
||||||
|
//! Доставка происходит только когда "performer" позже вызывает
|
||||||
|
//! \a callQueuedEvents() или \a maybeCallQueuedEvents(). Значения аргументов
|
||||||
|
//! передаются через \a PIVariantSimple, поэтому аргументы очереди должны в
|
||||||
|
//! нём представляться.
|
||||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl);
|
bool executeQueued(PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl);
|
||||||
|
//! \~english Overload of \a executeQueued() for a method without arguments.
|
||||||
|
//! \~russian Перегрузка \a executeQueued() для метода без аргументов.
|
||||||
bool executeQueued(PIObject * performer, const PIString & method) {
|
bool executeQueued(PIObject * performer, const PIString & method) {
|
||||||
return executeQueued(performer, method, PIVector<PIVariantSimple>());
|
return executeQueued(performer, method, PIVector<PIVariantSimple>());
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a executeQueued() for one argument.
|
||||||
|
//! \~russian Перегрузка \a executeQueued() для одного аргумента.
|
||||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0);
|
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0);
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a executeQueued() for two arguments.
|
||||||
|
//! \~russian Перегрузка \a executeQueued() для двух аргументов.
|
||||||
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
bool executeQueued(PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a executeQueued() for three arguments.
|
||||||
|
//! \~russian Перегрузка \a executeQueued() для трёх аргументов.
|
||||||
bool executeQueued(PIObject * performer,
|
bool executeQueued(PIObject * performer,
|
||||||
const PIString & method,
|
const PIString & method,
|
||||||
const PIVariantSimple & v0,
|
const PIVariantSimple & v0,
|
||||||
@@ -211,6 +289,8 @@ public:
|
|||||||
const PIVariantSimple & v2) {
|
const PIVariantSimple & v2) {
|
||||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a executeQueued() for four arguments.
|
||||||
|
//! \~russian Перегрузка \a executeQueued() для четырёх аргументов.
|
||||||
bool executeQueued(PIObject * performer,
|
bool executeQueued(PIObject * performer,
|
||||||
const PIString & method,
|
const PIString & method,
|
||||||
const PIVariantSimple & v0,
|
const PIVariantSimple & v0,
|
||||||
@@ -220,18 +300,30 @@ public:
|
|||||||
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
return executeQueued(performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Static convenience wrapper for \a execute().
|
||||||
|
//! \~russian Статическая удобная обёртка над \a execute().
|
||||||
static bool execute(PIObject * o, const PIString & method, const PIVector<PIVariantSimple> & vl) { return o->execute(method, vl); }
|
static bool execute(PIObject * o, const PIString & method, const PIVector<PIVariantSimple> & vl) { return o->execute(method, vl); }
|
||||||
|
//! \~english Static overload of \a execute() without arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a execute() без аргументов.
|
||||||
static bool execute(PIObject * o, const PIString & method) { return execute(o, method, PIVector<PIVariantSimple>()); }
|
static bool execute(PIObject * o, const PIString & method) { return execute(o, method, PIVector<PIVariantSimple>()); }
|
||||||
|
//! \~english Static overload of \a execute() for one argument.
|
||||||
|
//! \~russian Статическая перегрузка \a execute() для одного аргумента.
|
||||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0) {
|
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0) {
|
||||||
return execute(o, method, PIVector<PIVariantSimple>() << v0);
|
return execute(o, method, PIVector<PIVariantSimple>() << v0);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a execute() for two arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a execute() для двух аргументов.
|
||||||
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
static bool execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1);
|
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a execute() for three arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a execute() для трёх аргументов.
|
||||||
static bool
|
static bool
|
||||||
execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
execute(PIObject * o, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1, const PIVariantSimple & v2) {
|
||||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a execute() for four arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a execute() для четырёх аргументов.
|
||||||
static bool execute(PIObject * o,
|
static bool execute(PIObject * o,
|
||||||
const PIString & method,
|
const PIString & method,
|
||||||
const PIVariantSimple & v0,
|
const PIVariantSimple & v0,
|
||||||
@@ -241,19 +333,29 @@ public:
|
|||||||
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
return execute(o, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Static convenience wrapper for \a executeQueued().
|
||||||
|
//! \~russian Статическая удобная обёртка над \a executeQueued().
|
||||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVector<PIVariantSimple> & vl) {
|
||||||
return o->executeQueued(performer, method, vl);
|
return o->executeQueued(performer, method, vl);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a executeQueued() without arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a executeQueued() без аргументов.
|
||||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method) {
|
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method) {
|
||||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>());
|
return executeQueued(o, performer, method, PIVector<PIVariantSimple>());
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a executeQueued() for one argument.
|
||||||
|
//! \~russian Статическая перегрузка \a executeQueued() для одного аргумента.
|
||||||
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
static bool executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0) {
|
||||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0);
|
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a executeQueued() for two arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a executeQueued() для двух аргументов.
|
||||||
static bool
|
static bool
|
||||||
executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
executeQueued(PIObject * o, PIObject * performer, const PIString & method, const PIVariantSimple & v0, const PIVariantSimple & v1) {
|
||||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a executeQueued() for three arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a executeQueued() для трёх аргументов.
|
||||||
static bool executeQueued(PIObject * o,
|
static bool executeQueued(PIObject * o,
|
||||||
PIObject * performer,
|
PIObject * performer,
|
||||||
const PIString & method,
|
const PIString & method,
|
||||||
@@ -262,6 +364,8 @@ public:
|
|||||||
const PIVariantSimple & v2) {
|
const PIVariantSimple & v2) {
|
||||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2);
|
||||||
}
|
}
|
||||||
|
//! \~english Static overload of \a executeQueued() for four arguments.
|
||||||
|
//! \~russian Статическая перегрузка \a executeQueued() для четырёх аргументов.
|
||||||
static bool executeQueued(PIObject * o,
|
static bool executeQueued(PIObject * o,
|
||||||
PIObject * performer,
|
PIObject * performer,
|
||||||
const PIString & method,
|
const PIString & method,
|
||||||
@@ -272,22 +376,37 @@ public:
|
|||||||
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
return executeQueued(o, performer, method, PIVector<PIVariantSimple>() << v0 << v1 << v2 << v3);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Dumps object diagnostics to the project output stream.
|
||||||
|
//! \~russian Выводит диагностическую информацию об объекте в проектный поток вывода.
|
||||||
void dump(const PIString & line_prefix = PIString()) const;
|
void dump(const PIString & line_prefix = PIString()) const;
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns subclass scope of this object (including this class name)
|
//! \~english Returns the registered inheritance scope of this object, including its own class.
|
||||||
//! \~russian Возвращает цепочку наследования объекта (вместе с классом самого объекта)
|
//! \~russian Возвращает зарегистрированную цепочку наследования объекта, включая его собственный класс.
|
||||||
PIStringList scopeList() const;
|
PIStringList scopeList() const;
|
||||||
|
|
||||||
|
//! \~english Returns full signatures of all registered event and handler methods for this class scope.
|
||||||
|
//! \~russian Возвращает полные сигнатуры всех зарегистрированных событий и обработчиков для области этого класса.
|
||||||
PIStringList methodsEH() const;
|
PIStringList methodsEH() const;
|
||||||
|
//! \~english Returns whether a registered event or handler method with this name exists.
|
||||||
|
//! \~russian Возвращает, существует ли зарегистрированное событие или обработчик с таким именем.
|
||||||
bool isMethodEHContains(const PIString & name) const;
|
bool isMethodEHContains(const PIString & name) const;
|
||||||
|
//! \~english Returns the comma-separated argument type list of a registered method.
|
||||||
|
//! \~russian Возвращает список типов аргументов зарегистрированного метода через запятую.
|
||||||
PIString methodEHArguments(const PIString & name) const;
|
PIString methodEHArguments(const PIString & name) const;
|
||||||
|
//! \~english Returns the full registered signature of a method.
|
||||||
|
//! \~russian Возвращает полную зарегистрированную сигнатуру метода.
|
||||||
PIString methodEHFullFormat(const PIString & name) const;
|
PIString methodEHFullFormat(const PIString & name) const;
|
||||||
|
//! \~english Returns the registered method name for the specified entry-point address.
|
||||||
|
//! \~russian Возвращает имя зарегистрированного метода для указанного адреса точки входа.
|
||||||
PIString methodEHFromAddr(const void * addr) const;
|
PIString methodEHFromAddr(const void * addr) const;
|
||||||
|
|
||||||
// / Direct connect
|
//! \~english Low-level direct connection helper behind the legacy \c CONNECT* macros.
|
||||||
|
//! \~russian Низкоуровневый помощник прямого соединения, лежащий под устаревшими макросами \c CONNECT*.
|
||||||
static PIObject::Connection
|
static PIObject::Connection
|
||||||
piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc);
|
piConnect(PIObject * src, const PIString & sig, PIObject * dest_o, void * dest, void * ev_h, void * e_h, int args, const char * loc);
|
||||||
|
//! \~english Low-level name-based connection helper behind \a CONNECTU() and \a CONNECTU_QUEUED().
|
||||||
|
//! \~russian Низкоуровневый помощник соединения по имени, лежащий под \a CONNECTU() и \a CONNECTU_QUEUED().
|
||||||
static PIObject::Connection piConnectU(PIObject * src,
|
static PIObject::Connection piConnectU(PIObject * src,
|
||||||
const PIString & sig,
|
const PIString & sig,
|
||||||
PIObject * dest_o,
|
PIObject * dest_o,
|
||||||
@@ -295,6 +414,8 @@ public:
|
|||||||
const PIString & hname,
|
const PIString & hname,
|
||||||
const char * loc,
|
const char * loc,
|
||||||
PIObject * performer = 0);
|
PIObject * performer = 0);
|
||||||
|
//! \~english Low-level helper that connects an event to a lambda or functor wrapper.
|
||||||
|
//! \~russian Низкоуровневый помощник, который соединяет событие с лямбдой или обёрткой функтора.
|
||||||
static PIObject::Connection piConnectLS(PIObject * src, const PIString & sig, std::function<void()> * f, const char * loc);
|
static PIObject::Connection piConnectLS(PIObject * src, const PIString & sig, std::function<void()> * f, const char * loc);
|
||||||
template<typename PIINPUT, typename... PITYPES>
|
template<typename PIINPUT, typename... PITYPES>
|
||||||
static std::function<void()> * __newFunctor(void (*stat_handler)(void *, PITYPES...), PIINPUT functor) {
|
static std::function<void()> * __newFunctor(void (*stat_handler)(void *, PITYPES...), PIINPUT functor) {
|
||||||
@@ -302,33 +423,33 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest" and handler "ev_h"
|
//! \~english Disconnects this source object from a specific destination handler for event "sig".
|
||||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest" и обработчику "ev_h"
|
//! \~russian Разрывает соединения этого объекта-источника с конкретным обработчиком объекта-приемника для события "sig".
|
||||||
void piDisconnect(const PIString & sig, PIObject * dest, void * ev_h) { piDisconnect(this, sig, dest, ev_h); }
|
void piDisconnect(const PIString & sig, PIObject * dest, void * ev_h) { piDisconnect(this, sig, dest, ev_h); }
|
||||||
|
|
||||||
//! \~english Disconnect object from all connections with event name "sig", connected to destination object "dest"
|
//! \~english Disconnects this source object from all connections of event "sig" to destination object "dest".
|
||||||
//! \~russian Разрывает все соединения от события "sig" к объекту "dest"
|
//! \~russian Разрывает все соединения этого объекта-источника от события "sig" к объекту-приемнику "dest".
|
||||||
void piDisconnect(const PIString & sig, PIObject * dest) { piDisconnect(this, sig, dest); }
|
void piDisconnect(const PIString & sig, PIObject * dest) { piDisconnect(this, sig, dest); }
|
||||||
|
|
||||||
//! \~english Disconnect object from all connections with event name "sig"
|
//! \~english Disconnects this source object from all connections of event "sig".
|
||||||
//! \~russian Разрывает все соединения от события "sig"
|
//! \~russian Разрывает все соединения этого объекта-источника от события "sig".
|
||||||
void piDisconnect(const PIString & sig) { piDisconnect(this, sig); }
|
void piDisconnect(const PIString & sig) { piDisconnect(this, sig); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest" and handler
|
//! \~english Disconnects source object "src" from a specific destination handler for event "sig".
|
||||||
//! "ev_h"
|
//! \~russian Разрывает соединения объекта-источника "src" с конкретным обработчиком объекта-приемника для события "sig".
|
||||||
//! \~russian Разрывает все соединения от события "sig" объекта "src" к объекту "dest" и обработчику "ev_h"
|
|
||||||
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest, void * ev_h);
|
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest, void * ev_h);
|
||||||
|
|
||||||
//! \~english Disconnect object "src" from all connections with event name "sig", connected to destination object "dest"
|
//! \~english Disconnects source object "src" from all connections of event "sig" to destination object "dest".
|
||||||
//! \~russian Разрывает все соединения от события "sig" объекта "src" к объекту "dest"
|
//! \~russian Разрывает все соединения объекта-источника "src" от события "sig" к объекту-приемнику "dest".
|
||||||
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest);
|
static void piDisconnect(PIObject * src, const PIString & sig, PIObject * dest);
|
||||||
|
|
||||||
//! \~english Disconnect object "src" from all connections with event name "sig"
|
//! \~english Disconnects source object "src" from all connections of event "sig".
|
||||||
//! \~russian Разрывает все соединения от события "sig" объекта "src"
|
//! \~russian Разрывает все соединения объекта-источника "src" от события "sig".
|
||||||
static void piDisconnect(PIObject * src, const PIString & sig);
|
static void piDisconnect(PIObject * src, const PIString & sig);
|
||||||
|
|
||||||
// / Raise events
|
//! \~english Internal event delivery helper for registered events without arguments.
|
||||||
|
//! \~russian Внутренний помощник доставки для зарегистрированных событий без аргументов.
|
||||||
static void raiseEvent(PIObject * sender, const uint eventID) {
|
static void raiseEvent(PIObject * sender, const uint eventID) {
|
||||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||||
Connection i(sender->connections[j]);
|
Connection i(sender->connections[j]);
|
||||||
@@ -357,6 +478,8 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Internal event delivery helper for registered events with one argument.
|
||||||
|
//! \~russian Внутренний помощник доставки для зарегистрированных событий с одним аргументом.
|
||||||
template<typename T0>
|
template<typename T0>
|
||||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0()) {
|
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0()) {
|
||||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||||
@@ -390,6 +513,8 @@ public:
|
|||||||
if (!sender->isPIObject()) break;
|
if (!sender->isPIObject()) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//! \~english Internal event delivery helper for registered events with two arguments.
|
||||||
|
//! \~russian Внутренний помощник доставки для зарегистрированных событий с двумя аргументами.
|
||||||
template<typename T0, typename T1>
|
template<typename T0, typename T1>
|
||||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1()) {
|
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1()) {
|
||||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||||
@@ -425,6 +550,8 @@ public:
|
|||||||
if (!sender->isPIObject()) break;
|
if (!sender->isPIObject()) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//! \~english Internal event delivery helper for registered events with three arguments.
|
||||||
|
//! \~russian Внутренний помощник доставки для зарегистрированных событий с тремя аргументами.
|
||||||
template<typename T0, typename T1, typename T2>
|
template<typename T0, typename T1, typename T2>
|
||||||
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1(), const T2 & v2 = T2()) {
|
static void raiseEvent(PIObject * sender, const uint eventID, const T0 & v0 = T0(), const T1 & v1 = T1(), const T2 & v2 = T2()) {
|
||||||
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
for (int j = 0; j < sender->connections.size_s(); ++j) {
|
||||||
@@ -462,6 +589,8 @@ public:
|
|||||||
if (!sender->isPIObject()) break;
|
if (!sender->isPIObject()) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
//! \~english Internal event delivery helper for registered events with four arguments.
|
||||||
|
//! \~russian Внутренний помощник доставки для зарегистрированных событий с четырьмя аргументами.
|
||||||
template<typename T0, typename T1, typename T2, typename T3>
|
template<typename T0, typename T1, typename T2, typename T3>
|
||||||
static void raiseEvent(PIObject * sender,
|
static void raiseEvent(PIObject * sender,
|
||||||
const uint eventID,
|
const uint eventID,
|
||||||
@@ -507,7 +636,8 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns PIObject* with name "name" or 0, if there is no object found
|
//! \~english Returns the first live object with name "name", or \c nullptr.
|
||||||
|
//! \~russian Возвращает первый живой объект с именем "name", либо \c nullptr.
|
||||||
static PIObject * findByName(const PIString & name) {
|
static PIObject * findByName(const PIString & name) {
|
||||||
PIMutexLocker _ml(mutexObjects());
|
PIMutexLocker _ml(mutexObjects());
|
||||||
for (auto * i: PIObject::objects()) {
|
for (auto * i: PIObject::objects()) {
|
||||||
@@ -517,12 +647,12 @@ public:
|
|||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns if this is valid %PIObject (check signature)
|
//! \~english Returns whether this pointer still refers to a live %PIObject instance.
|
||||||
//! \~russian Возвращает действительный ли это %PIObject (проверяет подпись)
|
//! \~russian Возвращает, указывает ли этот указатель на ещё существующий экземпляр %PIObject.
|
||||||
bool isPIObject() const { return isPIObject(this); }
|
bool isPIObject() const { return isPIObject(this); }
|
||||||
|
|
||||||
//! \~english Returns if this is valid %PIObject subclass "T" (check signature and classname)
|
//! \~english Returns whether this object belongs to class "T" or one of its registered descendants.
|
||||||
//! \~russian Возвращает действительный ли это наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
//! \~russian Возвращает, принадлежит ли этот объект классу "T" или одному из его зарегистрированных потомков.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool isTypeOf() const {
|
bool isTypeOf() const {
|
||||||
if (!isPIObject()) return false;
|
if (!isPIObject()) return false;
|
||||||
@@ -530,30 +660,35 @@ public:
|
|||||||
return __meta_data()[classNameID()].scope_id.contains(T::__classNameIDS());
|
return __meta_data()[classNameID()].scope_id.contains(T::__classNameIDS());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns cast to T if this is valid subclass "T" (check by \a isTypeOf()) or "nullptr"
|
//! \~english Returns this object cast to "T" when \a isTypeOf<T>() succeeds, otherwise \c nullptr.
|
||||||
//! \~russian Возвращает преобразование к типу T если это действительный наследник типа "T" (проверяет через \a isTypeOf()), или
|
//! \~russian Возвращает этот объект, приведённый к типу "T", если \a isTypeOf<T>() успешно, иначе \c nullptr.
|
||||||
//! "nullptr"
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
T * cast() const {
|
T * cast() const {
|
||||||
if (!isTypeOf<T>()) return (T *)nullptr;
|
if (!isTypeOf<T>()) return (T *)nullptr;
|
||||||
return (T *)this;
|
return (T *)this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns if "o" is valid %PIObject (check signature)
|
//! \~english Returns whether "o" points to a live %PIObject instance.
|
||||||
//! \~russian Возвращает действительный ли "o" %PIObject (проверяет подпись)
|
//! \~russian Возвращает, указывает ли "o" на ещё существующий экземпляр %PIObject.
|
||||||
static bool isPIObject(const PIObject * o);
|
static bool isPIObject(const PIObject * o);
|
||||||
|
//! \~english Overload of \a isPIObject() for an untyped pointer.
|
||||||
|
//! \~russian Перегрузка \a isPIObject() для нетипизированного указателя.
|
||||||
static bool isPIObject(const void * o) { return isPIObject((PIObject *)o); }
|
static bool isPIObject(const void * o) { return isPIObject((PIObject *)o); }
|
||||||
|
|
||||||
//! \~english Returns if "o" is valid %PIObject subclass "T" (check signature and classname)
|
//! \~english Returns whether "o" belongs to class "T" or one of its registered descendants.
|
||||||
//! \~russian Возвращает действительный ли "o" наследник %PIObject типа "T" (проверяет подпись и имя класса)
|
//! \~russian Возвращает, принадлежит ли "o" классу "T" или одному из его зарегистрированных потомков.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
static bool isTypeOf(const PIObject * o) {
|
static bool isTypeOf(const PIObject * o) {
|
||||||
return o->isTypeOf<T>();
|
return o->isTypeOf<T>();
|
||||||
}
|
}
|
||||||
|
//! \~english Overload of \a isTypeOf() for an untyped pointer.
|
||||||
|
//! \~russian Перегрузка \a isTypeOf() для нетипизированного указателя.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
static bool isTypeOf(const void * o) {
|
static bool isTypeOf(const void * o) {
|
||||||
return isTypeOf<T>((PIObject *)o);
|
return isTypeOf<T>((PIObject *)o);
|
||||||
}
|
}
|
||||||
|
//! \~english Simplifies a C++ type spelling for registered-method metadata.
|
||||||
|
//! \~russian Упрощает запись типа C++ для метаданных зарегистрированных методов.
|
||||||
static PIString simplifyType(const char * a, bool readable = true);
|
static PIString simplifyType(const char * a, bool readable = true);
|
||||||
|
|
||||||
struct PIP_EXPORT __MetaFunc {
|
struct PIP_EXPORT __MetaFunc {
|
||||||
@@ -589,36 +724,32 @@ public:
|
|||||||
};
|
};
|
||||||
typedef PIPair<const void *, __MetaFunc> __EHPair;
|
typedef PIPair<const void *, __MetaFunc> __EHPair;
|
||||||
|
|
||||||
//! \~english Execute all posted events from CONNECTU_QUEUED connections
|
//! \~english Executes all queued deliveries posted to this performer object.
|
||||||
//! \~russian Выполнить все отложенные события от CONNECTU_QUEUED соединений
|
//! \~russian Выполняет все отложенные доставки, поставленные в очередь этому объекту-исполнителю.
|
||||||
void callQueuedEvents();
|
void callQueuedEvents();
|
||||||
|
|
||||||
//! \~english
|
//! \~\brief
|
||||||
//! \brief Check if any CONNECTU_QUEUED connections to this object and execute them
|
//! \~english Executes queued deliveries only when this object was used as a performer.
|
||||||
//! \details This function is more optimized than \a callQueuedEvents() for objects that doesn`t
|
//! \~russian Выполняет отложенные доставки только если этот объект использовался как исполнитель.
|
||||||
//! appears as \"performer\" target at CONNECTU_QUEUED
|
//! \~\details
|
||||||
//! \~russian
|
//! \~english This helper is cheaper than unconditional \a callQueuedEvents() for objects that are rarely used as performer targets.
|
||||||
//! \brief Если было хотя бы одно CONNECTU_QUEUED соединение с исполнителем this, то выполнить события
|
//! \~russian Этот помощник дешевле, чем безусловный \a callQueuedEvents(), для объектов, которые редко используются как исполнители.
|
||||||
//! \details Этот метод более оптимален, чем \a callQueuedEvents(), для объектов, которые не были в роли
|
|
||||||
//! \"performer\" в макросе CONNECTU_QUEUED
|
|
||||||
bool maybeCallQueuedEvents() {
|
bool maybeCallQueuedEvents() {
|
||||||
if (proc_event_queue) callQueuedEvents();
|
if (proc_event_queue) callQueuedEvents();
|
||||||
return proc_event_queue;
|
return proc_event_queue;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Mark object to delete
|
//! \~english Schedules the object for deferred deletion.
|
||||||
//! \~russian Пометить объект на удаление
|
//! \~russian Планирует отложенное удаление объекта.
|
||||||
void deleteLater();
|
void deleteLater();
|
||||||
|
|
||||||
EVENT1(deleted, PIObject *, o);
|
|
||||||
|
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void deleted(PIObject * o)
|
//! \fn void deleted(PIObject * o)
|
||||||
//! \brief
|
//! \brief
|
||||||
//! \~english Raise before object delete
|
//! \~english Raised immediately before object destruction.
|
||||||
//! \~russian Вызывается перед удалением объекта
|
//! \~russian Вызывается непосредственно перед уничтожением объекта.
|
||||||
//! \~\warning
|
//! \~\warning
|
||||||
//! \~english
|
//! \~english
|
||||||
//! This event raised from destructor, so use only "o" numeric value,
|
//! This event raised from destructor, so use only "o" numeric value,
|
||||||
@@ -626,19 +757,23 @@ public:
|
|||||||
//! \~russian
|
//! \~russian
|
||||||
//! Это событие вызывается из деструктора, поэтому используйте
|
//! Это событие вызывается из деструктора, поэтому используйте
|
||||||
//! только численное значение "o", не надо кастовать его в другие типы!
|
//! только численное значение "o", не надо кастовать его в другие типы!
|
||||||
|
EVENT1(deleted, PIObject *, o);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
static PIMutex & __meta_mutex();
|
static PIMutex & __meta_mutex();
|
||||||
static PIMap<uint, __MetaData> & __meta_data(); // [hash(classname)]=__MetaData
|
static PIMap<uint, __MetaData> & __meta_data();
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//! \~english Returns %PIObject* which has raised an event. This value is correct only in definition of some event handler
|
//! \~english Returns the source object that raised the current event.
|
||||||
//! \~russian Возвращает %PIObject* который вызвал это событие. Значение допустимо только из методов обработчиков событий
|
//! \~russian Возвращает объект-источник, который вызвал текущее событие.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This value is valid only while an event handler is running.
|
||||||
|
//! \~russian Это значение корректно только пока выполняется обработчик события.
|
||||||
PIObject * emitter() const { return emitter_; }
|
PIObject * emitter() const { return emitter_; }
|
||||||
|
|
||||||
//! \~english Virtual function executes after property with name "name" has been changed
|
//! \~english Virtual method called after property "name" has been changed by \a setProperty().
|
||||||
//! \~russian Виртуальная функция, вызывается после изменения любого свойства.
|
//! \~russian Виртуальный метод, вызываемый после изменения свойства "name" через \a setProperty().
|
||||||
virtual void propertyChanged(const char * name) {}
|
virtual void propertyChanged(const char * name) {}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -702,8 +837,15 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
#ifndef MICRO_PIP
|
#ifndef MICRO_PIP
|
||||||
|
|
||||||
|
//! \~english Dumps application-level %PIObject diagnostics.
|
||||||
|
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject.
|
||||||
PIP_EXPORT void dumpApplication(bool with_objects = true);
|
PIP_EXPORT void dumpApplication(bool with_objects = true);
|
||||||
|
|
||||||
|
//! \~english Dumps application-level %PIObject diagnostics to file "path".
|
||||||
|
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject в файл "path".
|
||||||
PIP_EXPORT bool dumpApplicationToFile(const PIString & path, bool with_objects = true);
|
PIP_EXPORT bool dumpApplicationToFile(const PIString & path, bool with_objects = true);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#endif // PIOBJECT_H
|
#endif // PIOBJECT_H
|
||||||
|
|||||||
@@ -1,9 +1,17 @@
|
|||||||
/*! \file piobject_macros.h
|
//! \~\ingroup Core
|
||||||
* \ingroup Core
|
//! \~\file piobject_macros.h
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english PIObject macros
|
//! \~english PIObject macros for event system and object introspection
|
||||||
* \~russian Макросы PIObject
|
//! \~russian Макросы PIObject для событийной системы и интроспекции объектов
|
||||||
*/
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! This file declares the macro layer used by %PIObject-based classes:
|
||||||
|
//! class registration, event declaration, event handler declaration,
|
||||||
|
//! connection helpers and event raising helpers.
|
||||||
|
//! \~russian
|
||||||
|
//! Этот файл объявляет макросный слой для классов на базе %PIObject:
|
||||||
|
//! регистрацию класса, объявление событий, объявление обработчиков,
|
||||||
|
//! макросы соединения и макросы вызова событий.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Macros for PIObject
|
Macros for PIObject
|
||||||
@@ -32,47 +40,47 @@
|
|||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER and correct piCoutObj output
|
//! \~english Put this macro inside a direct %PIObject subclass definition to enable registered events, event handlers and class metadata.
|
||||||
//! \~russian Необходимо использовать этот макрос после объявления класса для использования событийной системы и корректного вывода
|
//! \~russian Поместите этот макрос внутрь объявления прямого наследника %PIObject, чтобы включить регистрацию событий, обработчиков и
|
||||||
//! piCoutObj
|
//! метаданных класса.
|
||||||
# define PIOBJECT(name)
|
# define PIOBJECT(name)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english You should use this macro after class declaration to use EVENT and EVENT_HANDLER of parent class, and \a scopeList()
|
//! \~english Put this macro inside a %PIObject subclass definition to inherit registered methods and class scope from "parent".
|
||||||
//! \~russian
|
//! \~russian Поместите этот макрос внутрь объявления наследника %PIObject, чтобы унаследовать зарегистрированные методы и цепочку
|
||||||
|
//! классов от "parent".
|
||||||
# define PIOBJECT_SUBCLASS(name, parent)
|
# define PIOBJECT_SUBCLASS(name, parent)
|
||||||
|
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name()
|
//! \~english Declare a registered event handler method with signature `ret name()`.
|
||||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name()
|
//! \~russian Объявляет зарегистрированный метод-обработчик событий с сигнатурой `ret name()`.
|
||||||
# define EVENT_HANDLER0(ret, name) ret name()
|
# define EVENT_HANDLER0(ret, name) ret name()
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0)
|
//! \~english Declare a registered event handler method with one argument.
|
||||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0)
|
//! \~russian Объявляет зарегистрированный метод-обработчик событий с одним аргументом.
|
||||||
# define EVENT_HANDLER1(ret, name, type0, var0) ret name(type0 var0)
|
# define EVENT_HANDLER1(ret, name, type0, var0) ret name(type0 var0)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1)
|
//! \~english Declare a registered event handler method with two arguments.
|
||||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1)
|
//! \~russian Объявляет зарегистрированный метод-обработчик событий с двумя аргументами.
|
||||||
# define EVENT_HANDLER2(ret, name, type0, var0, type1, var1) ret name(type0 var0, type1 var1)
|
# define EVENT_HANDLER2(ret, name, type0, var0, type1, var1) ret name(type0 var0, type1 var1)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
//! \~english Declare a registered event handler method with three arguments.
|
||||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2)
|
//! \~russian Объявляет зарегистрированный метод-обработчик событий с тремя аргументами.
|
||||||
# define EVENT_HANDLER3(ret, name, type0, var0, type1, var1, type2, var2) ret name(type0 var0, type1 var1, type2 var2)
|
# define EVENT_HANDLER3(ret, name, type0, var0, type1, var1, type2, var2) ret name(type0 var0, type1 var1, type2 var2)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event handler with name \"name\" and return type \"ret\", ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
//! \~english Declare a registered event handler method with four arguments.
|
||||||
//! \~russian Объявляет обработчик событий с именем \"name\" и возвращаемым типом \"ret\", ret name(type0 var0, type1 var1, type2 var2,
|
//! \~russian Объявляет зарегистрированный метод-обработчик событий с четырьмя аргументами.
|
||||||
//! type3 var3)
|
|
||||||
# define EVENT_HANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
# define EVENT_HANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||||
ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||||
|
|
||||||
@@ -85,36 +93,32 @@
|
|||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name()
|
//! \~english Declare a virtual registered event handler method with signature `virtual ret name()`.
|
||||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name()
|
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с сигнатурой `virtual ret name()`.
|
||||||
# define EVENT_VHANDLER0(ret, name) virtual ret name()
|
# define EVENT_VHANDLER0(ret, name) virtual ret name()
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0)
|
//! \~english Declare a virtual registered event handler method with one argument.
|
||||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0)
|
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с одним аргументом.
|
||||||
# define EVENT_VHANDLER1(ret, name, type0, var0) virtual ret name(type0 var0)
|
# define EVENT_VHANDLER1(ret, name, type0, var0) virtual ret name(type0 var0)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1)
|
//! \~english Declare a virtual registered event handler method with two arguments.
|
||||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с двумя аргументами.
|
||||||
//! var1)
|
|
||||||
# define EVENT_VHANDLER2(ret, name, type0, var0, type1, var1) virtual ret name(type0 var0, type1 var1)
|
# define EVENT_VHANDLER2(ret, name, type0, var0, type1, var1) virtual ret name(type0 var0, type1 var1)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2)
|
//! \~english Declare a virtual registered event handler method with three arguments.
|
||||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с тремя аргументами.
|
||||||
//! var1, type2 var2)
|
|
||||||
# define EVENT_VHANDLER3(ret, name, type0, var0, type1, var1, type2, var2) virtual ret name(type0 var0, type1 var1, type2 var2)
|
# define EVENT_VHANDLER3(ret, name, type0, var0, type1, var1, type2, var2) virtual ret name(type0 var0, type1 var1, type2 var2)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare virtual event handler with name \"name\" and return type \"ret\", virtual ret name(type0 var0, type1 var1, type2 var2,
|
//! \~english Declare a virtual registered event handler method with four arguments.
|
||||||
//! type3 var3)
|
//! \~russian Объявляет виртуальный зарегистрированный метод-обработчик с четырьмя аргументами.
|
||||||
//! \~russian Объявляет виртуальный обработчик событий с именем \"name\" и возвращаемым типом \"ret\", virtual ret name(type0 var0, type1
|
|
||||||
//! var1, type2 var2, type3 var3)
|
|
||||||
# define EVENT_VHANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
# define EVENT_VHANDLER4(ret, name, type0, var0, type1, var1, type2, var2, type3, var3) \
|
||||||
virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
virtual ret name(type0 var0, type1 var1, type2 var2, type3 var3)
|
||||||
|
|
||||||
@@ -127,32 +131,32 @@
|
|||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event with name \"name\", void name();
|
//! \~english Declare an event method with no arguments.
|
||||||
//! \~russian Объявляет событие с именем \"name\", void name();
|
//! \~russian Объявляет метод-событие без аргументов.
|
||||||
# define EVENT0(name) void name();
|
# define EVENT0(name) void name();
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event with name \"name\", void name(type0 var0);
|
//! \~english Declare an event method with one argument.
|
||||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0);
|
//! \~russian Объявляет метод-событие с одним аргументом.
|
||||||
# define EVENT1(name, type0, var0) void name(type0 var0);
|
# define EVENT1(name, type0, var0) void name(type0 var0);
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1);
|
//! \~english Declare an event method with two arguments.
|
||||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1);
|
//! \~russian Объявляет метод-событие с двумя аргументами.
|
||||||
# define EVENT2(name, type0, var0, type1, var1) void name(type0 var0, type1 var1);
|
# define EVENT2(name, type0, var0, type1, var1) void name(type0 var0, type1 var1);
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2);
|
//! \~english Declare an event method with three arguments.
|
||||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2);
|
//! \~russian Объявляет метод-событие с тремя аргументами.
|
||||||
# define EVENT3(name, type0, var0, type1, var1, type2, var2) void name(type0 var0, type1 var1, type2 var2);
|
# define EVENT3(name, type0, var0, type1, var1, type2, var2) void name(type0 var0, type1 var1, type2 var2);
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Declare event with name \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
//! \~english Declare an event method with four arguments.
|
||||||
//! \~russian Объявляет событие с именем \"name\", void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
//! \~russian Объявляет метод-событие с четырьмя аргументами.
|
||||||
# define EVENT4(name, type0, var0, type1, var1, type2, var2, type3, var3) void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
# define EVENT4(name, type0, var0, type1, var1, type2, var2, type3, var3) void name(type0 var0, type1 var1, type2 var2, type3 var3);
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -162,10 +166,26 @@
|
|||||||
# define EVENT EVENT0
|
# define EVENT EVENT0
|
||||||
|
|
||||||
|
|
||||||
|
//! \relatesalso PIObject
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Compatibility helper that raises event "event" on source object "src".
|
||||||
|
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" у объекта-источника "src".
|
||||||
# define RAISE_EVENT0(src, event)
|
# define RAISE_EVENT0(src, event)
|
||||||
|
//! \relatesalso PIObject
|
||||||
|
//! \~english Compatibility helper that raises event "event" with one argument.
|
||||||
|
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с одним аргументом.
|
||||||
# define RAISE_EVENT1(src, event, v0)
|
# define RAISE_EVENT1(src, event, v0)
|
||||||
|
//! \relatesalso PIObject
|
||||||
|
//! \~english Compatibility helper that raises event "event" with two arguments.
|
||||||
|
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с двумя аргументами.
|
||||||
# define RAISE_EVENT2(src, event, v0, v1)
|
# define RAISE_EVENT2(src, event, v0, v1)
|
||||||
|
//! \relatesalso PIObject
|
||||||
|
//! \~english Compatibility helper that raises event "event" with three arguments.
|
||||||
|
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с тремя аргументами.
|
||||||
# define RAISE_EVENT3(src, event, v0, v1, v2)
|
# define RAISE_EVENT3(src, event, v0, v1, v2)
|
||||||
|
//! \relatesalso PIObject
|
||||||
|
//! \~english Compatibility helper that raises event "event" with four arguments.
|
||||||
|
//! \~russian Совместимый вспомогательный макрос, вызывающий событие "event" с четырьмя аргументами.
|
||||||
# define RAISE_EVENT4(src, event, v0, v1, v2, v3)
|
# define RAISE_EVENT4(src, event, v0, v1, v2, v3)
|
||||||
# define RAISE_EVENT RAISE_EVENT0
|
# define RAISE_EVENT RAISE_EVENT0
|
||||||
|
|
||||||
@@ -176,11 +196,11 @@
|
|||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! \"handler\" can handle subset arguments of \"event\".
|
//! \"handler\" can accept a prefix of \"event\" arguments.
|
||||||
//! Returns \a PIObject::Connection
|
//! This macro resolves registered methods by name at run time and returns \a PIObject::Connection.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! \"handler\" может принимать не все аргументы от \"event\".
|
//! \"handler\" может принимать только начальную часть аргументов \"event\".
|
||||||
//! Возвращает \a PIObject::Connection
|
//! Макрос ищет зарегистрированные методы по имени во время выполнения и возвращает \a PIObject::Connection.
|
||||||
# define CONNECTU(src, event, dest, handler)
|
# define CONNECTU(src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -189,17 +209,19 @@
|
|||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" объекта \"dest\".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! \"handler\" can handle subset arguments of \"event\".
|
//! \"handler\" can accept a prefix of \"event\" arguments.
|
||||||
//! Event handler will be executed by \"performer\" when \a PIObject::callQueuedEvents() called.
|
//! Delivery is queued on the performer object and runs only when that object calls
|
||||||
|
//! \a PIObject::callQueuedEvents() or \a PIObject::maybeCallQueuedEvents().
|
||||||
//! All argument types should be registered by \a REGISTER_VARIANT() macro, but many
|
//! All argument types should be registered by \a REGISTER_VARIANT() macro, but many
|
||||||
//! common and PIP types already done.
|
//! common and PIP types already done.
|
||||||
//! Returns \a PIObject::Connection
|
//! Returns \a PIObject::Connection.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! \"handler\" может принимать не все аргументы от \"event\".
|
//! \"handler\" может принимать только начальную часть аргументов \"event\".
|
||||||
//! Обработчик будет вызван объектом \"performer\" при вызове \a PIObject::callQueuedEvents().
|
//! Доставка ставится в очередь объекта \"performer\" и выполняется только когда этот объект
|
||||||
|
//! вызывает \a PIObject::callQueuedEvents() или \a PIObject::maybeCallQueuedEvents().
|
||||||
//! Все типы аргументов должны быть зарегистрированы с помощью макроса \a REGISTER_VARIANT(),
|
//! Все типы аргументов должны быть зарегистрированы с помощью макроса \a REGISTER_VARIANT(),
|
||||||
//! однако многие стандартные и PIP типы уже там.
|
//! однако многие стандартные и PIP типы уже там.
|
||||||
//! Возвращает \a PIObject::Connection
|
//! Возвращает \a PIObject::Connection.
|
||||||
# define CONNECTU_QUEUED(src, event, dest, handler, performer)
|
# define CONNECTU_QUEUED(src, event, dest, handler, performer)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -208,13 +230,13 @@
|
|||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к лямбда-функции \"functor\".
|
//! \~russian Соединяет событие \"event\" объекта \"src\" к лямбда-функции \"functor\".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english
|
//! \~english
|
||||||
//! \"event\" and \"functor\" must has equal argument lists.
|
//! \"event\" and \"functor\" must have the same argument list.
|
||||||
//! You should parentness \"functor\" with () if this is complex lambda.
|
//! Wrap \"functor\" in () when the lambda expression is complex.
|
||||||
//! Returns \a PIObject::Connection
|
//! Returns \a PIObject::Connection.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! \"event\" и \"functor\" должны иметь одинаковые аргументы.
|
//! \"event\" и \"functor\" должны иметь одинаковый список аргументов.
|
||||||
//! В случае сложной лямбда-функции оберните её ().
|
//! В случае сложной лямбда-функции оберните её в ().
|
||||||
//! Возвращает \a PIObject::Connection
|
//! Возвращает \a PIObject::Connection.
|
||||||
# define CONNECTL(src, event, functor)
|
# define CONNECTL(src, event, functor)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -222,12 +244,11 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
//! \~english Legacy compatibility helper that connects an event to a registered handler with compile-time signature spelling.
|
||||||
//! check of event and handler exists
|
//! \~russian Устаревший совместимый макрос, который соединяет событие с зарегистрированным обработчиком через явное указание сигнатуры.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" с проверкой наличия события и обработчика.
|
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! Returns PIObject::Connection
|
//! \~english Prefer \a CONNECTU() for new code.
|
||||||
|
//! \~russian Для нового кода предпочитайте \a CONNECTU().
|
||||||
# define CONNECT0(ret, src, event, dest, handler)
|
# define CONNECT0(ret, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -235,12 +256,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
//! \~english Legacy compatibility helper for a one-argument registered event or handler.
|
||||||
//! check of event and handler exists
|
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с одним аргументом.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" с проверкой наличия события и обработчика.
|
|
||||||
//! \~\details
|
|
||||||
//! Returns PIObject::Connection
|
|
||||||
# define CONNECT1(ret, type0, src, event, dest, handler)
|
# define CONNECT1(ret, type0, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -248,12 +265,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
//! \~english Legacy compatibility helper for a two-argument registered event or handler.
|
||||||
//! check of event and handler exists
|
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с двумя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" с проверкой наличия события и обработчика.
|
|
||||||
//! \~\details
|
|
||||||
//! Returns PIObject::Connection
|
|
||||||
# define CONNECT2(ret, type0, type1, src, event, dest, handler)
|
# define CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -261,12 +274,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
//! \~english Legacy compatibility helper for a three-argument registered event or handler.
|
||||||
//! check of event and handler exists
|
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с тремя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" с проверкой наличия события и обработчика.
|
|
||||||
//! \~\details
|
|
||||||
//! Returns PIObject::Connection
|
|
||||||
# define CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
# define CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -274,12 +283,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" with
|
//! \~english Legacy compatibility helper for a four-argument registered event or handler.
|
||||||
//! check of event and handler exists.
|
//! \~russian Устаревший совместимый макрос для зарегистрированного события или обработчика с четырьмя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" с проверкой наличия события и обработчика.
|
|
||||||
//! \~\details
|
|
||||||
//! Returns PIObject::Connection
|
|
||||||
# define CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
# define CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -297,10 +302,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
//! \~english Legacy compatibility helper that skips source method verification.
|
||||||
//! check of event exists
|
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" без проверки наличия события и обработчика.
|
|
||||||
# define WEAK_CONNECT0(ret, src, event, dest, handler)
|
# define WEAK_CONNECT0(ret, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -308,10 +311,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
//! \~english Legacy compatibility helper that skips source method verification for one argument.
|
||||||
//! check of event exists
|
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с одним аргументом.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" без проверки наличия события и обработчика.
|
|
||||||
# define WEAK_CONNECT1(ret, type0, src, event, dest, handler)
|
# define WEAK_CONNECT1(ret, type0, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -319,10 +320,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
//! \~english Legacy compatibility helper that skips source method verification for two arguments.
|
||||||
//! check of event exists
|
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с двумя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" без проверки наличия события и обработчика.
|
|
||||||
# define WEAK_CONNECT2(ret, type0, type1, src, event, dest, handler)
|
# define WEAK_CONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -330,10 +329,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
//! \~english Legacy compatibility helper that skips source method verification for three arguments.
|
||||||
//! check of event exists
|
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с тремя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" без проверки наличия события и обработчика.
|
|
||||||
# define WEAK_CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
# define WEAK_CONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -341,10 +338,8 @@
|
|||||||
//! \~english Use \a CONNECTU() instead
|
//! \~english Use \a CONNECTU() instead
|
||||||
//! \~russian Используйте \a CONNECTU()
|
//! \~russian Используйте \a CONNECTU()
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Connect event \"event\" from object \"src\" to event handler \"handler\" with return type \"ret\" from object \"dest\" without
|
//! \~english Legacy compatibility helper that skips source method verification for four arguments.
|
||||||
//! check of event exists
|
//! \~russian Устаревший совместимый макрос, который пропускает проверку исходного метода для случая с четырьмя аргументами.
|
||||||
//! \~russian Соединяет событие \"event\" объекта \"src\" к обработчику или событию \"handler\" с возвращаемым типом \"ret\" объекта
|
|
||||||
//! \"dest\" без проверки наличия события и обработчика.
|
|
||||||
# define WEAK_CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
# define WEAK_CONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -359,37 +354,32 @@
|
|||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
//! \~english Disconnect a registered event from a registered event handler.
|
||||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
//! \~russian Разрывает соединение зарегистрированного события с зарегистрированным обработчиком.
|
||||||
//! \"dest\"
|
|
||||||
# define DISCONNECT0(ret, src, event, dest, handler)
|
# define DISCONNECT0(ret, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
//! \~english Disconnect a one-argument registered event from a registered event handler.
|
||||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
//! \~russian Разрывает соединение зарегистрированного события с одним аргументом и зарегистрированного обработчика.
|
||||||
//! \"dest\"
|
|
||||||
# define DISCONNECT1(ret, type0, src, event, dest, handler)
|
# define DISCONNECT1(ret, type0, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
//! \~english Disconnect a two-argument registered event from a registered event handler.
|
||||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
//! \~russian Разрывает соединение зарегистрированного события с двумя аргументами и зарегистрированного обработчика.
|
||||||
//! \"dest\"
|
|
||||||
# define DISCONNECT2(ret, type0, type1, src, event, dest, handler)
|
# define DISCONNECT2(ret, type0, type1, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
//! \~english Disconnect a three-argument registered event from a registered event handler.
|
||||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
//! \~russian Разрывает соединение зарегистрированного события с тремя аргументами и зарегистрированного обработчика.
|
||||||
//! \"dest\"
|
|
||||||
# define DISCONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
# define DISCONNECT3(ret, type0, type1, type2, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english piDisconnect event \"event\" from object \"src\" from event handler \"handler\" with return type \"ret\" from object \"dest\"
|
//! \~english Disconnect a four-argument registered event from a registered event handler.
|
||||||
//! \~russian piDisconnect событие \"event\" объекта \"src\" от обработчика или события \"handler\" с возвращаемым типом \"ret\" объекта
|
//! \~russian Разрывает соединение зарегистрированного события с четырьмя аргументами и зарегистрированного обработчика.
|
||||||
//! \"dest\"
|
|
||||||
# define DISCONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
# define DISCONNECT4(ret, type0, type1, type2, type3, src, event, dest, handler)
|
||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
@@ -401,8 +391,8 @@
|
|||||||
|
|
||||||
//! \relatesalso PIObject
|
//! \relatesalso PIObject
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Returns pointer to events handler \"handler\"
|
//! \~english Low-level helper that expands to the registered handler entry point.
|
||||||
//! \~russian Возвращает указатель на обработчик события \"handler\"
|
//! \~russian Низкоуровневый вспомогательный макрос, который разворачивается в точку входа зарегистрированного обработчика.
|
||||||
# define HANDLER(handler)
|
# define HANDLER(handler)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piauth.h
|
//! \~\file piauth.h
|
||||||
* \ingroup Crypt
|
//! \~\ingroup Crypt
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Authentication API
|
//! \~english Authentication API
|
||||||
* \~russian API аутентификации
|
//! \~russian API аутентификации
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PIP Authentication API
|
PIP Authentication API
|
||||||
@@ -31,72 +30,110 @@
|
|||||||
#include "pip_crypt_export.h"
|
#include "pip_crypt_export.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Crypt
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Peer authentication state machine with signed key exchange.
|
||||||
|
//! \~russian Машина состояний аутентификации узлов с подписанным обменом ключами.
|
||||||
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
|
class PIP_CRYPT_EXPORT PIAuth: public PIObject {
|
||||||
PIOBJECT(PIAuth)
|
PIOBJECT(PIAuth)
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Handshake state.
|
||||||
|
//! \~russian Состояние рукопожатия.
|
||||||
enum State {
|
enum State {
|
||||||
NotConnected,
|
NotConnected /** \~english No active authentication session. \~russian Активной сессии аутентификации нет. */,
|
||||||
AuthProbe,
|
AuthProbe /** \~english Initial probe stage with signed peer introduction. \~russian Начальный этап с подписанным представлением
|
||||||
PassRequest,
|
узла. */
|
||||||
AuthReply,
|
,
|
||||||
KeyExchange,
|
PassRequest /** \~english Password verification stage for unknown peers. \~russian Этап проверки пароля для неизвестных узлов. */,
|
||||||
Connected
|
AuthReply /** \~english Reply with client authentication data. \~russian Ответ с данными аутентификации клиента. */,
|
||||||
|
KeyExchange /** \~english Session key exchange stage. \~russian Этап обмена сеансовым ключом. */,
|
||||||
|
Connected /** \~english Authentication finished and session key is established. \~russian Аутентификация завершена и сеансовый ключ
|
||||||
|
установлен. */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! Create PIAuth with your digital sign
|
|
||||||
|
//! \~english Creates an authentication endpoint from a signing secret key.
|
||||||
|
//! \~russian Создает конечную точку аутентификации из секретного ключа подписи.
|
||||||
PIAuth(const PIByteArray & sign);
|
PIAuth(const PIByteArray & sign);
|
||||||
|
|
||||||
//! Set server info data for client authorize event
|
|
||||||
|
//! \~english Sets application-defined info exchanged during authorization.
|
||||||
|
//! \~russian Задает прикладные данные, передаваемые во время авторизации.
|
||||||
void setInfoData(const PIByteArray & info) { custom_info = info; }
|
void setInfoData(const PIByteArray & info) { custom_info = info; }
|
||||||
|
|
||||||
//! Set server password for check
|
//! \~english Sets the server password used for password-based peer validation.
|
||||||
|
//! \~russian Устанавливает пароль сервера, используемый для проверки узла по паролю.
|
||||||
void setServerPassword(const PIString & ps);
|
void setServerPassword(const PIString & ps);
|
||||||
|
|
||||||
//! Set list of trusted clients/servers public digital sign keys
|
//! \~english Replaces the list of trusted peer signing public keys.
|
||||||
|
//! \~russian Заменяет список доверенных открытых ключей подписи удаленных узлов.
|
||||||
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
|
void setAuthorizedPublicKeys(const PIVector<PIByteArray> & pkeys) { auth_pkeys = pkeys; }
|
||||||
|
|
||||||
//! Get list of trusted clients/servers public digital sign keys
|
//! \~english Returns the list of trusted peer signing public keys.
|
||||||
|
//! \~russian Возвращает список доверенных открытых ключей подписи удаленных узлов.
|
||||||
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
|
PIVector<PIByteArray> getAuthorizedPublicKeys() { return auth_pkeys; }
|
||||||
|
|
||||||
//! Get your digital sign public key
|
//! \~english Returns the public signing key derived from the local secret key.
|
||||||
|
//! \~russian Возвращает открытый ключ подписи, полученный из локального секретного ключа.
|
||||||
PIByteArray getSignPublicKey() { return sign_pk; }
|
PIByteArray getSignPublicKey() { return sign_pk; }
|
||||||
|
|
||||||
|
|
||||||
//! Stop authorization
|
//! \~english Stops the current authorization session and clears transient keys.
|
||||||
|
//! \~russian Останавливает текущую сессию авторизации и очищает временные ключи.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
//! Start authorization as client
|
//! \~english Starts the handshake in client mode.
|
||||||
|
//! \~russian Запускает рукопожатие в режиме клиента.
|
||||||
void startClient();
|
void startClient();
|
||||||
|
|
||||||
//! Start authorization as server, return first server message for client
|
//! \~english Starts the handshake in server mode and returns the first packet for the client.
|
||||||
|
//! \~russian Запускает рукопожатие в режиме сервера и возвращает первый пакет для клиента.
|
||||||
PIByteArray startServer();
|
PIByteArray startServer();
|
||||||
|
|
||||||
//! Process reseived message both for client and server, return current state and new message writed in "ba"
|
//! \~english Processes an incoming handshake packet, updates the state and writes the reply back to \a ba.
|
||||||
|
//! \~russian Обрабатывает входящий пакет рукопожатия, обновляет состояние и записывает ответ обратно в \a ba.
|
||||||
State receive(PIByteArray & ba);
|
State receive(PIByteArray & ba);
|
||||||
|
|
||||||
//! Get session secret key, return key only when Connected state
|
//! \~english Returns the session secret key after the state becomes \a Connected.
|
||||||
|
//! \~russian Возвращает сеансовый секретный ключ после перехода в состояние \a Connected.
|
||||||
PIByteArray getSecretKey();
|
PIByteArray getSecretKey();
|
||||||
|
|
||||||
//! Generate digital sign from seed
|
//! \~english Generates a signing secret key from \a seed.
|
||||||
|
//! \~russian Генерирует секретный ключ подписи из \a seed.
|
||||||
static PIByteArray generateSign(const PIByteArray & seed);
|
static PIByteArray generateSign(const PIByteArray & seed);
|
||||||
|
|
||||||
|
|
||||||
//! Disconneted event
|
//! \events
|
||||||
|
//! \{
|
||||||
|
|
||||||
|
//! \fn void disconnected(PIString reason)
|
||||||
|
//! \~english Raised when the handshake is aborted or an established session is dropped.
|
||||||
|
//! \~russian Вызывается при прерывании рукопожатия или разрыве установленной сессии.
|
||||||
EVENT1(disconnected, PIString, reason);
|
EVENT1(disconnected, PIString, reason);
|
||||||
|
|
||||||
//! Conneted event
|
//! \fn void connected(PIString info)
|
||||||
|
//! \~english Raised after the peer reaches state \a Connected.
|
||||||
|
//! \~russian Вызывается после перехода узла в состояние \a Connected.
|
||||||
EVENT1(connected, PIString, info);
|
EVENT1(connected, PIString, info);
|
||||||
|
|
||||||
//! Client event for authorize new server
|
//! \fn void authorize(PIByteArray info, bool * ok)
|
||||||
|
//! \~english Client-side callback used to approve an unknown server and optionally trust its signing key.
|
||||||
|
//! \~russian Клиентский вызов для подтверждения неизвестного сервера и, при необходимости, доверия его ключу подписи.
|
||||||
EVENT2(authorize, PIByteArray, info, bool *, ok);
|
EVENT2(authorize, PIByteArray, info, bool *, ok);
|
||||||
|
|
||||||
//! Client event for input server password
|
//! \fn void passwordRequest(PIString * pass)
|
||||||
|
//! \~english Client-side callback requesting the server password.
|
||||||
|
//! \~russian Клиентский вызов для запроса пароля сервера.
|
||||||
EVENT1(passwordRequest, PIString *, pass);
|
EVENT1(passwordRequest, PIString *, pass);
|
||||||
|
|
||||||
//! Server event on check client password
|
//! \fn void passwordCheck(bool result)
|
||||||
|
//! \~english Server-side callback reporting the result of client password validation.
|
||||||
|
//! \~russian Серверный вызов, сообщающий результат проверки пароля клиента.
|
||||||
EVENT1(passwordCheck, bool, result);
|
EVENT1(passwordCheck, bool, result);
|
||||||
|
|
||||||
|
//! \}
|
||||||
|
|
||||||
private:
|
private:
|
||||||
enum Role {
|
enum Role {
|
||||||
Client,
|
Client,
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file picrypt.h
|
//! \~\ingroup Crypt
|
||||||
* \ingroup Crypt
|
//! \~\file picrypt.h
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Cryptographic using libsodium
|
//! \~english Cryptographic using libsodium
|
||||||
* \~russian Шифрование с помощью libsodium
|
//! \~russian Шифрование с помощью libsodium
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Cryptographic class using lib Sodium
|
Cryptographic class using lib Sodium
|
||||||
@@ -29,154 +28,136 @@
|
|||||||
#include "pip_crypt_export.h"
|
#include "pip_crypt_export.h"
|
||||||
#include "pistring.h"
|
#include "pistring.h"
|
||||||
|
|
||||||
//! \ingroup Crypt
|
//! \~\ingroup Crypt
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Class for encrypting and decrypting data.
|
//! \~english Class for encrypting and decrypting data.
|
||||||
//! \~russian Класс для шифрования и дешифрования данных.
|
//! \~russian Класс для шифрования и дешифрования данных.
|
||||||
|
//! \details
|
||||||
|
//! \~english Class providing cryptographic operations using the libsodium library, including encryption, decryption, hashing, and digital
|
||||||
|
//! signatures. It supports both instance-based and static method-based operations.
|
||||||
|
//! \~russian Класс, предоставляющий криптографические операции с использованием библиотеки libsodium, включая шифрование, дешифрование,
|
||||||
|
//! хэширование и цифровые подписи. Поддерживаются операции как на основе экземпляра класса, так и на основе статических методов.
|
||||||
|
//! \note
|
||||||
|
//! \~english Requires libsodium library initialization. All methods are thread-safe when using different keys.
|
||||||
|
//! \~russian Требуется инициализация библиотеки libsodium. Все методы потокобезопасны при использовании различных ключей.
|
||||||
class PIP_CRYPT_EXPORT PICrypt {
|
class PIP_CRYPT_EXPORT PICrypt {
|
||||||
public:
|
public:
|
||||||
//! \~\brief
|
//! \~english Constructor that generates a random key.
|
||||||
//! \~english Constructor that generates a random key
|
//! \~russian Конструктор, генерирующий случайный ключ.
|
||||||
//! \~russian Конструктор, генерирующий случайный ключ
|
|
||||||
PICrypt();
|
PICrypt();
|
||||||
|
|
||||||
|
//! \~english Destructor.
|
||||||
|
//! \~russian Деструктор.
|
||||||
~PICrypt();
|
~PICrypt();
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Set key to "key", key size must be a \a sizeKey().
|
||||||
//! \~english Set key to "key", key size must be a \a sizeKey()
|
//! \~russian Установить ключ "key", размер ключа должен быть равен \a sizeKey().
|
||||||
//! \~russian Установить ключ "key", размер ключа должен быть равен \a sizeKey()
|
|
||||||
bool setKey(const PIByteArray & key);
|
bool setKey(const PIByteArray & key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate and set key from keyphrase "secret".
|
||||||
//! \~english Generate and set key from keyphrase "secret"
|
//! \~russian Генерировать и установить ключ из ключевой фразы "secret".
|
||||||
//! \~russian Генерировать и установить ключ из ключевой фразы "secret"
|
|
||||||
bool setKey(const PIString & secret);
|
bool setKey(const PIString & secret);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Returns current key.
|
||||||
//! \~english Returns current key
|
//! \~russian Возвращает текущий ключ.
|
||||||
//! \~russian Возвращает текущий ключ
|
|
||||||
PIByteArray key() { return key_; }
|
PIByteArray key() { return key_; }
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Encrypt given data "data", result size will be increased by \a sizeCrypt().
|
||||||
//! \~english Encrypt given data "data", result size will be increased by \a sizeCrypt()
|
//! \~russian Зашифровать данные "data", размер результата увеличится на \a sizeCrypt().
|
||||||
//! \~russian Зашифровать данные "data", размер результата увеличится на \a sizeCrypt()
|
|
||||||
PIByteArray crypt(const PIByteArray & data);
|
PIByteArray crypt(const PIByteArray & data);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Decrypt given data "crypt_data".
|
||||||
//! \~english Decrypt given data "crypt_data"
|
//! \~russian Расшифровать данные "crypt_data".
|
||||||
//! \~russian Расшифровать данные "crypt_data"
|
|
||||||
PIByteArray decrypt(const PIByteArray & crypt_data, bool * ok = 0);
|
PIByteArray decrypt(const PIByteArray & crypt_data, bool * ok = 0);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Encrypt given data "data" with key "key", result size will be increased by \a sizeCrypt().
|
||||||
//! \~english Encrypt given data "data" with key "key", result size will be increased by \a sizeCrypt()
|
//! \~russian Зашифровать данные "data" ключом "key", размер результата увеличится на \a sizeCrypt().
|
||||||
//! \~russian Зашифровать данные "data" ключом "key", размер результата увеличится на \a sizeCrypt()
|
|
||||||
static PIByteArray crypt(const PIByteArray & data, PIByteArray key);
|
static PIByteArray crypt(const PIByteArray & data, PIByteArray key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Decrypt given data "crypt_data" with key "key".
|
||||||
//! \~english Decrypt given data "crypt_data" with key "key"
|
//! \~russian Расшифровать данные "crypt_data" ключом "key".
|
||||||
//! \~russian Расшифровать данные "crypt_data" ключом "key"
|
|
||||||
static PIByteArray decrypt(const PIByteArray & crypt_data, PIByteArray key, bool * ok = 0);
|
static PIByteArray decrypt(const PIByteArray & crypt_data, PIByteArray key, bool * ok = 0);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate hash from keyphrase "secret", may be used as a key for encryption.
|
||||||
//! \~english Generate hash from keyphrase "secret", may be used as a key for encryption
|
//! \~russian Генерировать хэш из ключевой фразы "secret", может использоваться в качестве ключа для шифрования.
|
||||||
//! \~russian Генерировать хэш из ключевой фразы "secret", может использоваться в качестве ключа для шифрования
|
|
||||||
static PIByteArray hash(PIString secret);
|
static PIByteArray hash(PIString secret);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate hash from bytearray.
|
||||||
//! \~english Generate hash from bytearray
|
//! \~russian Генерировать хэш из массива байт.
|
||||||
//! \~russian Генерировать хэш из массива байт
|
|
||||||
static PIByteArray hash(const PIByteArray & data);
|
static PIByteArray hash(const PIByteArray & data);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate hash from bytearray using provided key.
|
||||||
//! \~english Generate hash from bytearray
|
//! \~russian Генерировать хэш из массива байт с использованием предоставленного ключа.
|
||||||
//! \~russian Генерировать хэш из массива байт
|
|
||||||
static PIByteArray hash(const PIByteArray & data, const unsigned char * key, size_t keylen);
|
static PIByteArray hash(const PIByteArray & data, const unsigned char * key, size_t keylen);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Returns hash size.
|
||||||
//! \~english Returns hash size
|
//! \~russian Возвращает размер хэша.
|
||||||
//! \~russian Возвращает размер хэша
|
|
||||||
static size_t sizeHash();
|
static size_t sizeHash();
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate short hash from string "s", may be used for hash table.
|
||||||
//! \~english Generate short hash from string "s", may be used for hash table
|
//! \~russian Генерировать короткий хэш из строки "s", может использоваться для хэш-таблиц.
|
||||||
//! \~russian Генерировать короткий хэш из строки "s", может использоваться для хэш-таблиц
|
|
||||||
static ullong shorthash(const PIString & s, PIByteArray key = PIByteArray());
|
static ullong shorthash(const PIString & s, PIByteArray key = PIByteArray());
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate random key.
|
||||||
//! \~english Generate random key
|
//! \~russian Генерировать случайный ключ.
|
||||||
//! \~russian Генерировать случайный ключ
|
|
||||||
static PIByteArray generateKey();
|
static PIByteArray generateKey();
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate random buffer.
|
||||||
//! \~english Generate random buffer
|
//! \~russian Генерировать случайный буфер.
|
||||||
//! \~russian Генерировать случайный буфер
|
|
||||||
static PIByteArray generateRandomBuff(int size);
|
static PIByteArray generateRandomBuff(int size);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Returns key size.
|
||||||
//! \~english Returns key size
|
//! \~russian Возвращает размер ключа.
|
||||||
//! \~russian Возвращает размер ключа
|
|
||||||
static size_t sizeKey();
|
static size_t sizeKey();
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Returns size which be added to data size in encryption process.
|
||||||
//! \~english Returns size which be added to data size in encryption process
|
//! \~russian Возвращает размер, который будет добавлен к размеру данных в процессе шифрования.
|
||||||
//! \~russian Возвращает размер, который будет добавлен к размеру данных в процессе шифрования
|
|
||||||
static size_t sizeCrypt();
|
static size_t sizeCrypt();
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Function randomly generates a secret key and a corresponding public key for digital signature.
|
||||||
//! \~english Function randomly generates a secret key and a corresponding public key for digital signature
|
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для цифровой подписи.
|
||||||
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для цифровой подписи
|
|
||||||
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key);
|
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Function generates a secret key from input data and a corresponding public key for digital signature.
|
||||||
//! \~english Function generates a secret key from input data and a corresponding public key for digital signature
|
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для цифровой подписи.
|
||||||
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для цифровой подписи
|
|
||||||
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
static bool generateSignKeys(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Function extract sign public key from sing secret key.
|
||||||
//! \~english Function extract sign public key from sing secret key
|
//! \~russian Функция извлекает открытый ключ для подписи из секретного ключа для подписи.
|
||||||
//! \~russian Функция извлекает открытый ключ для подписи из секретного ключа для подписи
|
|
||||||
static PIByteArray extractSignPublicKey(const PIByteArray & secret_key);
|
static PIByteArray extractSignPublicKey(const PIByteArray & secret_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Calculate digital signature for data.
|
||||||
//! \~english Calculate digital signature for data
|
//! \~russian Вычислить цифровую подпись для данных.
|
||||||
//! \~russian Вычислить цифровую подпись для данных
|
|
||||||
PIByteArray signMessage(const PIByteArray & data, const PIByteArray & secret_key);
|
PIByteArray signMessage(const PIByteArray & data, const PIByteArray & secret_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Verify digital signature of signed message.
|
||||||
//! \~english Verify digital signature of signed message
|
//! \~russian Проверить цифровую подпись подписанного сообщения.
|
||||||
//! \~russian Проверить цифровую подпись подписанного сообщения
|
|
||||||
bool verifySign(const PIByteArray & data, const PIByteArray & signature, const PIByteArray & public_key);
|
bool verifySign(const PIByteArray & data, const PIByteArray & signature, const PIByteArray & public_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Function randomly generates a secret key and a corresponding public key for authenticated encryption.
|
||||||
//! \~english Function randomly generates a secret key and a corresponding public key for authenticated encryption
|
|
||||||
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для аутентифицированного
|
//! \~russian Функция случайным образом генерирует секретный ключ и соответствующий ему открытый ключ для аутентифицированного
|
||||||
//! шифрования
|
//! шифрования.
|
||||||
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key);
|
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Function generates a secret key from input data and a corresponding public key for authenticated encryption.
|
||||||
//! \~english Function generates a secret key from input data and a corresponding public key for authenticated encryption
|
|
||||||
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для аутентифицированного
|
//! \~russian Функция генерирует секретный ключ из входных данных и соответствующий ему открытый ключ для аутентифицированного
|
||||||
//! шифрования
|
//! шифрования.
|
||||||
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
static bool generateKeypair(PIByteArray & public_key, PIByteArray & secret_key, const PIByteArray & seed);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Encrypt given data "data".
|
||||||
//! \~english Encrypt given data "data"
|
//! \~russian Зашифровать данные "data".
|
||||||
//! \~russian Зашифровать данные "data"
|
|
||||||
PIByteArray crypt(const PIByteArray & data, const PIByteArray & public_key, const PIByteArray & secret_key);
|
PIByteArray crypt(const PIByteArray & data, const PIByteArray & public_key, const PIByteArray & secret_key);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Decrypt given data "crypt_data".
|
||||||
//! \~english Decrypt given data "crypt_data"
|
//! \~russian Расшифровать данные "crypt_data".
|
||||||
//! \~russian Расшифровать данные "crypt_data"
|
|
||||||
PIByteArray decrypt(const PIByteArray & crypt_data, const PIByteArray & public_key, const PIByteArray & secret_key, bool * ok = 0);
|
PIByteArray decrypt(const PIByteArray & crypt_data, const PIByteArray & public_key, const PIByteArray & secret_key, bool * ok = 0);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Generate password hash from "password".
|
||||||
//! \~english Generate password hash from "password"
|
//! \~russian Генерировать хэш пароля из "password".
|
||||||
//! \~russian Генерировать хэш пароля из "password"
|
|
||||||
static PIByteArray passwordHash(PIString password, const PIByteArray & seed);
|
static PIByteArray passwordHash(PIString password, const PIByteArray & seed);
|
||||||
|
|
||||||
//! \~\brief
|
//! \~english Returns libsodium version.
|
||||||
//! \~english Returns libsodium version
|
//! \~russian Возвращает версию libsodium.
|
||||||
//! \~russian Возвращает версию libsodium
|
|
||||||
static PIString version();
|
static PIString version();
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file picryptmodule.h
|
||||||
|
* \ingroup Crypt
|
||||||
|
* \~\brief
|
||||||
|
* \~english Umbrella header for the Crypt module
|
||||||
|
* \~russian Зонтичный заголовок модуля Crypt
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public cryptographic and authentication headers.
|
||||||
|
* \~russian Подключает публичные заголовки шифрования и аутентификации.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
|
|||||||
@@ -1,15 +1,8 @@
|
|||||||
/*! \file pidigest.h
|
//! \~\file pidigest.h
|
||||||
* \ingroup Core
|
//! \~\ingroup Digest
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Digest algorithms
|
//! \~english Digest calculation helpers
|
||||||
* \~russian Алгоритмы хэш-сумм
|
//! \~russian Вспомогательные методы вычисления хэш-сумм
|
||||||
*
|
|
||||||
* \~\details
|
|
||||||
* \~english
|
|
||||||
* This file implements several common-usage hash algorithms
|
|
||||||
* \~russian
|
|
||||||
* Этот файл реализует несколько распространенных алгоритмов хэширования
|
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Digest algorithms
|
Digest algorithms
|
||||||
@@ -35,47 +28,72 @@
|
|||||||
#include "pibytearray.h"
|
#include "pibytearray.h"
|
||||||
#include "piconstchars.h"
|
#include "piconstchars.h"
|
||||||
|
|
||||||
|
//! \class PIDigest
|
||||||
|
//! \~\ingroup Digest
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english One-shot digest API for supported algorithms.
|
||||||
|
//! \~russian Одношаговый API хэширования для поддерживаемых алгоритмов.
|
||||||
class PIP_EXPORT PIDigest {
|
class PIP_EXPORT PIDigest {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Supported digest algorithms.
|
||||||
|
//! \~russian Поддерживаемые алгоритмы хэширования.
|
||||||
enum class Type {
|
enum class Type {
|
||||||
SHA1,
|
SHA1 /** \~english SHA-1 \~russian SHA-1 */,
|
||||||
|
|
||||||
SHA2_224,
|
SHA2_224 /** \~english SHA-2 with 224-bit digest \~russian SHA-2 с дайджестом 224 бита */,
|
||||||
SHA2_256,
|
SHA2_256 /** \~english SHA-2 with 256-bit digest \~russian SHA-2 с дайджестом 256 бит */,
|
||||||
SHA2_384,
|
SHA2_384 /** \~english SHA-2 with 384-bit digest \~russian SHA-2 с дайджестом 384 бита */,
|
||||||
SHA2_512,
|
SHA2_512 /** \~english SHA-2 with 512-bit digest \~russian SHA-2 с дайджестом 512 бит */,
|
||||||
SHA2_512_224,
|
SHA2_512_224 /** \~english SHA-512/224 \~russian SHA-512/224 */,
|
||||||
SHA2_512_256,
|
SHA2_512_256 /** \~english SHA-512/256 \~russian SHA-512/256 */,
|
||||||
|
|
||||||
MD2,
|
MD2 /** \~english MD2 \~russian MD2 */,
|
||||||
MD4,
|
MD4 /** \~english MD4 \~russian MD4 */,
|
||||||
MD5,
|
MD5 /** \~english MD5 \~russian MD5 */,
|
||||||
|
|
||||||
BLAKE2s_128,
|
BLAKE2s_128 /** \~english BLAKE2s with 128-bit digest \~russian BLAKE2s с дайджестом 128 бит */,
|
||||||
BLAKE2s_160,
|
BLAKE2s_160 /** \~english BLAKE2s with 160-bit digest \~russian BLAKE2s с дайджестом 160 бит */,
|
||||||
BLAKE2s_224,
|
BLAKE2s_224 /** \~english BLAKE2s with 224-bit digest \~russian BLAKE2s с дайджестом 224 бита */,
|
||||||
BLAKE2s_256,
|
BLAKE2s_256 /** \~english BLAKE2s with 256-bit digest \~russian BLAKE2s с дайджестом 256 бит */,
|
||||||
BLAKE2b_128,
|
BLAKE2b_128 /** \~english BLAKE2b with 128-bit digest \~russian BLAKE2b с дайджестом 128 бит */,
|
||||||
BLAKE2b_160,
|
BLAKE2b_160 /** \~english BLAKE2b with 160-bit digest \~russian BLAKE2b с дайджестом 160 бит */,
|
||||||
BLAKE2b_224,
|
BLAKE2b_224 /** \~english BLAKE2b with 224-bit digest \~russian BLAKE2b с дайджестом 224 бита */,
|
||||||
BLAKE2b_256,
|
BLAKE2b_256 /** \~english BLAKE2b with 256-bit digest \~russian BLAKE2b с дайджестом 256 бит */,
|
||||||
BLAKE2b_384,
|
BLAKE2b_384 /** \~english BLAKE2b with 384-bit digest \~russian BLAKE2b с дайджестом 384 бита */,
|
||||||
BLAKE2b_512,
|
BLAKE2b_512 /** \~english BLAKE2b with 512-bit digest \~russian BLAKE2b с дайджестом 512 бит */,
|
||||||
|
|
||||||
SipHash_2_4_64,
|
SipHash_2_4_64 /** \~english SipHash-2-4 with 64-bit output \~russian SipHash-2-4 с выходом 64 бита */,
|
||||||
SipHash_2_4_128,
|
SipHash_2_4_128 /** \~english SipHash-2-4 with 128-bit output \~russian SipHash-2-4 с выходом 128 бит */,
|
||||||
HalfSipHash_2_4_32,
|
HalfSipHash_2_4_32 /** \~english HalfSipHash-2-4 with 32-bit output \~russian HalfSipHash-2-4 с выходом 32 бита */,
|
||||||
HalfSipHash_2_4_64,
|
HalfSipHash_2_4_64 /** \~english HalfSipHash-2-4 with 64-bit output \~russian HalfSipHash-2-4 с выходом 64 бита */,
|
||||||
|
|
||||||
Count,
|
Count /** \~english Number of supported algorithms \~russian Количество поддерживаемых алгоритмов */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns digest length in bytes for algorithm "type".
|
||||||
|
//! \~russian Возвращает длину дайджеста в байтах для алгоритма "type".
|
||||||
static int hashLength(Type type);
|
static int hashLength(Type type);
|
||||||
|
|
||||||
|
//! \~english Returns internal block length in bytes for algorithm "type".
|
||||||
|
//! \~russian Возвращает внутреннюю длину блока в байтах для алгоритма "type".
|
||||||
static int blockLength(Type type);
|
static int blockLength(Type type);
|
||||||
|
|
||||||
|
//! \~english Returns stable algorithm name for "type".
|
||||||
|
//! \~russian Возвращает стабильное имя алгоритма для "type".
|
||||||
static PIConstChars typeName(Type type);
|
static PIConstChars typeName(Type type);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Calculates digest of message "msg" with algorithm "type".
|
||||||
|
//! \~russian Вычисляет хэш сообщения "msg" алгоритмом "type".
|
||||||
static PIByteArray calculate(const PIByteArray & msg, Type type);
|
static PIByteArray calculate(const PIByteArray & msg, Type type);
|
||||||
|
|
||||||
|
//! \~english Calculates keyed digest for algorithms with native key support, otherwise returns empty array.
|
||||||
|
//! \~russian Вычисляет keyed digest для алгоритмов с нативной поддержкой ключа, иначе возвращает пустой массив.
|
||||||
static PIByteArray calculateWithKey(const PIByteArray & msg, const PIByteArray & key, Type type);
|
static PIByteArray calculateWithKey(const PIByteArray & msg, const PIByteArray & key, Type type);
|
||||||
|
|
||||||
|
//! \~english Calculates HMAC for message "msg" and key "key" with algorithm "type".
|
||||||
|
//! \~russian Вычисляет HMAC для сообщения "msg" и ключа "key" алгоритмом "type".
|
||||||
static PIByteArray HMAC(const PIByteArray & msg, const PIByteArray & key, PIDigest::Type type);
|
static PIByteArray HMAC(const PIByteArray & msg, const PIByteArray & key, PIDigest::Type type);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piellipsoidmodel.h
|
//! \~\ingroup Geo
|
||||||
* \ingroup Geo
|
//! \~\file piellipsoidmodel.h
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Geographical ellipsoid Earth models
|
//! \~english Geographical ellipsoid Earth models
|
||||||
* \~russian Географическая эллипсоидная модель Земли
|
//! \~russian Географическая эллипсоидная модель Земли
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Contains geo ellipsoid models
|
Contains geo ellipsoid models
|
||||||
@@ -29,21 +28,60 @@
|
|||||||
|
|
||||||
#include "pimathbase.h"
|
#include "pimathbase.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Geo
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Reference ellipsoid parameters used by geographic calculations.
|
||||||
|
//! \~russian Параметры опорного эллипсоида для географических вычислений.
|
||||||
|
//! \details
|
||||||
|
//! \~english This module provides Earth ellipsoid models used in geodesy and navigation systems. It includes standard models like WGS84,
|
||||||
|
//! PZ90, GPS, and Krasovskiy.
|
||||||
|
//! \~russian Этот модуль предоставляет модели эллипсоидов Земли, используемые в геодезии и навигационных системах. Он включает стандартные
|
||||||
|
//! модели WGS84, ПЗ-90, GPS и Красовского.
|
||||||
class PIP_EXPORT PIEllipsoidModel {
|
class PIP_EXPORT PIEllipsoidModel {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an empty ellipsoid description.
|
||||||
|
//! \~russian Создает пустое описание эллипсоида.
|
||||||
PIEllipsoidModel();
|
PIEllipsoidModel();
|
||||||
double eccSquared() const { return eccentricity * eccentricity; } // eccentricity squared
|
|
||||||
|
//! \~english Returns squared eccentricity.
|
||||||
|
//! \~russian Возвращает квадрат эксцентриситета.
|
||||||
|
double eccSquared() const { return eccentricity * eccentricity; }
|
||||||
|
|
||||||
|
//! \~english Returns semi-minor axis in meters.
|
||||||
|
//! \~russian Возвращает малую полуось в метрах.
|
||||||
double b() const { return a * sqrt(1 - eccSquared()); }
|
double b() const { return a * sqrt(1 - eccSquared()); }
|
||||||
|
|
||||||
|
//! \~english Returns the WGS84 reference ellipsoid.
|
||||||
|
//! \~russian Возвращает опорный эллипсоид WGS84.
|
||||||
static PIEllipsoidModel WGS84Ellipsoid();
|
static PIEllipsoidModel WGS84Ellipsoid();
|
||||||
|
|
||||||
|
//! \~english Returns the PZ-90 reference ellipsoid.
|
||||||
|
//! \~russian Возвращает опорный эллипсоид ПЗ-90.
|
||||||
static PIEllipsoidModel PZ90Ellipsoid();
|
static PIEllipsoidModel PZ90Ellipsoid();
|
||||||
|
|
||||||
|
//! \~english Returns the GPS ellipsoid variant used by this module.
|
||||||
|
//! \~russian Возвращает вариант GPS-эллипсоида, используемый в этом модуле.
|
||||||
static PIEllipsoidModel GPSEllipsoid();
|
static PIEllipsoidModel GPSEllipsoid();
|
||||||
|
|
||||||
|
//! \~english Returns the Krasovskiy reference ellipsoid.
|
||||||
|
//! \~russian Возвращает опорный эллипсоид Красовского.
|
||||||
static PIEllipsoidModel KrasovskiyEllipsoid();
|
static PIEllipsoidModel KrasovskiyEllipsoid();
|
||||||
|
|
||||||
double a; /// Major axis of Earth in meters
|
//! \~english Semi-major axis in meters.
|
||||||
double flattening; /// Flattening (ellipsoid parameter)
|
//! \~russian Большая полуось в метрах.
|
||||||
double eccentricity; /// Eccentricity (ellipsoid parameter)
|
double a;
|
||||||
double angVelocity; /// Angular velocity of Earth in radians/sec
|
|
||||||
|
//! \~english Flattening coefficient.
|
||||||
|
//! \~russian Коэффициент сжатия.
|
||||||
|
double flattening;
|
||||||
|
|
||||||
|
//! \~english First eccentricity.
|
||||||
|
//! \~russian Первый эксцентриситет.
|
||||||
|
double eccentricity;
|
||||||
|
|
||||||
|
//! \~english Angular velocity in radians per second.
|
||||||
|
//! \~russian Угловая скорость в радианах в секунду.
|
||||||
|
double angVelocity;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file pigeomodule.h
|
||||||
|
* \ingroup Geo
|
||||||
|
* \~\brief
|
||||||
|
* \~english Entry header for the Geo module
|
||||||
|
* \~russian Входной заголовок модуля Geo
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the public geographic position header.
|
||||||
|
* \~russian Подключает публичный заголовок географической позиции.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -16,17 +26,16 @@
|
|||||||
You should have received a copy of the GNU Lesser General Public License
|
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/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
//! \defgroup Geo Geo
|
//! \addtogroup Geo
|
||||||
//! \~\brief
|
//! \{
|
||||||
//! \~english Geographical position and Earth models
|
//! \~\file pigeomodule.h
|
||||||
//! \~russian Географическая позиция и модели Земли
|
//! \brief
|
||||||
//!
|
//! \~english Geographical position and Earth models module
|
||||||
//! \~\details
|
//! \~russian Модуль географической позиции и моделей Земли
|
||||||
//! \~english \section cmake_module_Geo Building with CMake
|
//! \details
|
||||||
//! \~russian \section cmake_module_Geo Сборка с использованием CMake
|
//! \~english This module provides classes for geographical position storage, coordinate transformations, and Earth models.
|
||||||
//!
|
//! \~russian Этот модуль предоставляет классы для хранения географической позиции, преобразования координат и моделей Земли.
|
||||||
//! \~\code
|
//! \~\}
|
||||||
//! find_package(PIP REQUIRED)
|
|
||||||
//! target_link_libraries([target] PIP)
|
//! target_link_libraries([target] PIP)
|
||||||
//! \endcode
|
//! \endcode
|
||||||
//!
|
//!
|
||||||
@@ -34,12 +43,12 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides geographical position, several Earth models and converting
|
//! The module provides Earth ellipsoid models, geographic position storage and
|
||||||
//! from one model to another.
|
//! conversions between supported coordinate systems.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают географическую позицию, несколько моделей Земли и
|
//! Модуль предоставляет модели земного эллипсоида, хранение географической
|
||||||
//! преобразования из одной модели в другую.
|
//! позиции и преобразования между поддерживаемыми системами координат.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pigeoposition.h
|
//! \~\ingroup Geo
|
||||||
* \ingroup Geo
|
//! \~\file pigeoposition.h
|
||||||
* \~\brief
|
//! \brief
|
||||||
* \~english Class for geo position storage and conversions
|
//! \~english Class for geo position storage and conversions
|
||||||
* \~russian Класс для хранения географической позиции и преобразований
|
//! \~russian Класс для хранения географической позиции и преобразований
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Class for geo position storage and conversions
|
Class for geo position storage and conversions
|
||||||
@@ -29,147 +28,285 @@
|
|||||||
#include "piellipsoidmodel.h"
|
#include "piellipsoidmodel.h"
|
||||||
#include "pimathvector.h"
|
#include "pimathvector.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Geo
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Geographic position represented in one of several coordinate systems.
|
||||||
|
//! \~russian Географическая позиция, представленная в одной из нескольких систем координат.
|
||||||
|
//! \details
|
||||||
|
//! \~english This class provides functionality for storing and converting between different coordinate systems including geodetic,
|
||||||
|
//! geocentric, Cartesian, and spherical coordinates. It supports various ellipsoid models for Earth representation.
|
||||||
|
//! \~russian Этот класс предоставляет функциональность для хранения и преобразования между различными системами координат, включая
|
||||||
|
//! геодезическую, геоцентрическую, декартову и сферическую. Он поддерживает различные модели эллипсоида для представления Земли.
|
||||||
class PIP_EXPORT PIGeoPosition: public PIMathVectorT3d {
|
class PIP_EXPORT PIGeoPosition: public PIMathVectorT3d {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Coordinate system used by stored components.
|
||||||
|
//! \~russian Система координат, используемая для хранимых компонент.
|
||||||
enum CoordinateSystem {
|
enum CoordinateSystem {
|
||||||
Unknown = 0, /// Unknown coordinate system
|
Unknown = 0 /** \~english Unknown coordinate system \~russian Неизвестная система координат */,
|
||||||
Geodetic, /// Geodetic latitude, longitude, and height above ellipsoid
|
Geodetic /** \~english Geodetic latitude, longitude and height above the ellipsoid \~russian Геодезическая широта, долгота и высота
|
||||||
Geocentric, /// Geocentric (regular spherical coordinates)
|
над эллипсоидом */
|
||||||
Cartesian, /// Cartesian (Earth-centered, Earth-fixed)
|
,
|
||||||
Spherical /// Spherical coordinates (theta,phi,radius)
|
Geocentric /** \~english Geocentric latitude, longitude and radius \~russian Геоцентрическая широта, долгота и радиус */,
|
||||||
|
Cartesian /** \~english Earth-centered Earth-fixed Cartesian coordinates \~russian Декартовы координаты ECEF */,
|
||||||
|
Spherical /** \~english Spherical coordinates as theta, phi and radius \~russian Сферические координаты: тета, фи и радиус */
|
||||||
};
|
};
|
||||||
|
|
||||||
static const double one_cm_tolerance; /// One centimeter tolerance.
|
//! \~english One centimeter tolerance in meters.
|
||||||
static const double one_mm_tolerance; /// One millimeter tolerance.
|
//! \~russian Допуск в один сантиметр в метрах.
|
||||||
static const double one_um_tolerance; /// One micron tolerance.
|
static const double one_cm_tolerance;
|
||||||
static double position_tolerance; /// Default tolerance (default 1mm)
|
|
||||||
|
//! \~english One millimeter tolerance in meters.
|
||||||
|
//! \~russian Допуск в один миллиметр в метрах.
|
||||||
|
static const double one_mm_tolerance;
|
||||||
|
|
||||||
|
//! \~english One micron tolerance in meters.
|
||||||
|
//! \~russian Допуск в один микрон в метрах.
|
||||||
|
static const double one_um_tolerance;
|
||||||
|
|
||||||
|
//! \~english Default comparison and singularity tolerance in meters.
|
||||||
|
//! \~russian Допуск по умолчанию для сравнений и вырожденных случаев, в метрах.
|
||||||
|
static double position_tolerance;
|
||||||
|
|
||||||
|
//! \~english Sets the default tolerance in meters.
|
||||||
|
//! \~russian Устанавливает допуск по умолчанию в метрах.
|
||||||
static double setPositionTolerance(const double tol) {
|
static double setPositionTolerance(const double tol) {
|
||||||
position_tolerance = tol;
|
position_tolerance = tol;
|
||||||
return position_tolerance;
|
return position_tolerance;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns the default tolerance in meters.
|
||||||
|
//! \~russian Возвращает допуск по умолчанию в метрах.
|
||||||
static double getPositionTolerance() { return position_tolerance; }
|
static double getPositionTolerance() { return position_tolerance; }
|
||||||
|
|
||||||
|
//! \~english Constructs the zero position in Cartesian coordinates.
|
||||||
|
//! \~russian Создает нулевую позицию в декартовой системе координат.
|
||||||
PIGeoPosition();
|
PIGeoPosition();
|
||||||
|
|
||||||
|
//! \~english Constructs a position from three components in the selected coordinate system.
|
||||||
|
//! \~russian Создает позицию из трех компонент в выбранной системе координат.
|
||||||
PIGeoPosition(double a, double b, double c, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIGeoPosition(double a, double b, double c, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
|
//! \~english Constructs a position from an existing 3D vector.
|
||||||
|
//! \~russian Создает позицию из существующего трехмерного вектора.
|
||||||
PIGeoPosition(PIMathVectorT3d v, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIGeoPosition(PIMathVectorT3d v, CoordinateSystem s = Cartesian, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Converts the stored value to another coordinate system in place.
|
||||||
|
//! \~russian Преобразует хранимое значение в другую систему координат на месте.
|
||||||
PIGeoPosition & transformTo(CoordinateSystem sys);
|
PIGeoPosition & transformTo(CoordinateSystem sys);
|
||||||
|
|
||||||
|
//! \~english Converts this position to geodetic coordinates.
|
||||||
|
//! \~russian Преобразует позицию в геодезические координаты.
|
||||||
PIGeoPosition & asGeodetic() {
|
PIGeoPosition & asGeodetic() {
|
||||||
transformTo(Geodetic);
|
transformTo(Geodetic);
|
||||||
return *this;
|
return *this;
|
||||||
} /// Convert to geodetic coordinate
|
}
|
||||||
|
|
||||||
|
//! \~english Switches to another ellipsoid and converts to geodetic coordinates.
|
||||||
|
//! \~russian Переключает эллипсоид и преобразует позицию в геодезические координаты.
|
||||||
PIGeoPosition & asGeodetic(const PIEllipsoidModel & ell) {
|
PIGeoPosition & asGeodetic(const PIEllipsoidModel & ell) {
|
||||||
setEllipsoidModel(ell);
|
setEllipsoidModel(ell);
|
||||||
transformTo(Geodetic);
|
transformTo(Geodetic);
|
||||||
return *this;
|
return *this;
|
||||||
} /// Convert to another ell, then to geodetic coordinates
|
}
|
||||||
|
|
||||||
|
//! \~english Converts this position to Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Преобразует позицию в декартовы координаты ECEF.
|
||||||
PIGeoPosition & asECEF() {
|
PIGeoPosition & asECEF() {
|
||||||
transformTo(Cartesian);
|
transformTo(Cartesian);
|
||||||
return *this;
|
return *this;
|
||||||
} /// Convert to cartesian coordinates
|
}
|
||||||
|
|
||||||
|
//! \~english Returns the X component in Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Возвращает компоненту X в декартовых координатах ECEF.
|
||||||
double x() const;
|
double x() const;
|
||||||
|
|
||||||
|
//! \~english Returns the Y component in Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Возвращает компоненту Y в декартовых координатах ECEF.
|
||||||
double y() const;
|
double y() const;
|
||||||
|
|
||||||
|
//! \~english Returns the Z component in Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Возвращает компоненту Z в декартовых координатах ECEF.
|
||||||
double z() const;
|
double z() const;
|
||||||
|
|
||||||
|
//! \~english Returns geodetic latitude in degrees.
|
||||||
|
//! \~russian Возвращает геодезическую широту в градусах.
|
||||||
double latitudeGeodetic() const;
|
double latitudeGeodetic() const;
|
||||||
|
|
||||||
|
//! \~english Returns geocentric latitude in degrees.
|
||||||
|
//! \~russian Возвращает геоцентрическую широту в градусах.
|
||||||
double latitudeGeocentric() const;
|
double latitudeGeocentric() const;
|
||||||
|
|
||||||
|
//! \~english Returns longitude in degrees.
|
||||||
|
//! \~russian Возвращает долготу в градусах.
|
||||||
double longitude() const;
|
double longitude() const;
|
||||||
|
|
||||||
|
//! \~english Returns spherical theta angle in degrees (angle from Z axis).
|
||||||
|
//! \~russian Возвращает сферический угол тета в градусах (угол от оси Z).
|
||||||
double theta() const;
|
double theta() const;
|
||||||
|
|
||||||
|
//! \~english Returns spherical phi angle in degrees (angle in XY plane from X axis).
|
||||||
|
//! \~russian Возвращает сферический угол фи в градусах (угол в плоскости XY от оси X).
|
||||||
double phi() const;
|
double phi() const;
|
||||||
|
|
||||||
|
//! \~english Returns radius in meters for spherical or geocentric form (distance from Earth center).
|
||||||
|
//! \~russian Возвращает радиус в метрах для сферического или геоцентрического представления (расстояние от центра Земли).
|
||||||
double radius() const;
|
double radius() const;
|
||||||
|
|
||||||
|
//! \~english Returns geodetic height above the ellipsoid in meters.
|
||||||
|
//! \~russian Возвращает геодезическую высоту над эллипсоидом в метрах.
|
||||||
double height() const;
|
double height() const;
|
||||||
|
|
||||||
/// Set the ellipsoid values for this PIGeoPosition given a ellipsoid.
|
//! \~english Sets the ellipsoid model used by geodetic conversions.
|
||||||
|
//! \~russian Устанавливает модель эллипсоида, используемую в геодезических преобразованиях.
|
||||||
void setEllipsoidModel(const PIEllipsoidModel & ell) { el = ell; }
|
void setEllipsoidModel(const PIEllipsoidModel & ell) { el = ell; }
|
||||||
|
|
||||||
/// Set the \a PIGeoPosition given geodetic coordinates in degrees. \a CoordinateSystem is set to \a Geodetic.
|
//! \~english Sets geodetic latitude, longitude and height in degrees/meters.
|
||||||
|
//! \~russian Устанавливает геодезические широту, долготу и высоту в градусах и метрах.
|
||||||
PIGeoPosition & setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIGeoPosition & setGeodetic(double lat, double lon, double ht, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
/// Set the \a PIGeoPosition given geocentric coordinates in degrees. \a CoordinateSystem is set to \a Geocentric
|
//! \~english Sets geocentric latitude, longitude and radius in degrees/meters.
|
||||||
|
//! \~russian Устанавливает геоцентрические широту, долготу и радиус в градусах и метрах.
|
||||||
PIGeoPosition & setGeocentric(double lat, double lon, double rad);
|
PIGeoPosition & setGeocentric(double lat, double lon, double rad);
|
||||||
|
|
||||||
/// Set the \a PIGeoPosition given spherical coordinates in degrees. \a CoordinateSystem is set to \a Spherical
|
//! \~english Sets spherical theta, phi and radius in degrees/meters.
|
||||||
|
//! \~russian Устанавливает сферические тета, фи и радиус в градусах и метрах.
|
||||||
PIGeoPosition & setSpherical(double theta, double phi, double rad);
|
PIGeoPosition & setSpherical(double theta, double phi, double rad);
|
||||||
|
|
||||||
/// Set the \a PIGeoPosition given ECEF coordinates in meeters. \a CoordinateSystem is set to \a Cartesian.
|
//! \~english Sets Cartesian ECEF coordinates in meters.
|
||||||
|
//! \~russian Устанавливает декартовы координаты ECEF в метрах.
|
||||||
PIGeoPosition & setECEF(double x, double y, double z);
|
PIGeoPosition & setECEF(double x, double y, double z);
|
||||||
|
|
||||||
/// Fundamental conversion from spherical to cartesian coordinates.
|
//! \~english Converts spherical coordinates to Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Преобразует сферические координаты в декартовы координаты ECEF.
|
||||||
static void convertSphericalToCartesian(const PIMathVectorT3d & tpr, PIMathVectorT3d & xyz);
|
static void convertSphericalToCartesian(const PIMathVectorT3d & tpr, PIMathVectorT3d & xyz);
|
||||||
|
|
||||||
/// Fundamental routine to convert cartesian to spherical coordinates.
|
//! \~english Converts Cartesian ECEF coordinates to spherical coordinates.
|
||||||
|
//! \~russian Преобразует декартовы координаты ECEF в сферические координаты.
|
||||||
static void convertCartesianToSpherical(const PIMathVectorT3d & xyz, PIMathVectorT3d & tpr);
|
static void convertCartesianToSpherical(const PIMathVectorT3d & xyz, PIMathVectorT3d & tpr);
|
||||||
|
|
||||||
/// Fundamental routine to convert ECEF (cartesian) to geodetic coordinates,
|
//! \~english Converts Cartesian ECEF coordinates to geodetic coordinates.
|
||||||
|
//! \~russian Преобразует декартовы координаты ECEF в геодезические координаты.
|
||||||
static void convertCartesianToGeodetic(const PIMathVectorT3d & xyz,
|
static void convertCartesianToGeodetic(const PIMathVectorT3d & xyz,
|
||||||
PIMathVectorT3d & llh,
|
PIMathVectorT3d & llh,
|
||||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
/// Fundamental routine to convert geodetic to ECEF (cartesian) coordinates,
|
//! \~english Converts geodetic coordinates to Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Преобразует геодезические координаты в декартовы координаты ECEF.
|
||||||
static void convertGeodeticToCartesian(const PIMathVectorT3d & llh,
|
static void convertGeodeticToCartesian(const PIMathVectorT3d & llh,
|
||||||
PIMathVectorT3d & xyz,
|
PIMathVectorT3d & xyz,
|
||||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
/// Fundamental routine to convert cartesian (ECEF) to geocentric
|
//! \~english Converts Cartesian ECEF coordinates to geocentric coordinates.
|
||||||
|
//! \~russian Преобразует декартовы координаты ECEF в геоцентрические координаты.
|
||||||
static void convertCartesianToGeocentric(const PIMathVectorT3d & xyz, PIMathVectorT3d & llr);
|
static void convertCartesianToGeocentric(const PIMathVectorT3d & xyz, PIMathVectorT3d & llr);
|
||||||
|
|
||||||
/// Fundamental routine to convert geocentric to cartesian (ECEF)
|
//! \~english Converts geocentric coordinates to Cartesian ECEF coordinates.
|
||||||
|
//! \~russian Преобразует геоцентрические координаты в декартовы координаты ECEF.
|
||||||
static void convertGeocentricToCartesian(const PIMathVectorT3d & llr, PIMathVectorT3d & xyz);
|
static void convertGeocentricToCartesian(const PIMathVectorT3d & llr, PIMathVectorT3d & xyz);
|
||||||
|
|
||||||
/// Fundamental routine to convert geocentric to geodetic
|
//! \~english Converts geocentric coordinates to geodetic coordinates.
|
||||||
|
//! \~russian Преобразует геоцентрические координаты в геодезические координаты.
|
||||||
static void convertGeocentricToGeodetic(const PIMathVectorT3d & llr,
|
static void convertGeocentricToGeodetic(const PIMathVectorT3d & llr,
|
||||||
PIMathVectorT3d & llh,
|
PIMathVectorT3d & llh,
|
||||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
/// Fundamental routine to convert geodetic to geocentric
|
//! \~english Converts geodetic coordinates to geocentric coordinates.
|
||||||
|
//! \~russian Преобразует геодезические координаты в геоцентрические координаты.
|
||||||
static void convertGeodeticToGeocentric(const PIMathVectorT3d & llh,
|
static void convertGeodeticToGeocentric(const PIMathVectorT3d & llh,
|
||||||
PIMathVectorT3d & llr,
|
PIMathVectorT3d & llr,
|
||||||
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
/// Compute the radius of the ellipsoidal Earth, given the geodetic latitude.
|
//! \~english Returns ellipsoid radius at the given geodetic latitude.
|
||||||
|
//! \~russian Возвращает радиус эллипсоида на заданной геодезической широте.
|
||||||
static double radiusEarth(double geolat, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
static double radiusEarth(double geolat, PIEllipsoidModel ell = PIEllipsoidModel::WGS84Ellipsoid());
|
||||||
|
|
||||||
|
//! \~english Returns ellipsoid radius for this position.
|
||||||
|
//! \~russian Возвращает радиус эллипсоида для этой позиции.
|
||||||
double radiusEarth() const {
|
double radiusEarth() const {
|
||||||
PIGeoPosition p(*this);
|
PIGeoPosition p(*this);
|
||||||
p.transformTo(PIGeoPosition::Geodetic);
|
p.transformTo(PIGeoPosition::Geodetic);
|
||||||
return PIGeoPosition::radiusEarth((*this)[0], p.el);
|
return PIGeoPosition::radiusEarth((*this)[0], p.el);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Compute the range in meters between two PIGeoPositions.
|
//! \~english Returns straight-line range between two positions in meters.
|
||||||
|
//! \~russian Возвращает прямую дальность между двумя позициями в метрах.
|
||||||
static double range(const PIGeoPosition & a, const PIGeoPosition & b);
|
static double range(const PIGeoPosition & a, const PIGeoPosition & b);
|
||||||
|
|
||||||
|
//! \~english Returns straight-line range to another position in meters.
|
||||||
|
//! \~russian Возвращает прямую дальность до другой позиции в метрах.
|
||||||
double range(const PIGeoPosition & p) const { return range((*this), p); }
|
double range(const PIGeoPosition & p) const { return range((*this), p); }
|
||||||
|
|
||||||
/// Computes the elevation of the input (p) position as seen from this PIGeoPosition.
|
//! \~english Computes elevation to another position.
|
||||||
|
//! \~russian Вычисляет угол места до другой позиции.
|
||||||
double elevation(const PIGeoPosition & p) const;
|
double elevation(const PIGeoPosition & p) const;
|
||||||
|
|
||||||
/// Computes the elevation of the input (p) position as seen from this PIGeoPosition, using a Geodetic (ellipsoidal) system.
|
//! \~english Computes elevation using local geodetic vertical.
|
||||||
|
//! \~russian Вычисляет угол места относительно локальной геодезической вертикали.
|
||||||
double elevationGeodetic(const PIGeoPosition & p) const;
|
double elevationGeodetic(const PIGeoPosition & p) const;
|
||||||
|
|
||||||
/// Computes the azimuth of the input (p) position as seen from this PIGeoPosition.
|
//! \~english Computes azimuth to another position.
|
||||||
|
//! \~russian Вычисляет азимут на другую позицию.
|
||||||
double azimuth(const PIGeoPosition & p) const;
|
double azimuth(const PIGeoPosition & p) const;
|
||||||
|
|
||||||
/// Computes the azimuth of the input (p) position as seen from this PIGeoPosition, using a Geodetic (ellipsoidal) system.
|
//! \~english Computes azimuth using local geodetic north-east axes.
|
||||||
|
//! \~russian Вычисляет азимут по локальным геодезическим осям север-восток.
|
||||||
double azimuthGeodetic(const PIGeoPosition & p) const;
|
double azimuthGeodetic(const PIGeoPosition & p) const;
|
||||||
|
|
||||||
/// Computes the radius of curvature of the meridian (Rm) corresponding to this PIGeoPosition.
|
//! \~english Returns meridian radius of curvature for this position.
|
||||||
|
//! \~russian Возвращает радиус кривизны меридиана для этой позиции.
|
||||||
double getCurvMeridian() const;
|
double getCurvMeridian() const;
|
||||||
|
|
||||||
/// Computes the radius of curvature in the prime vertical (Rn) corresponding to this PIGeoPosition.
|
//! \~english Returns prime-vertical radius of curvature for this position.
|
||||||
|
//! \~russian Возвращает радиус кривизны первого вертикала для этой позиции.
|
||||||
double getCurvPrimeVertical() const;
|
double getCurvPrimeVertical() const;
|
||||||
|
|
||||||
/// Returns as PIMathVectorT3d
|
//! \~english Returns the underlying three-component vector in the current system.
|
||||||
|
//! \~russian Возвращает базовый трехкомпонентный вектор в текущей системе.
|
||||||
const PIMathVectorT3d & vector() const { return *this; }
|
const PIMathVectorT3d & vector() const { return *this; }
|
||||||
|
|
||||||
|
//! \~english Assigns coordinates from a plain 3D vector without changing metadata.
|
||||||
|
//! \~russian Присваивает координаты из обычного 3D-вектора без изменения метаданных.
|
||||||
PIGeoPosition & operator=(const PIMathVectorT3d & v);
|
PIGeoPosition & operator=(const PIMathVectorT3d & v);
|
||||||
|
|
||||||
|
//! \~english Subtracts another position after converting both operands to Cartesian coordinates.
|
||||||
|
//! \~russian Вычитает другую позицию после перевода обоих операндов в декартовы координаты.
|
||||||
PIGeoPosition & operator-=(const PIGeoPosition & right);
|
PIGeoPosition & operator-=(const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Adds another position after converting both operands to Cartesian coordinates.
|
||||||
|
//! \~russian Складывает другую позицию после перевода обоих операндов в декартовы координаты.
|
||||||
PIGeoPosition & operator+=(const PIGeoPosition & right);
|
PIGeoPosition & operator+=(const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Returns Cartesian difference of two positions.
|
||||||
|
//! \~russian Возвращает декартову разность двух позиций.
|
||||||
friend PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right);
|
friend PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Returns Cartesian sum of two positions.
|
||||||
|
//! \~russian Возвращает декартову сумму двух позиций.
|
||||||
friend PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right);
|
friend PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Scales a position by a floating-point factor.
|
||||||
|
//! \~russian Масштабирует позицию вещественным коэффициентом.
|
||||||
friend PIGeoPosition operator*(const double & scale, const PIGeoPosition & right);
|
friend PIGeoPosition operator*(const double & scale, const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Scales a position by a floating-point factor.
|
||||||
|
//! \~russian Масштабирует позицию вещественным коэффициентом.
|
||||||
friend PIGeoPosition operator*(const PIGeoPosition & left, const double & scale);
|
friend PIGeoPosition operator*(const PIGeoPosition & left, const double & scale);
|
||||||
|
|
||||||
|
//! \~english Scales a position by an integer factor.
|
||||||
|
//! \~russian Масштабирует позицию целочисленным коэффициентом.
|
||||||
friend PIGeoPosition operator*(const int & scale, const PIGeoPosition & right);
|
friend PIGeoPosition operator*(const int & scale, const PIGeoPosition & right);
|
||||||
|
|
||||||
|
//! \~english Scales a position by an integer factor.
|
||||||
|
//! \~russian Масштабирует позицию целочисленным коэффициентом.
|
||||||
friend PIGeoPosition operator*(const PIGeoPosition & left, const int & scale);
|
friend PIGeoPosition operator*(const PIGeoPosition & left, const int & scale);
|
||||||
|
|
||||||
|
//! \~english Compares two positions using the configured tolerance and ellipsoid model.
|
||||||
|
//! \~russian Сравнивает две позиции с учетом настроенного допуска и модели эллипсоида.
|
||||||
bool operator==(const PIGeoPosition & right) const;
|
bool operator==(const PIGeoPosition & right) const;
|
||||||
|
|
||||||
|
//! \~english Returns true when positions are not equal.
|
||||||
|
//! \~russian Возвращает true, если позиции не равны.
|
||||||
bool operator!=(const PIGeoPosition & right) const { return !(operator==(right)); }
|
bool operator!=(const PIGeoPosition & right) const { return !(operator==(right)); }
|
||||||
|
|
||||||
|
|
||||||
@@ -181,6 +318,11 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Subtraction
|
||||||
|
//! \~russian Вычитание
|
||||||
|
//! \details
|
||||||
|
//! \~english Subtracts two positions by converting them to Cartesian coordinates and performing element-wise subtraction.
|
||||||
|
//! \~russian Вычитает две позиции путем преобразования их в декартовы координаты и выполнения поэлементного вычитания.
|
||||||
inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right) {
|
inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||||
PIGeoPosition l(left), r(right);
|
PIGeoPosition l(left), r(right);
|
||||||
l.transformTo(PIGeoPosition::Cartesian);
|
l.transformTo(PIGeoPosition::Cartesian);
|
||||||
@@ -188,6 +330,12 @@ inline PIGeoPosition operator-(const PIGeoPosition & left, const PIGeoPosition &
|
|||||||
l -= r;
|
l -= r;
|
||||||
return l;
|
return l;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Addition
|
||||||
|
//! \~russian Сложение
|
||||||
|
//! \details
|
||||||
|
//! \~english Adds two positions by converting them to Cartesian coordinates and performing element-wise addition.
|
||||||
|
//! \~russian Складывает две позиции путем преобразования их в декартовы координаты и выполнения поэлементного сложения.
|
||||||
inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right) {
|
inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition & right) {
|
||||||
PIGeoPosition l(left), r(right);
|
PIGeoPosition l(left), r(right);
|
||||||
l.transformTo(PIGeoPosition::Cartesian);
|
l.transformTo(PIGeoPosition::Cartesian);
|
||||||
@@ -195,17 +343,40 @@ inline PIGeoPosition operator+(const PIGeoPosition & left, const PIGeoPosition &
|
|||||||
l += r;
|
l += r;
|
||||||
return l;
|
return l;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Scalar multiplication (double)
|
||||||
|
//! \~russian Умножение на скаляр (double)
|
||||||
|
//! \details
|
||||||
|
//! \~english Multiplies a position by a double scalar value.
|
||||||
|
//! \~russian Умножает позицию на скалярное значение типа double.
|
||||||
inline PIGeoPosition operator*(const double & scale, const PIGeoPosition & right) {
|
inline PIGeoPosition operator*(const double & scale, const PIGeoPosition & right) {
|
||||||
PIMathVectorT3d tmp(right);
|
PIMathVectorT3d tmp(right);
|
||||||
tmp *= scale;
|
tmp *= scale;
|
||||||
return PIGeoPosition(tmp);
|
return PIGeoPosition(tmp);
|
||||||
}
|
}
|
||||||
|
//! \~english Scalar multiplication (double)
|
||||||
|
//! \~russian Умножение на скаляр (double)
|
||||||
|
//! \details
|
||||||
|
//! \~english Multiplies a position by a double scalar value.
|
||||||
|
//! \~russian Умножает позицию на скалярное значение типа double.
|
||||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const double & scale) {
|
inline PIGeoPosition operator*(const PIGeoPosition & left, const double & scale) {
|
||||||
return operator*(scale, left);
|
return operator*(scale, left);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Scalar multiplication (int)
|
||||||
|
//! \~russian Умножение на скаляр (int)
|
||||||
|
//! \details
|
||||||
|
//! \~english Multiplies a position by an integer scalar value.
|
||||||
|
//! \~russian Умножает позицию на скалярное значение типа int.
|
||||||
inline PIGeoPosition operator*(const int & scale, const PIGeoPosition & right) {
|
inline PIGeoPosition operator*(const int & scale, const PIGeoPosition & right) {
|
||||||
return operator*(double(scale), right);
|
return operator*(double(scale), right);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Scalar multiplication (int)
|
||||||
|
//! \~russian Умножение на скаляр (int)
|
||||||
|
//! \details
|
||||||
|
//! \~english Multiplies a position by an integer scalar value.
|
||||||
|
//! \~russian Умножает позицию на скалярное значение типа int.
|
||||||
inline PIGeoPosition operator*(const PIGeoPosition & left, const int & scale) {
|
inline PIGeoPosition operator*(const PIGeoPosition & left, const int & scale) {
|
||||||
return operator*(double(scale), left);
|
return operator*(double(scale), left);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,27 @@
|
|||||||
|
//! \~\file pihttpclient.h
|
||||||
|
//! \~\ingroup HTTP
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Public HTTP client request API
|
||||||
|
//! \~russian Публичный API HTTP-клиента для выполнения запросов
|
||||||
|
/*
|
||||||
|
PIP - Platform Independent Primitives
|
||||||
|
Public HTTP client request API
|
||||||
|
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 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
#ifndef pihttpclient_h
|
#ifndef pihttpclient_h
|
||||||
#define pihttpclient_h
|
#define pihttpclient_h
|
||||||
|
|
||||||
@@ -13,57 +37,65 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \~english Main HTTP client class for performing requests with event callbacks.
|
//! \~\ingroup HTTP
|
||||||
//! \~russian Основной класс HTTP-клиента для выполнения запросов с callback-ми событий.
|
//! \~\brief
|
||||||
|
//! \~english Asynchronous HTTP client request with completion callbacks.
|
||||||
|
//! \~russian Асинхронный HTTP-запрос клиента с callback-ами завершения.
|
||||||
class PIP_HTTP_CLIENT_EXPORT PIHTTPClient: private PIHTTPClientBase {
|
class PIP_HTTP_CLIENT_EXPORT PIHTTPClient: private PIHTTPClientBase {
|
||||||
friend class PIHTTPClientBase;
|
friend class PIHTTPClientBase;
|
||||||
friend class CurlThreadPool;
|
friend class CurlThreadPool;
|
||||||
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Creates a new HTTP request instance with the specified URL, method and message.
|
//! \~english Creates a request object for the specified URL, method and initial message data.
|
||||||
//! \~russian Создает новый экземпляр HTTP-запроса с указанным URL, методом и сообщением.
|
//! \~russian Создает объект запроса для указанного URL, метода и начальных данных сообщения.
|
||||||
static PIHTTPClient * create(const PIString & url, PIHTTP::Method method = PIHTTP::Method::Get, const PIHTTP::MessageConst & req = {});
|
static PIHTTPClient * create(const PIString & url, PIHTTP::Method method = PIHTTP::Method::Get, const PIHTTP::MessageConst & req = {});
|
||||||
|
|
||||||
//! \~english Sets a callback for successful request completion (no parameters).
|
|
||||||
//! \~russian Устанавливает callback для успешного завершения запроса (без параметров).
|
//! \~english Sets a callback invoked when the transfer completes successfully.
|
||||||
|
//! \~russian Устанавливает callback, вызываемый при успешном завершении передачи.
|
||||||
PIHTTPClient * onFinish(std::function<void()> f);
|
PIHTTPClient * onFinish(std::function<void()> f);
|
||||||
|
|
||||||
//! \~english Sets a callback for successful request completion (with response).
|
//! \~english Sets a callback invoked when the transfer completes successfully and provides the parsed reply.
|
||||||
//! \~russian Устанавливает callback для успешного завершения запроса (с ответом).
|
//! \~russian Устанавливает callback, вызываемый при успешном завершении передачи, и передает разобранный ответ.
|
||||||
PIHTTPClient * onFinish(std::function<void(const PIHTTP::MessageConst &)> f);
|
PIHTTPClient * onFinish(std::function<void(const PIHTTP::MessageConst &)> f);
|
||||||
|
|
||||||
//! \~english Sets a callback for request errors (no parameters).
|
//! \~english Sets a callback invoked when the transfer fails with a transport-level error.
|
||||||
//! \~russian Устанавливает callback для ошибок запроса (без параметров).
|
//! \~russian Устанавливает callback, вызываемый при ошибке передачи на транспортном уровне.
|
||||||
PIHTTPClient * onError(std::function<void()> f);
|
PIHTTPClient * onError(std::function<void()> f);
|
||||||
|
|
||||||
//! \~english Sets a callback for request errors (with error response).
|
//! \~english Sets a callback invoked when the transfer fails with a transport-level error and provides the partial reply state.
|
||||||
//! \~russian Устанавливает callback для ошибок запроса (с ответом об ошибке).
|
//! \~russian Устанавливает callback, вызываемый при ошибке передачи на транспортном уровне, и передает текущее состояние ответа.
|
||||||
PIHTTPClient * onError(std::function<void(const PIHTTP::MessageConst &)> f);
|
PIHTTPClient * onError(std::function<void(const PIHTTP::MessageConst &)> f);
|
||||||
|
|
||||||
//! \~english Sets a callback for request abortion (no parameters).
|
//! \~english Sets a callback invoked when the request is aborted.
|
||||||
//! \~russian Устанавливает callback для прерывания запроса (без параметров).
|
//! \~russian Устанавливает callback, вызываемый при прерывании запроса.
|
||||||
PIHTTPClient * onAbort(std::function<void()> f);
|
PIHTTPClient * onAbort(std::function<void()> f);
|
||||||
|
|
||||||
//! \~english Sets a callback for request abortion (with abort response).
|
//! \~english Sets a callback invoked when the request is aborted and provides the current reply state.
|
||||||
//! \~russian Устанавливает callback для прерывания запроса (с ответом о прерывании).
|
//! \~russian Устанавливает callback, вызываемый при прерывании запроса, и передает текущее состояние ответа.
|
||||||
PIHTTPClient * onAbort(std::function<void(const PIHTTP::MessageConst &)> f);
|
PIHTTPClient * onAbort(std::function<void(const PIHTTP::MessageConst &)> f);
|
||||||
|
|
||||||
//! \~english Setup request to ignore SSL errors. Need to call before \a start().
|
|
||||||
//! \~russian Устанавливает игнорирование ошибок SSL. Необходимо вызывать перед \a start().
|
//! \~english Disables SSL verification checks for this request. Call \b before \a start().
|
||||||
|
//! \~russian Отключает проверки SSL для этого запроса. Вызывайте \b до \a start().
|
||||||
PIHTTPClient * ignoreSSLErrors();
|
PIHTTPClient * ignoreSSLErrors();
|
||||||
|
|
||||||
//! \~english Starts the HTTP request execution.
|
|
||||||
//! \~russian Начинает выполнение HTTP-запроса.
|
//! \~english Queues the request for asynchronous execution.
|
||||||
|
//! \~russian Ставит запрос в очередь на асинхронное выполнение.
|
||||||
void start();
|
void start();
|
||||||
|
|
||||||
//! \~english Aborts the current HTTP request.
|
//! \~english Requests cancellation of the running transfer.
|
||||||
//! \~russian Прерывает текущий HTTP-запрос.
|
//! \~russian Запрашивает отмену выполняющейся передачи.
|
||||||
void abort();
|
void abort();
|
||||||
|
|
||||||
//! \~english Returns the last error message.
|
|
||||||
//! \~russian Возвращает последнее сообщение об ошибке.
|
//! \~english Returns the last transport error message.
|
||||||
|
//! \~russian Возвращает последнее сообщение об ошибке транспортного уровня.
|
||||||
PIString lastError() const { return last_error; }
|
PIString lastError() const { return last_error; }
|
||||||
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
NO_COPY_CLASS(PIHTTPClient)
|
NO_COPY_CLASS(PIHTTPClient)
|
||||||
PIHTTPClient();
|
PIHTTPClient();
|
||||||
|
|||||||
@@ -1,7 +1,19 @@
|
|||||||
|
//! \~\file pihttpclientmodule.h
|
||||||
|
//! \~\ingroup HTTPClient
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english HTTP client module includes for PIP library
|
||||||
|
//! \~russian Модуль инклюдов HTTP клиента для библиотеки PIP
|
||||||
|
//! \details
|
||||||
|
//! \~english
|
||||||
|
//! This file includes all HTTP client module headers providing async HTTP client functionality
|
||||||
|
//! using libcurl for performing HTTP requests with callbacks.
|
||||||
|
//! \~russian
|
||||||
|
//! Этот файл включает все заголовки модуля HTTP клиента, предоставляющие функциональность
|
||||||
|
//! асинхронного HTTP клиента с использованием libcurl.
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
Ivan Pelipenko peri4ko@yandex.ru
|
||||||
|
|
||||||
This program is free software: you can redistribute it and/or modify
|
This program is free software: you can redistribute it and/or modify
|
||||||
it under the terms of the GNU Lesser General Public License as published by
|
it under the terms of the GNU Lesser General Public License as published by
|
||||||
@@ -16,28 +28,20 @@
|
|||||||
You should have received a copy of the GNU Lesser General Public License
|
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/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
//! \defgroup HTTPServer HTTPServer
|
//! \defgroup HTTPClient HTTPClient
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english HTTP client
|
//! \~english HTTP client
|
||||||
//! \~russian HTTP сервер
|
//! \~russian HTTP клиент
|
||||||
//!
|
|
||||||
//! \~\details
|
|
||||||
//! \~english \section cmake_module_HTTPServer Building with CMake
|
|
||||||
//! \~russian \section cmake_module_HTTPServer Сборка с использованием CMake
|
|
||||||
//!
|
//!
|
||||||
//! \~\code
|
//! \~\code
|
||||||
//! find_package(PIP REQUIRED)
|
//! find_package(PIP REQUIRED)
|
||||||
//! target_link_libraries([target] PIP::HTTPServer)
|
//! target_link_libraries([target] PIP::HTTPClient)
|
||||||
//! \endcode
|
//! \endcode
|
||||||
//!
|
//! \~\details
|
||||||
//! \~english \par Common
|
|
||||||
//! \~russian \par Общее
|
|
||||||
//!
|
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides HTTP server based on libmicrohttpd
|
//! These files provide HTTP client functionality using libcurl for performing asynchronous HTTP requests with callbacks.
|
||||||
//!
|
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают HTTP сервер, основанный на libmicrohttpd
|
//! Эти файлы предоставляют функциональность HTTP клиента с использованием libcurl для выполнения асинхронных HTTP запросов с callback-ми.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,41 @@
|
|||||||
|
//! \~\ingroup 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
|
||||||
|
//! заголовков.
|
||||||
|
/*
|
||||||
|
PIP - Platform Independent Primitives
|
||||||
|
HTTP constants and enumerations
|
||||||
|
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 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
#ifndef pihttpconstants_h
|
#ifndef pihttpconstants_h
|
||||||
#define pihttpconstants_h
|
#define pihttpconstants_h
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Namespace with shared HTTP constants and vocabulary.
|
||||||
|
//! \~russian Пространство имен с общими HTTP-константами и базовой терминологией.
|
||||||
namespace PIHTTP {
|
namespace PIHTTP {
|
||||||
|
|
||||||
|
//! \~english HTTP request method.
|
||||||
|
//! \~russian HTTP-метод запроса.
|
||||||
enum class Method {
|
enum class Method {
|
||||||
Unknown,
|
Unknown,
|
||||||
Get,
|
Get,
|
||||||
@@ -14,9 +46,11 @@ enum class Method {
|
|||||||
Connect,
|
Connect,
|
||||||
Options,
|
Options,
|
||||||
Trace,
|
Trace,
|
||||||
Patch
|
Patch,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english HTTP status code.
|
||||||
|
//! \~russian HTTP-код статуса.
|
||||||
enum class Code {
|
enum class Code {
|
||||||
Unknown = -1,
|
Unknown = -1,
|
||||||
Continue = 100,
|
Continue = 100,
|
||||||
@@ -90,7 +124,14 @@ enum class Code {
|
|||||||
NetworkAuthenticationRequired = 511,
|
NetworkAuthenticationRequired = 511,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Namespace with shared HTTP header field name literals.
|
||||||
|
//! \~russian Пространство имен с общими строковыми литералами имен HTTP-заголовков.
|
||||||
|
//!
|
||||||
|
//! \~english Constant names follow the header field names used on the wire.
|
||||||
|
//! \~russian Имена констант повторяют имена полей заголовков, используемые в протоколе.
|
||||||
namespace Header {
|
namespace Header {
|
||||||
|
//! \~english Common request and response header fields.
|
||||||
|
//! \~russian Общие поля заголовков запросов и ответов.
|
||||||
constexpr static char Accept[] = "Accept";
|
constexpr static char Accept[] = "Accept";
|
||||||
constexpr static char AcceptCharset[] = "Accept-Charset";
|
constexpr static char AcceptCharset[] = "Accept-Charset";
|
||||||
constexpr static char AcceptEncoding[] = "Accept-Encoding";
|
constexpr static char AcceptEncoding[] = "Accept-Encoding";
|
||||||
@@ -140,7 +181,11 @@ constexpr static char UserAgent[] = "User-Agent";
|
|||||||
constexpr static char Vary[] = "Vary";
|
constexpr static char Vary[] = "Vary";
|
||||||
constexpr static char Via[] = "Via";
|
constexpr static char Via[] = "Via";
|
||||||
constexpr static char WWWAuthenticate[] = "WWW-Authenticate";
|
constexpr static char WWWAuthenticate[] = "WWW-Authenticate";
|
||||||
|
//! \~english Special wildcard token used by some HTTP fields.
|
||||||
|
//! \~russian Специальный подстановочный токен, используемый некоторыми HTTP-полями.
|
||||||
constexpr static char Asterisk[] = "*";
|
constexpr static char Asterisk[] = "*";
|
||||||
|
//! \~english Extended, CORS, security and protocol-specific header fields.
|
||||||
|
//! \~russian Расширенные, CORS-, security- и protocol-specific поля заголовков.
|
||||||
constexpr static char AIM[] = "A-IM";
|
constexpr static char AIM[] = "A-IM";
|
||||||
constexpr static char AcceptAdditions[] = "Accept-Additions";
|
constexpr static char AcceptAdditions[] = "Accept-Additions";
|
||||||
constexpr static char AcceptCH[] = "Accept-CH";
|
constexpr static char AcceptCH[] = "Accept-CH";
|
||||||
|
|||||||
@@ -1,3 +1,27 @@
|
|||||||
|
//! \~\file pihttptypes.h
|
||||||
|
//! \~\ingroup HTTP
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Shared HTTP message container types
|
||||||
|
//! \~russian Общие типы контейнеров HTTP-сообщений
|
||||||
|
/*
|
||||||
|
PIP - Platform Independent Primitives
|
||||||
|
Shared HTTP message container types
|
||||||
|
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 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
#ifndef pihttptypes_h
|
#ifndef pihttptypes_h
|
||||||
#define pihttptypes_h
|
#define pihttptypes_h
|
||||||
|
|
||||||
@@ -6,71 +30,76 @@
|
|||||||
#include "pistringlist.h"
|
#include "pistringlist.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Namespace with shared HTTP data types.
|
||||||
|
//! \~russian Пространство имен с общими HTTP-типами данных.
|
||||||
namespace PIHTTP {
|
namespace PIHTTP {
|
||||||
|
|
||||||
|
|
||||||
//! \~english Immutable HTTP message container with accessors for message components
|
//! \~\ingroup HTTP
|
||||||
//! \~russian Контейнер для неизменяемого HTTP-сообщения с методами доступа к компонентам
|
//! \~\brief
|
||||||
|
//! \~english Immutable HTTP message view with accessors for method, path, headers and body.
|
||||||
|
//! \~russian Неизменяемое HTTP-сообщение с доступом к методу, пути, заголовкам и телу.
|
||||||
class PIP_EXPORT MessageConst {
|
class PIP_EXPORT MessageConst {
|
||||||
public:
|
public:
|
||||||
//! \~english Gets the HTTP method used in the message
|
//! \~english Returns the HTTP method of the message.
|
||||||
//! \~russian Возвращает HTTP-метод, использованный в сообщении
|
//! \~russian Возвращает HTTP-метод сообщения.
|
||||||
PIHTTP::Method method() const { return m_method; }
|
PIHTTP::Method method() const { return m_method; }
|
||||||
|
|
||||||
//! \~english Gets the HTTP status code
|
//! \~english Returns the HTTP status code of the message.
|
||||||
//! \~russian Возвращает HTTP-статус код
|
//! \~russian Возвращает HTTP-код статуса сообщения.
|
||||||
PIHTTP::Code code() const { return m_code; }
|
PIHTTP::Code code() const { return m_code; }
|
||||||
|
|
||||||
//! \~english Checks if status code is informational (1xx)
|
//! \~english Returns \c true for informational status codes in the 1xx range.
|
||||||
//! \~russian Проверяет, является ли статус код информационным (1xx)
|
//! \~russian Возвращает \c true для информационных кодов статуса из диапазона 1xx.
|
||||||
bool isCodeInformational() const;
|
bool isCodeInformational() const;
|
||||||
|
|
||||||
//! \~english Checks if status code indicates success (2xx)
|
//! \~english Returns \c true for successful status codes in the 2xx range.
|
||||||
//! \~russian Проверяет, указывает ли статус код на успех (2xx)
|
//! \~russian Возвращает \c true для успешных кодов статуса из диапазона 2xx.
|
||||||
bool isCodeSuccess() const;
|
bool isCodeSuccess() const;
|
||||||
|
|
||||||
//! \~english Checks if status code indicates redirection (3xx)
|
//! \~english Returns \c true for redirection status codes in the 3xx range.
|
||||||
//! \~russian Проверяет, указывает ли статус код на перенаправление (3xx)
|
//! \~russian Возвращает \c true для кодов перенаправления из диапазона 3xx.
|
||||||
bool isCodeRedirection() const;
|
bool isCodeRedirection() const;
|
||||||
|
|
||||||
//! \~english Checks if status code indicates client error (4xx)
|
//! \~english Returns \c true for client error status codes in the 4xx range.
|
||||||
//! \~russian Проверяет, указывает ли статус код на ошибку клиента (4xx)
|
//! \~russian Возвращает \c true для кодов ошибки клиента из диапазона 4xx.
|
||||||
bool isCodeClientError() const;
|
bool isCodeClientError() const;
|
||||||
|
|
||||||
//! \~english Checks if status code indicates server error (5xx)
|
//! \~english Returns \c true for server error status codes in the 5xx range.
|
||||||
//! \~russian Проверяет, указывает ли статус код на ошибку сервера (5xx)
|
//! \~russian Возвращает \c true для кодов ошибки сервера из диапазона 5xx.
|
||||||
bool isCodeServerError() const;
|
bool isCodeServerError() const;
|
||||||
|
|
||||||
//! \~english Checks if status code indicates any error (4xx or 5xx)
|
//! \~english Returns \c true for any client or server error status code.
|
||||||
//! \~russian Проверяет, указывает ли статус код на любую ошибку (4xx или 5xx)
|
//! \~russian Возвращает \c true для любого кода ошибки клиента или сервера.
|
||||||
bool isCodeError() const { return isCodeClientError() || isCodeServerError(); }
|
bool isCodeError() const { return isCodeClientError() || isCodeServerError(); }
|
||||||
|
|
||||||
//! \~english Gets the request/response path
|
|
||||||
//! \~russian Возвращает путь запроса/ответа
|
//! \~english Returns the request path or response target path.
|
||||||
|
//! \~russian Возвращает путь запроса или целевой путь ответа.
|
||||||
const PIString & path() const { return m_path; }
|
const PIString & path() const { return m_path; }
|
||||||
|
|
||||||
//! \~english Gets path components as list
|
//! \~english Returns the path split into non-empty components.
|
||||||
//! \~russian Возвращает компоненты пути в виде списка
|
//! \~russian Возвращает путь, разбитый на непустые компоненты.
|
||||||
PIStringList pathList() const { return m_path.split('/').removeAll({}); }
|
PIStringList pathList() const { return m_path.split('/').removeAll({}); }
|
||||||
|
|
||||||
//! \~english Gets the message body
|
//! \~english Returns the message body.
|
||||||
//! \~russian Возвращает тело сообщения
|
//! \~russian Возвращает тело сообщения.
|
||||||
const PIByteArray & body() const { return m_body; }
|
const PIByteArray & body() const { return m_body; }
|
||||||
|
|
||||||
//! \~english Gets all message headers
|
//! \~english Returns all message headers.
|
||||||
//! \~russian Возвращает все заголовки сообщения
|
//! \~russian Возвращает все заголовки сообщения.
|
||||||
const PIMap<PIString, PIString> & headers() const { return m_headers; }
|
const PIMap<PIString, PIString> & headers() const { return m_headers; }
|
||||||
|
|
||||||
//! \~english Gets URL query arguments
|
//! \~english Returns parsed query arguments from the URL.
|
||||||
//! \~russian Возвращает URL query аргументы
|
//! \~russian Возвращает разобранные query-аргументы URL.
|
||||||
const PIMap<PIString, PIString> & queryArguments() const { return m_query_arguments; }
|
const PIMap<PIString, PIString> & queryArguments() const { return m_query_arguments; }
|
||||||
|
|
||||||
//! \~english Gets URL path arguments
|
//! \~english Returns extracted path arguments.
|
||||||
//! \~russian Возвращает URL path аргументы
|
//! \~russian Возвращает извлеченные аргументы пути.
|
||||||
const PIMap<PIString, PIString> & pathArguments() const { return m_path_arguments; }
|
const PIMap<PIString, PIString> & pathArguments() const { return m_path_arguments; }
|
||||||
|
|
||||||
//! \~english Gets all message arguments (query + path)
|
//! \~english Returns the combined argument map from query and path arguments.
|
||||||
//! \~russian Возвращает все аргументы сообщения (query + path)
|
//! \~russian Возвращает объединенную карту аргументов из query и path.
|
||||||
const PIMap<PIString, PIString> & arguments() const { return m_arguments; }
|
const PIMap<PIString, PIString> & arguments() const { return m_arguments; }
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -83,78 +112,101 @@ protected:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \~english Mutable HTTP message container with modifiers for message components
|
//! \~\ingroup HTTP
|
||||||
//! \~russian Контейнер для изменяемого HTTP-сообщения с методами модификации
|
//! \~\brief
|
||||||
|
//! \~english Mutable HTTP message with setters and argument/header modifiers.
|
||||||
|
//! \~russian Изменяемое HTTP-сообщение с сеттерами и методами изменения аргументов и заголовков.
|
||||||
class PIP_EXPORT MessageMutable: public MessageConst {
|
class PIP_EXPORT MessageMutable: public MessageConst {
|
||||||
public:
|
public:
|
||||||
//! \~english Sets the HTTP method
|
//! \~english Sets the HTTP method.
|
||||||
//! \~russian Устанавливает HTTP-метод
|
//! \~russian Устанавливает HTTP-метод.
|
||||||
MessageMutable & setMethod(PIHTTP::Method m);
|
MessageMutable & setMethod(PIHTTP::Method m);
|
||||||
|
|
||||||
//! \~english Sets the HTTP status code
|
//! \~english Sets the HTTP status code.
|
||||||
//! \~russian Устанавливает HTTP-статус код
|
//! \~russian Устанавливает HTTP-код статуса.
|
||||||
MessageMutable & setCode(PIHTTP::Code c);
|
MessageMutable & setCode(PIHTTP::Code c);
|
||||||
|
|
||||||
//! \~english Sets the request/response path
|
//! \~english Sets the request path or response target path.
|
||||||
//! \~russian Устанавливает путь запроса/ответа
|
//! \~russian Устанавливает путь запроса или целевой путь ответа.
|
||||||
MessageMutable & setPath(PIString p);
|
MessageMutable & setPath(PIString p);
|
||||||
|
|
||||||
//! \~english Sets the message body
|
//! \~english Sets the message body.
|
||||||
//! \~russian Устанавливает тело сообщения
|
//! \~russian Устанавливает тело сообщения.
|
||||||
MessageMutable & setBody(PIByteArray b);
|
MessageMutable & setBody(PIByteArray b);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns all message headers.
|
||||||
|
//! \~russian Возвращает все заголовки сообщения.
|
||||||
const PIMap<PIString, PIString> & headers() const { return m_headers; }
|
const PIMap<PIString, PIString> & headers() const { return m_headers; }
|
||||||
|
|
||||||
|
//! \~english Returns a modifiable map of all arguments.
|
||||||
|
//! \~russian Возвращает изменяемую карту всех аргументов.
|
||||||
PIMap<PIString, PIString> & arguments() { return m_arguments; }
|
PIMap<PIString, PIString> & arguments() { return m_arguments; }
|
||||||
|
|
||||||
|
//! \~english Returns all arguments.
|
||||||
|
//! \~russian Возвращает все аргументы.
|
||||||
const PIMap<PIString, PIString> & arguments() const { return m_arguments; }
|
const PIMap<PIString, PIString> & arguments() const { return m_arguments; }
|
||||||
|
|
||||||
|
//! \~english Returns query arguments.
|
||||||
|
//! \~russian Возвращает query-аргументы.
|
||||||
const PIMap<PIString, PIString> & queryArguments() const { return m_query_arguments; }
|
const PIMap<PIString, PIString> & queryArguments() const { return m_query_arguments; }
|
||||||
|
|
||||||
|
//! \~english Returns path arguments.
|
||||||
|
//! \~russian Возвращает аргументы пути.
|
||||||
const PIMap<PIString, PIString> & pathArguments() const { return m_path_arguments; }
|
const PIMap<PIString, PIString> & pathArguments() const { return m_path_arguments; }
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns a modifiable map of all message headers.
|
||||||
|
//! \~russian Возвращает изменяемую карту всех заголовков сообщения.
|
||||||
PIMap<PIString, PIString> & headers() { return m_headers; }
|
PIMap<PIString, PIString> & headers() { return m_headers; }
|
||||||
|
|
||||||
//! \~english Adds a header to the message
|
//! \~english Adds or replaces a header in the message.
|
||||||
//! \~russian Добавляет заголовок к сообщению
|
//! \~russian Добавляет заголовок в сообщение или заменяет существующий.
|
||||||
MessageMutable & addHeader(const PIString & header, const PIString & value);
|
MessageMutable & addHeader(const PIString & header, const PIString & value);
|
||||||
|
|
||||||
//! \~english Removes a header from the message
|
//! \~english Removes a header from the message.
|
||||||
//! \~russian Удаляет заголовок из сообщения
|
//! \~russian Удаляет заголовок из сообщения.
|
||||||
MessageMutable & removeHeader(const PIString & header);
|
MessageMutable & removeHeader(const PIString & header);
|
||||||
|
|
||||||
//! \~english Gets reference to URL query arguments
|
|
||||||
//! \~russian Возвращает ссылку на URL query аргументы
|
//! \~english Returns a modifiable map of query arguments.
|
||||||
|
//! \~russian Возвращает изменяемую карту query-аргументов.
|
||||||
PIMap<PIString, PIString> & queryArguments() { return m_query_arguments; }
|
PIMap<PIString, PIString> & queryArguments() { return m_query_arguments; }
|
||||||
|
|
||||||
//! \~english Adds an URL query argument to the message
|
//! \~english Adds or replaces a query argument.
|
||||||
//! \~russian Добавляет URL query аргумент к сообщению
|
//! \~russian Добавляет query-аргумент или заменяет существующий.
|
||||||
MessageMutable & addQueryArgument(const PIString & arg, const PIString & value);
|
MessageMutable & addQueryArgument(const PIString & arg, const PIString & value);
|
||||||
|
|
||||||
//! \~english Removes an URL query argument from the message
|
//! \~english Removes a query argument.
|
||||||
//! \~russian Удаляет URL query аргумент из сообщения
|
//! \~russian Удаляет query-аргумент.
|
||||||
MessageMutable & removeQueryArgument(const PIString & arg);
|
MessageMutable & removeQueryArgument(const PIString & arg);
|
||||||
|
|
||||||
//! \~english Gets reference to URL path arguments
|
|
||||||
//! \~russian Возвращает ссылку на URL path аргументы
|
//! \~english Returns a modifiable map of path arguments.
|
||||||
|
//! \~russian Возвращает изменяемую карту аргументов пути.
|
||||||
PIMap<PIString, PIString> & pathArguments() { return m_path_arguments; }
|
PIMap<PIString, PIString> & pathArguments() { return m_path_arguments; }
|
||||||
|
|
||||||
//! \~english Adds an URL path argument to the message
|
//! \~english Adds or replaces a path argument.
|
||||||
//! \~russian Добавляет URL path аргумент к сообщению
|
//! \~russian Добавляет аргумент пути или заменяет существующий.
|
||||||
MessageMutable & addPathArgument(const PIString & arg, const PIString & value);
|
MessageMutable & addPathArgument(const PIString & arg, const PIString & value);
|
||||||
|
|
||||||
//! \~english Removes an URL path argument from the message
|
//! \~english Removes a path argument.
|
||||||
//! \~russian Удаляет URL query path из сообщения
|
//! \~russian Удаляет аргумент пути.
|
||||||
MessageMutable & removePathArgument(const PIString & arg);
|
MessageMutable & removePathArgument(const PIString & arg);
|
||||||
|
|
||||||
//! \~english Creates message from HTTP status code
|
|
||||||
//! \~russian Создает сообщение из HTTP-статус кода
|
//! \~english Creates a message initialized from an HTTP status code.
|
||||||
|
//! \~russian Создает сообщение, инициализированное HTTP-кодом статуса.
|
||||||
static MessageMutable fromCode(PIHTTP::Code c);
|
static MessageMutable fromCode(PIHTTP::Code c);
|
||||||
|
|
||||||
//! \~english Creates message from HTTP method
|
//! \~english Creates a message initialized from an HTTP method.
|
||||||
//! \~russian Создает сообщение из HTTP-метода
|
//! \~russian Создает сообщение, инициализированное HTTP-методом.
|
||||||
static MessageMutable fromMethod(PIHTTP::Method m);
|
static MessageMutable fromMethod(PIHTTP::Method m);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \~english Gets string representation of HTTP method
|
//! \~english Returns the canonical string representation of an HTTP method.
|
||||||
//! \~russian Возвращает строковое представление HTTP-метода
|
//! \~russian Возвращает каноническое строковое представление HTTP-метода.
|
||||||
PIP_EXPORT const char * methodName(Method m);
|
PIP_EXPORT const char * methodName(Method m);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,3 +1,27 @@
|
|||||||
|
//! \~\file microhttpd_server.h
|
||||||
|
//! \~\ingroup HTTP
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Base HTTP server API built on top of libmicrohttpd
|
||||||
|
//! \~russian Базовый API HTTP-сервера, построенный поверх libmicrohttpd
|
||||||
|
/*
|
||||||
|
PIP - Platform Independent Primitives
|
||||||
|
Base HTTP server API built on top of libmicrohttpd
|
||||||
|
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 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
#ifndef MICROHTTPD_SERVER_P_H
|
#ifndef MICROHTTPD_SERVER_P_H
|
||||||
#define MICROHTTPD_SERVER_P_H
|
#define MICROHTTPD_SERVER_P_H
|
||||||
|
|
||||||
@@ -7,85 +31,92 @@
|
|||||||
|
|
||||||
struct MicrohttpdServerConnection;
|
struct MicrohttpdServerConnection;
|
||||||
|
|
||||||
//! \~english Base HTTP server class implementing core functionality
|
//! \~\ingroup HTTP
|
||||||
//! \~russian Базовый класс HTTP сервера, реализующий основную функциональность
|
//! \~\brief
|
||||||
|
//! \~english Base HTTP server with request dispatch and optional basic authentication.
|
||||||
|
//! \~russian Базовый HTTP-сервер с диспетчеризацией запросов и необязательной basic-аутентификацией.
|
||||||
class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
|
class PIP_HTTP_SERVER_EXPORT MicrohttpdServer: public PIObject {
|
||||||
PIOBJECT(MicrohttpdServer)
|
PIOBJECT(MicrohttpdServer)
|
||||||
friend struct MicrohttpdServerConnection;
|
friend struct MicrohttpdServerConnection;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Creates a stopped server instance with default options.
|
||||||
|
//! \~russian Создает остановленный экземпляр сервера с настройками по умолчанию.
|
||||||
MicrohttpdServer();
|
MicrohttpdServer();
|
||||||
|
//! \~english Stops the server and releases native resources.
|
||||||
|
//! \~russian Останавливает сервер и освобождает нативные ресурсы.
|
||||||
virtual ~MicrohttpdServer();
|
virtual ~MicrohttpdServer();
|
||||||
|
|
||||||
//! \~english Server configuration options
|
//! \~english Server configuration options accepted by \a setOption().
|
||||||
//! \~russian Опции конфигурации сервера
|
//! \~russian Параметры конфигурации сервера, принимаемые методом \a setOption().
|
||||||
enum class Option {
|
enum class Option {
|
||||||
ConnectionLimit, //!< \~english Maximum concurrent connections
|
ConnectionLimit /** \~english Maximum number of simultaneously accepted connections. \~russian Максимальное число одновременно
|
||||||
//!< \~russian Максимальное количество соединений
|
принимаемых соединений. */
|
||||||
ConnectionTimeout, //!< \~english Connection timeout in seconds
|
,
|
||||||
//!< \~russian Таймаут соединения в секундах
|
ConnectionTimeout /** \~english Per-connection timeout value. \~russian Значение таймаута для отдельного соединения. */,
|
||||||
HTTPSEnabled, //!< \~english Enable HTTPS support
|
HTTPSEnabled /** \~english Enables TLS mode for the daemon. \~russian Включает режим TLS для демона. */,
|
||||||
//!< \~russian Включить поддержку HTTPS
|
HTTPSMemKey /** \~english Private key stored in memory as \c PIByteArray. \~russian Приватный ключ, хранящийся в памяти в виде \c
|
||||||
HTTPSMemKey, //!< \~english SSL key in memory (PIByteArray)
|
PIByteArray. */
|
||||||
//!< \~russian SSL ключ в памяти (PIByteArray)
|
,
|
||||||
HTTPSMemCert, //!< \~english SSL certificate in memory (PIByteArray)
|
HTTPSMemCert /** \~english Certificate stored in memory as \c PIByteArray. \~russian Сертификат, хранящийся в памяти в виде \c
|
||||||
//!< \~russian SSL сертификат в памяти (PIByteArray)
|
PIByteArray. */
|
||||||
HTTPSKeyPassword //!< \~english SSL key password (PIByteArray)
|
,
|
||||||
//!< \~russian Пароль SSL ключа (PIByteArray)
|
HTTPSKeyPassword /** \~english Password for the in-memory private key as \c PIByteArray. \~russian Пароль для приватного ключа в
|
||||||
|
памяти в виде \c PIByteArray. */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Sets server option
|
//! \~english Sets a server option. The expected variant payload depends on the selected \a Option.
|
||||||
//! \~russian Устанавливает опцию сервера
|
//! \~russian Устанавливает параметр сервера. Ожидаемый тип значения \c PIVariant зависит от выбранного \a Option.
|
||||||
void setOption(Option o, PIVariant v);
|
void setOption(Option o, PIVariant v);
|
||||||
|
|
||||||
//! \~english Sets server favicon
|
//! \~english Sets the bytes returned for requests to \c /favicon.ico.
|
||||||
//! \~russian Устанавливает фавикон сервера
|
//! \~russian Устанавливает байты, возвращаемые для запросов к \c /favicon.ico.
|
||||||
void setFavicon(const PIByteArray & im);
|
void setFavicon(const PIByteArray & im);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Starts server on specified address
|
//! \~english Starts listening on the specified network address, restarting the daemon if needed.
|
||||||
//! \~russian Запускает сервер на указанном адресе
|
//! \~russian Запускает прослушивание на указанном сетевом адресе, при необходимости перезапуская демон.
|
||||||
bool listen(PINetworkAddress addr);
|
bool listen(PINetworkAddress addr);
|
||||||
|
|
||||||
//! \~english Starts server on all interfaces
|
//! \~english Starts listening on all interfaces for the specified port.
|
||||||
//! \~russian Запускает сервер на всех интерфейсах
|
//! \~russian Запускает прослушивание на всех интерфейсах для указанного порта.
|
||||||
bool listenAll(ushort port) { return listen({0, port}); }
|
bool listenAll(ushort port) { return listen({0, port}); }
|
||||||
|
|
||||||
//! \~english Checks if server is running
|
//! \~english Returns \c true while the native HTTP daemon is running.
|
||||||
//! \~russian Проверяет, работает ли сервер
|
//! \~russian Возвращает \c true, пока нативный HTTP-демон запущен.
|
||||||
bool isListen() const;
|
bool isListen() const;
|
||||||
|
|
||||||
//! \~english Stops the server
|
//! \~english Stops listening and shuts down the native HTTP daemon.
|
||||||
//! \~russian Останавливает сервер
|
//! \~russian Останавливает прослушивание и завершает работу нативного HTTP-демона.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Enables basic authentication
|
//! \~english Enables HTTP Basic authentication checks for new requests.
|
||||||
//! \~russian Включает базовую аутентификацию
|
//! \~russian Включает проверки HTTP Basic-аутентификации для новых запросов.
|
||||||
void enableBasicAuth() { setBasicAuthEnabled(true); }
|
void enableBasicAuth() { setBasicAuthEnabled(true); }
|
||||||
|
|
||||||
//! \~english Disables basic authentication
|
//! \~english Disables HTTP Basic authentication checks.
|
||||||
//! \~russian Выключает базовую аутентификацию
|
//! \~russian Отключает проверки HTTP Basic-аутентификации.
|
||||||
void disableBasicAuth() { setBasicAuthEnabled(false); }
|
void disableBasicAuth() { setBasicAuthEnabled(false); }
|
||||||
|
|
||||||
//! \~english Set basic authentication enabled to "yes"
|
//! \~english Enables or disables HTTP Basic authentication checks.
|
||||||
//! \~russian Устанавливает базовую аутентификацию в "yes"
|
//! \~russian Включает или отключает проверки HTTP Basic-аутентификации.
|
||||||
void setBasicAuthEnabled(bool yes) { use_basic_auth = yes; }
|
void setBasicAuthEnabled(bool yes) { use_basic_auth = yes; }
|
||||||
|
|
||||||
//! \~english Return if basic authentication enabled
|
//! \~english Returns whether HTTP Basic authentication checks are enabled.
|
||||||
//! \~russian Возвращает включена ли базовая аутентификация
|
//! \~russian Возвращает, включены ли проверки HTTP Basic-аутентификации.
|
||||||
bool isBasicAuthEnabled() const { return use_basic_auth; }
|
bool isBasicAuthEnabled() const { return use_basic_auth; }
|
||||||
|
|
||||||
//! \~english Sets basic authentication realm
|
//! \~english Sets the realm sent in HTTP Basic authentication challenges.
|
||||||
//! \~russian Устанавливает область аутентификации
|
//! \~russian Устанавливает realm, отправляемый в challenge HTTP Basic-аутентификации.
|
||||||
void setBasicAuthRealm(const PIString & r) { realm = r; }
|
void setBasicAuthRealm(const PIString & r) { realm = r; }
|
||||||
|
|
||||||
//! \~english Sets request processing callback
|
//! \~english Sets the callback that receives parsed requests and returns replies.
|
||||||
//! \~russian Устанавливает callback для обработки запросов
|
//! \~russian Устанавливает callback, который получает разобранные запросы и возвращает ответы.
|
||||||
void setRequestCallback(std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)> c) { callback = c; }
|
void setRequestCallback(std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)> c) { callback = c; }
|
||||||
|
|
||||||
//! \~english Sets basic authentication callback
|
//! \~english Sets the credential validator used when HTTP Basic authentication is enabled.
|
||||||
//! \~russian Устанавливает callback для базовой аутентификации
|
//! \~russian Устанавливает валидатор учетных данных, используемый при включенной HTTP Basic-аутентификации.
|
||||||
void setBasicAuthCallback(std::function<bool(const PIString &, const PIString &)> c) { callback_auth = c; }
|
void setBasicAuthCallback(std::function<bool(const PIString &, const PIString &)> c) { callback_auth = c; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,26 +1,67 @@
|
|||||||
|
//! \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 сервер с маршрутизацией по путям и регистрацией обработчиков
|
||||||
|
/*
|
||||||
|
PIP - Platform Independent Primitives
|
||||||
|
High-level HTTP server implementation
|
||||||
|
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 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
#ifndef PIHTTPSERVER_H
|
#ifndef PIHTTPSERVER_H
|
||||||
#define PIHTTPSERVER_H
|
#define PIHTTPSERVER_H
|
||||||
|
|
||||||
#include "microhttpd_server.h"
|
#include "microhttpd_server.h"
|
||||||
|
|
||||||
//! \~english HTTP server
|
//! \~\ingroup HTTP
|
||||||
//! \~russian HTTP сервер
|
//! \~\brief
|
||||||
|
//! \~english HTTP server that routes requests by method and path pattern.
|
||||||
|
//! \~russian HTTP-сервер, маршрутизирующий запросы по методу и шаблону пути.
|
||||||
|
//!
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Registered paths are matched segment by segment. The router supports fixed segments,
|
||||||
|
//! \c * for any single segment, \c ** for any tail, and \c {name} placeholders that populate
|
||||||
|
//! \a PIHTTP::MessageConst::pathArguments().
|
||||||
|
//! \~russian Зарегистрированные пути сопоставляются посегментно. Маршрутизатор поддерживает
|
||||||
|
//! фиксированные сегменты, \c * для любого одного сегмента, \c ** для любого хвоста и
|
||||||
|
//! заполнители \c {name}, которые заполняют \a PIHTTP::MessageConst::pathArguments().
|
||||||
class PIP_HTTP_SERVER_EXPORT PIHTTPServer: public MicrohttpdServer {
|
class PIP_HTTP_SERVER_EXPORT PIHTTPServer: public MicrohttpdServer {
|
||||||
PIOBJECT_SUBCLASS(PIHTTPServer, MicrohttpdServer)
|
PIOBJECT_SUBCLASS(PIHTTPServer, MicrohttpdServer)
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Creates a server with built-in path dispatching.
|
||||||
|
//! \~russian Создает сервер со встроенной диспетчеризацией по путям.
|
||||||
PIHTTPServer();
|
PIHTTPServer();
|
||||||
|
|
||||||
|
//! \~english Destroys the server and stops listening if needed.
|
||||||
|
//! \~russian Удаляет сервер и при необходимости останавливает прослушивание.
|
||||||
virtual ~PIHTTPServer();
|
virtual ~PIHTTPServer();
|
||||||
|
|
||||||
|
//! \~english Request handler used by registered routes and fallback processing.
|
||||||
|
//! \~russian Обработчик запроса, используемый зарегистрированными маршрутами и fallback-обработкой.
|
||||||
using RequestFunction = std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)>;
|
using RequestFunction = std::function<PIHTTP::MessageMutable(const PIHTTP::MessageConst &)>;
|
||||||
|
|
||||||
|
|
||||||
//! \~english Registers handler for specific path and HTTP method
|
//! \~english Registers a handler for the specified path pattern and HTTP method.
|
||||||
//! \~russian Регистрирует обработчик для указанного пути и HTTP метода
|
//! \~russian Регистрирует обработчик для указанного шаблона пути и HTTP-метода.
|
||||||
bool registerPath(const PIString & path, PIHTTP::Method method, RequestFunction functor);
|
bool registerPath(const PIString & path, PIHTTP::Method method, RequestFunction functor);
|
||||||
|
|
||||||
//! \~english Registers handler for specific path and HTTP method
|
//! \~english Registers an object method as a handler for the specified path pattern and HTTP method.
|
||||||
//! \~russian Регистрирует обработчик для указанного пути и HTTP метода
|
//! \~russian Регистрирует метод объекта как обработчик для указанного шаблона пути и HTTP-метода.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
bool
|
bool
|
||||||
registerPath(const PIString & path, PIHTTP::Method method, T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
registerPath(const PIString & path, PIHTTP::Method method, T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
||||||
@@ -28,36 +69,36 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Registers handler for unregistered pathes
|
//! \~english Registers a fallback handler for requests that did not match any route.
|
||||||
//! \~russian Регистрирует обработчик для незарегистрированных путей
|
//! \~russian Регистрирует fallback-обработчик для запросов, не совпавших ни с одним маршрутом.
|
||||||
void registerUnhandled(RequestFunction functor);
|
void registerUnhandled(RequestFunction functor);
|
||||||
|
|
||||||
//! \~english Registers handler for unregistered pathes
|
//! \~english Registers an object method as the fallback handler for unmatched requests.
|
||||||
//! \~russian Регистрирует обработчик для незарегистрированных путей
|
//! \~russian Регистрирует метод объекта как fallback-обработчик для несовпавших запросов.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
void registerUnhandled(T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
void registerUnhandled(T * o, PIHTTP::MessageMutable (T::*function)(const PIHTTP::MessageConst &)) {
|
||||||
registerUnhandled([o, function](const PIHTTP::MessageConst & m) { return (o->*function)(m); });
|
registerUnhandled([o, function](const PIHTTP::MessageConst & m) { return (o->*function)(m); });
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Unregisters handler for specific path and method
|
//! \~english Unregisters the handler for the specified path pattern and HTTP method.
|
||||||
//! \~russian Удаляет обработчик для указанного пути и метода
|
//! \~russian Удаляет обработчик для указанного шаблона пути и HTTP-метода.
|
||||||
void unregisterPath(const PIString & path, PIHTTP::Method method);
|
void unregisterPath(const PIString & path, PIHTTP::Method method);
|
||||||
|
|
||||||
//! \~english Unregisters all handlers for specific path
|
//! \~english Unregisters all handlers bound to the specified path pattern.
|
||||||
//! \~russian Удаляет все обработчики для указанного пути
|
//! \~russian Удаляет все обработчики, привязанные к указанному шаблону пути.
|
||||||
void unregisterPath(const PIString & path);
|
void unregisterPath(const PIString & path);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Adds header to all server responses
|
//! \~english Adds a header that will be copied to all replies produced by this router.
|
||||||
//! \~russian Добавляет заголовок ко всем ответам сервера
|
//! \~russian Добавляет заголовок, который будет копироваться во все ответы этого маршрутизатора.
|
||||||
void addReplyHeader(const PIString & name, const PIString & value) { reply_headers[name] = value; }
|
void addReplyHeader(const PIString & name, const PIString & value) { reply_headers[name] = value; }
|
||||||
|
|
||||||
//! \~english Removes header from server responses
|
//! \~english Removes a previously added common reply header.
|
||||||
//! \~russian Удаляет заголовок из ответов сервера
|
//! \~russian Удаляет ранее добавленный общий заголовок ответа.
|
||||||
void removeReplyHeader(const PIString & name) { reply_headers.remove(name); }
|
void removeReplyHeader(const PIString & name) { reply_headers.remove(name); }
|
||||||
|
|
||||||
//! \~english Clears all custom response headers
|
//! \~english Clears all custom headers added to router replies.
|
||||||
//! \~russian Очищает все пользовательские заголовки ответов
|
//! \~russian Очищает все пользовательские заголовки, добавленные к ответам маршрутизатора.
|
||||||
void clearReplyHeaders() { reply_headers.clear(); }
|
void clearReplyHeaders() { reply_headers.clear(); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file pihttpservermodule.h
|
||||||
|
* \ingroup HTTP
|
||||||
|
* \~\brief
|
||||||
|
* \~english Module include for the public HTTP server API
|
||||||
|
* \~russian Модульный include для публичного API HTTP-сервера
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the primary public HTTP server class declarations.
|
||||||
|
* \~russian Подключает основные публичные объявления классов HTTP-сервера.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -16,39 +26,21 @@
|
|||||||
You should have received a copy of the GNU Lesser General Public License
|
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/>.
|
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
//! \defgroup HTTPServer HTTPServer
|
|
||||||
//! \~\brief
|
|
||||||
//! \~english HTTP server
|
|
||||||
//! \~russian HTTP сервер
|
|
||||||
//!
|
|
||||||
//! \~\details
|
|
||||||
//! \~english \section cmake_module_HTTPServer Building with CMake
|
|
||||||
//! \~russian \section cmake_module_HTTPServer Сборка с использованием CMake
|
|
||||||
//!
|
|
||||||
//! \~\code
|
|
||||||
//! find_package(PIP REQUIRED)
|
|
||||||
//! target_link_libraries([target] PIP::HTTPServer)
|
|
||||||
//! \endcode
|
|
||||||
//!
|
|
||||||
//! \~english \par Common
|
|
||||||
//! \~russian \par Общее
|
|
||||||
//!
|
|
||||||
//! \~english
|
|
||||||
//! These files provides HTTP server based on libmicrohttpd
|
|
||||||
//!
|
|
||||||
//! \~russian
|
|
||||||
//! Эти файлы обеспечивают HTTP сервер, основанный на libmicrohttpd
|
|
||||||
//!
|
|
||||||
//! \~\authors
|
|
||||||
//! \~english
|
|
||||||
//! Ivan Pelipenko peri4ko@yandex.ru;
|
|
||||||
//! \~russian
|
|
||||||
//! Иван Пелипенко peri4ko@yandex.ru;
|
|
||||||
//!
|
|
||||||
|
|
||||||
#ifndef pihttpservermodule_H
|
#ifndef pihttpservermodule_H
|
||||||
#define pihttpservermodule_H
|
#define pihttpservermodule_H
|
||||||
|
|
||||||
|
//! \~\addtogroup HTTPServer
|
||||||
|
//! \~\{
|
||||||
|
//! \~\file pihttpservermodule.h
|
||||||
|
//! \~\brief HTTP server module includes
|
||||||
|
//! \~english HTTP server module includes
|
||||||
|
//! \~russian Модуль включений HTTP сервера
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This file provides includes for the HTTP server module
|
||||||
|
//! \~russian Этот файл предоставляет включения для модуля HTTP сервера
|
||||||
|
//! \~\}
|
||||||
|
|
||||||
#include "pihttpserver.h"
|
#include "pihttpserver.h"
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -1,3 +1,9 @@
|
|||||||
|
/*! \file piintrospection_base.h
|
||||||
|
* \ingroup Introspection
|
||||||
|
* \~\brief
|
||||||
|
* \~english Base declarations for the introspection subsystem
|
||||||
|
* \~russian Базовые объявления подсистемы интроспекции
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Introspection module - base macros and types
|
Introspection module - base macros and types
|
||||||
@@ -60,6 +66,22 @@ class PIPeer;
|
|||||||
class PIIntrospection;
|
class PIIntrospection;
|
||||||
class PIIntrospectionServer;
|
class PIIntrospectionServer;
|
||||||
|
|
||||||
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Declares singleton accessor `instance()` for an introspection interface class.
|
||||||
|
//! \~russian Объявляет метод-синглтон `instance()` для класса интерфейса интроспекции.
|
||||||
|
# define __PIINTROSPECTION_SINGLETON_H__(T)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Defines singleton accessor `instance()` for an introspection interface class.
|
||||||
|
//! \~russian Определяет метод-синглтон `instance()` для класса интерфейса интроспекции.
|
||||||
|
# define __PIINTROSPECTION_SINGLETON_CPP__(T)
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
#if defined(PIP_INTROSPECTION) && !defined(PIP_FORCE_NO_PIINTROSPECTION)
|
||||||
# define __PIINTROSPECTION_SINGLETON_H__(T) static PIIntrospection##T##Interface * instance();
|
# define __PIINTROSPECTION_SINGLETON_H__(T) static PIIntrospection##T##Interface * instance();
|
||||||
|
|
||||||
@@ -69,4 +91,6 @@ class PIIntrospectionServer;
|
|||||||
return &ret; \
|
return &ret; \
|
||||||
}
|
}
|
||||||
#endif // PIP_INTROSPECTION
|
#endif // PIP_INTROSPECTION
|
||||||
|
|
||||||
|
#endif // DOXYGEN
|
||||||
#endif // PIINTROSPECTION_BASE_H
|
#endif // PIINTROSPECTION_BASE_H
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
//! \~\file piintrospection_containers.h
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Container introspection helpers
|
||||||
|
//! \~russian Вспомогательные средства интроспекции контейнеров
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Introspection module - interface for containers
|
Introspection module - interface for containers
|
||||||
@@ -22,13 +27,37 @@
|
|||||||
|
|
||||||
#include "pibase.h"
|
#include "pibase.h"
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Metadata describing one tracked container element type.
|
||||||
|
//! \~russian Метаданные, описывающие один отслеживаемый тип элементов контейнера.
|
||||||
struct PIP_EXPORT PIIntrospectionContainersType {
|
struct PIP_EXPORT PIIntrospectionContainersType {
|
||||||
|
//! \~english Destroys the type descriptor.
|
||||||
|
//! \~russian Уничтожает дескриптор типа.
|
||||||
~PIIntrospectionContainersType();
|
~PIIntrospectionContainersType();
|
||||||
|
|
||||||
|
//! \~english Finalizes type information, including generated identifiers and names.
|
||||||
|
//! \~russian Завершает подготовку информации о типе, включая сгенерированные идентификаторы и имена.
|
||||||
void finish();
|
void finish();
|
||||||
|
|
||||||
|
//! \~english Stable identifier of the tracked type.
|
||||||
|
//! \~russian Стабильный идентификатор отслеживаемого типа.
|
||||||
uint id = 0;
|
uint id = 0;
|
||||||
|
|
||||||
|
//! \~english Compiler-provided type name.
|
||||||
|
//! \~russian Имя типа, предоставленное компилятором.
|
||||||
const char * name = nullptr;
|
const char * name = nullptr;
|
||||||
|
|
||||||
|
//! \~english Demangled type name when available.
|
||||||
|
//! \~russian Деманглированное имя типа, если доступно.
|
||||||
const char * demangled = "?";
|
const char * demangled = "?";
|
||||||
|
|
||||||
|
//! \~english True after \a finish() prepares the descriptor.
|
||||||
|
//! \~russian Истина после того, как \a finish() подготовит дескриптор.
|
||||||
bool inited = false;
|
bool inited = false;
|
||||||
|
|
||||||
|
//! \~english True when demangled name was resolved successfully.
|
||||||
|
//! \~russian Истина, если деманглированное имя успешно получено.
|
||||||
bool has_demangled = false;
|
bool has_demangled = false;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -38,9 +67,15 @@ struct PIP_EXPORT PIIntrospectionContainersType {
|
|||||||
|
|
||||||
class PIIntrospectionContainers;
|
class PIIntrospectionContainers;
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Lazily builds and caches type metadata for container introspection macros.
|
||||||
|
//! \~russian Лениво создает и кеширует метаданные типа для макросов интроспекции контейнеров.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
class PIIntrospectionContainersTypeInfo {
|
class PIIntrospectionContainersTypeInfo {
|
||||||
public:
|
public:
|
||||||
|
//! \~english Returns cached metadata for type `T`.
|
||||||
|
//! \~russian Возвращает кешированные метаданные для типа `T`.
|
||||||
static const PIIntrospectionContainersType & get() {
|
static const PIIntrospectionContainersType & get() {
|
||||||
static PIIntrospectionContainersType ret = create();
|
static PIIntrospectionContainersType ret = create();
|
||||||
return ret;
|
return ret;
|
||||||
@@ -57,6 +92,52 @@ private:
|
|||||||
|
|
||||||
# define PIINTROSPECTION_CONTAINERS (PIIntrospectionContainersInterface::instance())
|
# define PIINTROSPECTION_CONTAINERS (PIIntrospectionContainersInterface::instance())
|
||||||
|
|
||||||
|
# ifdef DOXYGEN
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Registers construction of a container storing elements of type `t`.
|
||||||
|
//! \~russian Регистрирует создание контейнера, хранящего элементы типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_NEW(t, isz)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Registers destruction of a container storing elements of type `t`.
|
||||||
|
//! \~russian Регистрирует уничтожение контейнера, хранящего элементы типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_DELETE(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Adds `cnt` allocated element slots for containers of type `t`.
|
||||||
|
//! \~russian Добавляет `cnt` выделенных слотов элементов для контейнеров типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Removes `cnt` allocated element slots for containers of type `t`.
|
||||||
|
//! \~russian Убирает `cnt` выделенных слотов элементов для контейнеров типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Adds `cnt` used element slots for containers of type `t`.
|
||||||
|
//! \~russian Добавляет `cnt` занятых слотов элементов для контейнеров типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_USED(t, cnt)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionContainersInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Removes `cnt` used element slots for containers of type `t`.
|
||||||
|
//! \~russian Убирает `cnt` занятых слотов элементов для контейнеров типа `t`.
|
||||||
|
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt)
|
||||||
|
|
||||||
|
# else
|
||||||
|
|
||||||
// clang-format off
|
// clang-format off
|
||||||
# define PIINTROSPECTION_CONTAINER_NEW(t, isz) PIINTROSPECTION_CONTAINERS->containerNew (PIIntrospectionContainersTypeInfo<t>::get(), isz);
|
# define PIINTROSPECTION_CONTAINER_NEW(t, isz) PIINTROSPECTION_CONTAINERS->containerNew (PIIntrospectionContainersTypeInfo<t>::get(), isz);
|
||||||
# define PIINTROSPECTION_CONTAINER_DELETE(t) PIINTROSPECTION_CONTAINERS->containerDelete(PIIntrospectionContainersTypeInfo<t>::get() );
|
# define PIINTROSPECTION_CONTAINER_DELETE(t) PIINTROSPECTION_CONTAINERS->containerDelete(PIIntrospectionContainersTypeInfo<t>::get() );
|
||||||
@@ -66,7 +147,13 @@ private:
|
|||||||
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUnused(PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUnused(PIIntrospectionContainersTypeInfo<t>::get(), cnt);
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
|
# endif
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Entry point for collecting container allocation and usage statistics.
|
||||||
|
//! \~russian Точка входа для сбора статистики выделения и использования контейнеров.
|
||||||
class PIP_EXPORT PIIntrospectionContainersInterface {
|
class PIP_EXPORT PIIntrospectionContainersInterface {
|
||||||
friend class PIIntrospection;
|
friend class PIIntrospection;
|
||||||
friend class PIIntrospectionServer;
|
friend class PIIntrospectionServer;
|
||||||
@@ -74,15 +161,32 @@ class PIP_EXPORT PIIntrospectionContainersInterface {
|
|||||||
public:
|
public:
|
||||||
__PIINTROSPECTION_SINGLETON_H__(Containers)
|
__PIINTROSPECTION_SINGLETON_H__(Containers)
|
||||||
|
|
||||||
// clang-format off
|
//! \~english Registers construction of a container instance with element size `isz`.
|
||||||
|
//! \~russian Регистрирует создание экземпляра контейнера с размером элемента `isz`.
|
||||||
void containerNew(const PIIntrospectionContainersType & ti, uint isz);
|
void containerNew(const PIIntrospectionContainersType & ti, uint isz);
|
||||||
void containerDelete(const PIIntrospectionContainersType & ti);
|
|
||||||
void containerAlloc (const PIIntrospectionContainersType & ti, ullong cnt);
|
|
||||||
void containerFree (const PIIntrospectionContainersType & ti, ullong cnt);
|
|
||||||
void containerUsed (const PIIntrospectionContainersType & ti, ullong cnt);
|
|
||||||
void containerUnused(const PIIntrospectionContainersType & ti, ullong cnt);
|
|
||||||
// clang-format on
|
|
||||||
|
|
||||||
|
//! \~english Registers destruction of a container instance.
|
||||||
|
//! \~russian Регистрирует уничтожение экземпляра контейнера.
|
||||||
|
void containerDelete(const PIIntrospectionContainersType & ti);
|
||||||
|
|
||||||
|
//! \~english Adds `cnt` allocated element slots for tracked type `ti`.
|
||||||
|
//! \~russian Добавляет `cnt` выделенных слотов элементов для отслеживаемого типа `ti`.
|
||||||
|
void containerAlloc(const PIIntrospectionContainersType & ti, ullong cnt);
|
||||||
|
|
||||||
|
//! \~english Removes `cnt` allocated element slots for tracked type `ti`.
|
||||||
|
//! \~russian Убирает `cnt` выделенных слотов элементов для отслеживаемого типа `ti`.
|
||||||
|
void containerFree(const PIIntrospectionContainersType & ti, ullong cnt);
|
||||||
|
|
||||||
|
//! \~english Adds `cnt` used element slots for tracked type `ti`.
|
||||||
|
//! \~russian Добавляет `cnt` занятых слотов элементов для отслеживаемого типа `ti`.
|
||||||
|
void containerUsed(const PIIntrospectionContainersType & ti, ullong cnt);
|
||||||
|
|
||||||
|
//! \~english Removes `cnt` used element slots for tracked type `ti`.
|
||||||
|
//! \~russian Убирает `cnt` занятых слотов элементов для отслеживаемого типа `ti`.
|
||||||
|
void containerUnused(const PIIntrospectionContainersType & ti, ullong cnt);
|
||||||
|
|
||||||
|
//! \~english Private implementation pointer with collected statistics.
|
||||||
|
//! \~russian Указатель на приватную реализацию с накопленной статистикой.
|
||||||
PIIntrospectionContainers * p;
|
PIIntrospectionContainers * p;
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piintrospection_server.h
|
//! \~\file piintrospection_server.h
|
||||||
* \ingroup Introspection
|
//! \~\ingroup Introspection
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Introspection server
|
//! \~english Introspection server
|
||||||
* \~russian Сервер интроспекции
|
//! \~russian Сервер интроспекции
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Introspection module
|
Introspection module
|
||||||
@@ -28,12 +27,16 @@
|
|||||||
|
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
//! \ingroup Introspection
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionServer
|
||||||
|
//! \~\brief
|
||||||
//! \~english Start introspection server with name "name"
|
//! \~english Start introspection server with name "name"
|
||||||
//! \~russian Запускает сервер интроспекции с именем "name"
|
//! \~russian Запускает сервер интроспекции с именем "name"
|
||||||
# define PIINTROSPECTION_START(name)
|
# define PIINTROSPECTION_START(name)
|
||||||
|
|
||||||
//! \ingroup Introspection
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionServer
|
||||||
|
//! \~\brief
|
||||||
//! \~english Stop introspection server
|
//! \~english Stop introspection server
|
||||||
//! \~russian Останавливает сервер интроспекции
|
//! \~russian Останавливает сервер интроспекции
|
||||||
# define PIINTROSPECTION_STOP
|
# define PIINTROSPECTION_STOP
|
||||||
@@ -51,13 +54,24 @@ class PISystemMonitor;
|
|||||||
# define PIINTROSPECTION_START(name) PIINTROSPECTION_SERVER->start(#name);
|
# define PIINTROSPECTION_START(name) PIINTROSPECTION_SERVER->start(#name);
|
||||||
# define PIINTROSPECTION_STOP PIINTROSPECTION_SERVER->stop();
|
# define PIINTROSPECTION_STOP PIINTROSPECTION_SERVER->stop();
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Peer-based server that replies to introspection requests for the current process.
|
||||||
|
//! \~russian Сервер на основе peer, отвечающий на запросы интроспекции для текущего процесса.
|
||||||
class PIP_EXPORT PIIntrospectionServer: public PIPeer {
|
class PIP_EXPORT PIIntrospectionServer: public PIPeer {
|
||||||
PIOBJECT_SUBCLASS(PIIntrospectionServer, PIPeer);
|
PIOBJECT_SUBCLASS(PIIntrospectionServer, PIPeer);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Returns singleton server instance.
|
||||||
|
//! \~russian Возвращает экземпляр сервера-синглтона.
|
||||||
static PIIntrospectionServer * instance();
|
static PIIntrospectionServer * instance();
|
||||||
|
|
||||||
|
//! \~english Starts the server and publishes it under name derived from `server_name`.
|
||||||
|
//! \~russian Запускает сервер и публикует его под именем, построенным от `server_name`.
|
||||||
void start(const PIString & server_name);
|
void start(const PIString & server_name);
|
||||||
|
|
||||||
|
//! \~english Stops the server and releases its system monitor when needed.
|
||||||
|
//! \~russian Останавливает сервер и при необходимости освобождает его системный монитор.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,3 +1,8 @@
|
|||||||
|
//! \~\file piintrospection_threads.h
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Thread introspection helpers
|
||||||
|
//! \~russian Вспомогательные средства интроспекции потоков
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Introspection module - interface for threads
|
Introspection module - interface for threads
|
||||||
@@ -28,6 +33,59 @@ class PIIntrospectionThreads;
|
|||||||
|
|
||||||
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
|
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
|
||||||
|
|
||||||
|
# ifdef DOXYGEN
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Registers creation of thread object `t`.
|
||||||
|
//! \~russian Регистрирует создание объекта потока `t`.
|
||||||
|
# define PIINTROSPECTION_THREAD_NEW(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Registers destruction of thread object `t`.
|
||||||
|
//! \~russian Регистрирует уничтожение объекта потока `t`.
|
||||||
|
# define PIINTROSPECTION_THREAD_DELETE(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Marks thread `t` as starting.
|
||||||
|
//! \~russian Помечает поток `t` как запускающийся.
|
||||||
|
# define PIINTROSPECTION_THREAD_START(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Marks thread `t` as running.
|
||||||
|
//! \~russian Помечает поток `t` как выполняющийся.
|
||||||
|
# define PIINTROSPECTION_THREAD_RUN(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Marks thread `t` as waiting.
|
||||||
|
//! \~russian Помечает поток `t` как ожидающий.
|
||||||
|
# define PIINTROSPECTION_THREAD_WAIT(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Marks thread `t` as stopped.
|
||||||
|
//! \~russian Помечает поток `t` как остановленный.
|
||||||
|
# define PIINTROSPECTION_THREAD_STOP(t)
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \relatesalso PIIntrospectionThreadsInterface
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Reports completed run of thread `t` that took `us` microseconds.
|
||||||
|
//! \~russian Сообщает о завершенном проходе потока `t`, занявшем `us` микросекунд.
|
||||||
|
# define PIINTROSPECTION_THREAD_RUN_DONE(t, us)
|
||||||
|
|
||||||
|
# else
|
||||||
|
|
||||||
# define PIINTROSPECTION_THREAD_NEW(t) PIINTROSPECTION_THREADS->threadNew(t);
|
# define PIINTROSPECTION_THREAD_NEW(t) PIINTROSPECTION_THREADS->threadNew(t);
|
||||||
# define PIINTROSPECTION_THREAD_DELETE(t) PIINTROSPECTION_THREADS->threadDelete(t);
|
# define PIINTROSPECTION_THREAD_DELETE(t) PIINTROSPECTION_THREADS->threadDelete(t);
|
||||||
# define PIINTROSPECTION_THREAD_START(t) PIINTROSPECTION_THREADS->threadStart(t);
|
# define PIINTROSPECTION_THREAD_START(t) PIINTROSPECTION_THREADS->threadStart(t);
|
||||||
@@ -36,21 +94,45 @@ class PIIntrospectionThreads;
|
|||||||
# define PIINTROSPECTION_THREAD_STOP(t) PIINTROSPECTION_THREADS->threadStop(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_RUN_DONE(t, us) PIINTROSPECTION_THREADS->threadRunDone(t, us);
|
||||||
|
|
||||||
|
# endif
|
||||||
|
|
||||||
|
//! \~\ingroup Introspection
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Entry point for collecting state and timing statistics of \a PIThread objects.
|
||||||
|
//! \~russian Точка входа для сбора статистики состояний и времени выполнения объектов \a PIThread.
|
||||||
class PIP_EXPORT PIIntrospectionThreadsInterface {
|
class PIP_EXPORT PIIntrospectionThreadsInterface {
|
||||||
friend class PIIntrospection;
|
friend class PIIntrospection;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
__PIINTROSPECTION_SINGLETON_H__(Threads)
|
__PIINTROSPECTION_SINGLETON_H__(Threads)
|
||||||
|
|
||||||
// clang-format off
|
//! \~english Registers creation of thread object `t`.
|
||||||
|
//! \~russian Регистрирует создание объекта потока `t`.
|
||||||
void threadNew(PIThread * t);
|
void threadNew(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Registers destruction of thread object `t`.
|
||||||
|
//! \~russian Регистрирует уничтожение объекта потока `t`.
|
||||||
void threadDelete(PIThread * t);
|
void threadDelete(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Updates statistics for thread `t` when it starts.
|
||||||
|
//! \~russian Обновляет статистику потока `t` при его запуске.
|
||||||
void threadStart(PIThread * t);
|
void threadStart(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Updates statistics for thread `t` when its run handler begins.
|
||||||
|
//! \~russian Обновляет статистику потока `t`, когда начинается его рабочий проход.
|
||||||
void threadRun(PIThread * t);
|
void threadRun(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Marks thread `t` as waiting for the next run.
|
||||||
|
//! \~russian Помечает поток `t` как ожидающий следующего прохода.
|
||||||
void threadWait(PIThread * t);
|
void threadWait(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Marks thread `t` as stopped.
|
||||||
|
//! \~russian Помечает поток `t` как остановленный.
|
||||||
void threadStop(PIThread * t);
|
void threadStop(PIThread * t);
|
||||||
|
|
||||||
|
//! \~english Updates averaged run time of thread `t` in microseconds.
|
||||||
|
//! \~russian Обновляет усредненное время выполнения потока `t` в микросекундах.
|
||||||
void threadRunDone(PIThread * t, ullong us);
|
void threadRunDone(PIThread * t, ullong us);
|
||||||
// clang-format on
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
PIIntrospectionThreadsInterface();
|
PIIntrospectionThreadsInterface();
|
||||||
|
|||||||
@@ -29,328 +29,843 @@
|
|||||||
#include "pichunkstream.h"
|
#include "pichunkstream.h"
|
||||||
#include "pifile.h"
|
#include "pifile.h"
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~english Class for writing and reading binary data to/from log files, with support for playback in different modes.
|
||||||
//! \~\brief
|
//! \~russian Класс для записи и чтения бинарных данных в/из файлов логов с поддержкой воспроизведения в различных режимах.
|
||||||
//! \~english Binary log
|
//! \~\details
|
||||||
//! \~russian Бинарный лог
|
//! \~english The PIBinaryLog class provides functionality to write binary data to log files and read/playback data from them. It supports
|
||||||
|
//! multiple play modes including real-time, variable speed, and static delay modes. The class also supports splitting log files by size,
|
||||||
|
//! time, or record count.
|
||||||
|
//! \~russian Класс PIBinaryLog предоставляет функциональность для записи бинарных данных в файлы логов и чтения/воспроизведения данных из.
|
||||||
|
//! них. Он поддерживает несколько режимов воспроизведения, включая режим реального времени, режим переменной скорости и режим статической
|
||||||
|
//! задержки. Класс также поддерживает разделение файлов логов по размеру, времени или количеству записей.
|
||||||
class PIP_EXPORT PIBinaryLog: public PIIODevice {
|
class PIP_EXPORT PIBinaryLog: public PIIODevice {
|
||||||
PIIODEVICE(PIBinaryLog, "binlog");
|
PIIODEVICE(PIBinaryLog, "binlog");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs %PIBinaryLog with default playback and split settings.
|
||||||
|
//! \~russian Создает %PIBinaryLog со стандартными настройками воспроизведения и разделения файлов.
|
||||||
explicit PIBinaryLog();
|
explicit PIBinaryLog();
|
||||||
|
|
||||||
|
//! \~english Stops background activity and closes the current log.
|
||||||
|
//! \~russian Останавливает фоновую активность и закрывает текущий лог.
|
||||||
virtual ~PIBinaryLog();
|
virtual ~PIBinaryLog();
|
||||||
|
|
||||||
//! \brief Play modes for \a PIBinaryLog
|
//! \~english Playback modes used by \a PIBinaryLog.
|
||||||
|
//! \~russian Режимы воспроизведения, используемые \a PIBinaryLog.
|
||||||
enum PlayMode {
|
enum PlayMode {
|
||||||
PlayRealTime /*! Play in system realtime, default mode */,
|
PlayRealTime /*! \~english Playback follows record timestamps in real time, default mode \~russian Воспроизведение следует временным
|
||||||
PlayVariableSpeed /*! Play in software realtime with speed, set by \a setSpeed */,
|
меткам записей в реальном времени, режим по умолчанию */
|
||||||
PlayStaticDelay /*! Play with custom static delay, ignoring timestamp */
|
,
|
||||||
|
PlayVariableSpeed /*! \~english Playback uses recorded timing scaled by \a setPlaySpeed() \~russian Воспроизведение использует
|
||||||
|
записанные интервалы времени, масштабированные через \a setPlaySpeed() */
|
||||||
|
,
|
||||||
|
PlayStaticDelay /*! \~english Playback uses fixed delay from \a setPlayDelay() and ignores record timestamps \~russian
|
||||||
|
Воспроизведение использует фиксированную задержку из \a setPlayDelay() и игнорирует временные метки записей */
|
||||||
|
,
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \brief Different split modes for writing \a PIBinaryLog, which can separate files by size, by time or by records count
|
//! \~english File splitting modes used while writing logs.
|
||||||
|
//! \~russian Режимы разделения файлов, используемые при записи логов.
|
||||||
enum SplitMode {
|
enum SplitMode {
|
||||||
SplitNone /*! Without separate, default mode */,
|
SplitNone /*! \~english Do not split files, default mode \~russian Не разделять файлы, режим по умолчанию */,
|
||||||
SplitTime /*! Separate files by record time */,
|
SplitTime /*! \~english Start a new file when elapsed record time exceeds configured limit \~russian Начинать новый файл, когда
|
||||||
SplitSize /*! Separate files by size */,
|
накопленное время записей превышает заданный предел */
|
||||||
SplitCount /*! Separate files by records count */
|
,
|
||||||
|
SplitSize /*! \~english Start a new file when file size exceeds configured limit \~russian Начинать новый файл, когда размер файла
|
||||||
|
превышает заданный предел */
|
||||||
|
,
|
||||||
|
SplitCount /*! \~english Start a new file when written record count exceeds configured limit \~russian Начинать новый файл, когда
|
||||||
|
количество записанных записей превышает заданный предел */
|
||||||
|
,
|
||||||
};
|
};
|
||||||
|
|
||||||
#pragma pack(push, 8)
|
#pragma pack(push, 8)
|
||||||
|
|
||||||
//! \brief Struct contains information about all records with same ID
|
//! \~english Statistics for records sharing the same record ID.
|
||||||
|
//! \~russian Статистика по записям с одинаковым идентификатором.
|
||||||
struct PIP_EXPORT BinLogRecordInfo {
|
struct PIP_EXPORT BinLogRecordInfo {
|
||||||
|
//! \~english Constructs zero-initialized statistics.
|
||||||
|
//! \~russian Создает статистику, инициализированную нулями.
|
||||||
BinLogRecordInfo() {
|
BinLogRecordInfo() {
|
||||||
id = count = 0;
|
id = count = 0;
|
||||||
minimum_size = maximum_size = 0;
|
minimum_size = maximum_size = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Unique identifier for this record type within the log file.
|
||||||
|
//! \~russian Уникальный идентификатор для этого типа записи в файле лога.
|
||||||
int id;
|
int id;
|
||||||
|
|
||||||
|
//! \~english Total number of records with this ID in the log file.
|
||||||
|
//! \~russian Общее количество записей с этим ID в файле лога.
|
||||||
int count;
|
int count;
|
||||||
|
|
||||||
|
//! \~english Size in bytes of the smallest record with this ID.
|
||||||
|
//! \~russian Размер в байтах самой маленькой записи с этим ID.
|
||||||
int minimum_size;
|
int minimum_size;
|
||||||
|
|
||||||
|
//! \~english Size in bytes of the largest record with this ID.
|
||||||
|
//! \~russian Размер в байтах самой большой записи с этим ID.
|
||||||
int maximum_size;
|
int maximum_size;
|
||||||
|
|
||||||
|
//! \~english Timestamp of the first record with this ID.
|
||||||
|
//! \~russian Метка времени первой записи с этим ID.
|
||||||
PISystemTime start_time;
|
PISystemTime start_time;
|
||||||
|
|
||||||
|
//! \~english Timestamp of the last record with this ID.
|
||||||
|
//! \~russian Временная метка последней записи с этим идентификатором.
|
||||||
PISystemTime end_time;
|
PISystemTime end_time;
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \brief Struct contains position, ID and timestamp of record in file
|
//! \~english Indexed location of a record inside a log file.
|
||||||
|
//! \~russian Индексированное положение записи внутри файла лога.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This structure provides direct access information for a single log record, including its position in the file, size, ID,
|
||||||
|
//! and timestamp.
|
||||||
|
//! \~russian Эта структура предоставляет информацию прямого доступа для одной записи лога, включая её позицию в файле, размер, ID и
|
||||||
|
//! метку времени.
|
||||||
struct PIP_EXPORT BinLogIndex {
|
struct PIP_EXPORT BinLogIndex {
|
||||||
|
//! \~english Record ID.
|
||||||
|
//! \~russian Идентификатор записи.
|
||||||
int id;
|
int id;
|
||||||
|
|
||||||
|
//! \~english Record payload size in bytes.
|
||||||
|
//! \~russian Размер данных записи в байтах.
|
||||||
int data_size;
|
int data_size;
|
||||||
|
|
||||||
|
//! \~english Byte position of the record header in the file.
|
||||||
|
//! \~russian Позиция заголовка записи в файле в байтах.
|
||||||
llong pos;
|
llong pos;
|
||||||
|
|
||||||
|
//! \~english Recorded timestamp.
|
||||||
|
//! \~russian Сохраненная временная метка.
|
||||||
PISystemTime timestamp;
|
PISystemTime timestamp;
|
||||||
};
|
};
|
||||||
|
|
||||||
#pragma pack(pop)
|
#pragma pack(pop)
|
||||||
|
|
||||||
//! \brief Struct contains full information about Binary Log file and about all Records using map of \a BinLogRecordInfo
|
//! \~english Summary information about a log file and its indexed record types.
|
||||||
|
//! \~russian Сводная информация о файле лога и его индексированных типах записей.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This structure provides comprehensive information about a binary log file, including file metadata, record statistics, and
|
||||||
|
//! user-defined header data.
|
||||||
|
//! \~russian Эта структура предоставляет исчерпывающую информацию о файле бинарного лога, включая метаданные файла, статистику записей
|
||||||
|
//! и пользовательские данные заголовка.
|
||||||
struct PIP_EXPORT BinLogInfo {
|
struct PIP_EXPORT BinLogInfo {
|
||||||
|
//! \~english Path to the analyzed log file.
|
||||||
|
//! \~russian Путь к анализируемому файлу лога.
|
||||||
PIString path;
|
PIString path;
|
||||||
|
|
||||||
|
//! \~english Total number of records in the file, or negative error code for invalid logs.
|
||||||
|
//! \~russian Общее количество записей в файле или отрицательный код ошибки для некорректных логов.
|
||||||
int records_count = 0;
|
int records_count = 0;
|
||||||
|
|
||||||
|
//! \~english File size in bytes.
|
||||||
|
//! \~russian Размер файла в байтах.
|
||||||
llong log_size = 0L;
|
llong log_size = 0L;
|
||||||
|
|
||||||
|
//! \~english Timestamp of the first record.
|
||||||
|
//! \~russian Временная метка первой записи.
|
||||||
PISystemTime start_time;
|
PISystemTime start_time;
|
||||||
|
|
||||||
|
//! \~english Timestamp of the last record.
|
||||||
|
//! \~russian Временная метка последней записи.
|
||||||
PISystemTime end_time;
|
PISystemTime end_time;
|
||||||
|
|
||||||
|
//! \~english Per-ID record statistics.
|
||||||
|
//! \~russian Статистика записей по идентификаторам.
|
||||||
PIMap<int, BinLogRecordInfo> records;
|
PIMap<int, BinLogRecordInfo> records;
|
||||||
|
|
||||||
|
//! \~english Custom user header stored in the file header.
|
||||||
|
//! \~russian Пользовательский заголовок, сохраненный в заголовке файла.
|
||||||
PIByteArray user_header;
|
PIByteArray user_header;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! Current \a PlayMode
|
//! \~english Returns current \a PlayMode.
|
||||||
|
//! \~russian Возвращает текущий \a PlayMode.
|
||||||
PlayMode playMode() const { return play_mode; }
|
PlayMode playMode() const { return play_mode; }
|
||||||
|
|
||||||
//! Current \a SplitMode
|
//! \~english Returns current \a SplitMode.
|
||||||
|
//! \~russian Возвращает текущий \a SplitMode.
|
||||||
SplitMode splitMode() const { return split_mode; }
|
SplitMode splitMode() const { return split_mode; }
|
||||||
|
|
||||||
//! Current directory where billogs wiil be saved
|
//! \~english Returns directory used for new log files.
|
||||||
|
//! \~russian Возвращает каталог, используемый для новых файлов лога.
|
||||||
PIString logDir() const { return property("logDir").toString(); }
|
PIString logDir() const { return property("logDir").toString(); }
|
||||||
|
|
||||||
//! Returns current file prefix
|
//! \~english Returns filename prefix used for new log files.
|
||||||
|
//! \~russian Возвращает префикс имени файла, используемый для новых файлов лога.
|
||||||
PIString filePrefix() const { return property("filePrefix").toString(); }
|
PIString filePrefix() const { return property("filePrefix").toString(); }
|
||||||
|
|
||||||
//! Default ID, used in \a write function
|
//! \~english Returns default record ID used by \a write().
|
||||||
|
//! \~russian Возвращает идентификатор записи по умолчанию, используемый \a write().
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The default record ID used when writing without explicitly specifying an ID.
|
||||||
|
//! \~russian ID записи по умолчанию, используемый при записи без явного указания ID.
|
||||||
int defaultID() const { return default_id; }
|
int defaultID() const { return default_id; }
|
||||||
|
|
||||||
//! Returns current play speed
|
//! \~english Returns current playback speed multiplier.
|
||||||
|
//! \~russian Возвращает текущий множитель скорости воспроизведения.
|
||||||
double playSpeed() const { return play_speed > 0 ? 1. / play_speed : 0.; }
|
double playSpeed() const { return play_speed > 0 ? 1. / play_speed : 0.; }
|
||||||
|
|
||||||
//! Returns current play delay
|
//! \~english Returns static delay used in \a PlayStaticDelay mode.
|
||||||
|
//! \~russian Возвращает фиксированную задержку, используемую в режиме \a PlayStaticDelay.
|
||||||
PISystemTime playDelay() const { return play_delay; }
|
PISystemTime playDelay() const { return play_delay; }
|
||||||
|
|
||||||
//! Returns current binlog file split time
|
//! \~english Returns elapsed-time threshold for \a SplitTime mode.
|
||||||
|
//! \~russian Возвращает порог накопленного времени для режима \a SplitTime.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The time interval used for splitting log files in SplitTime mode.
|
||||||
|
//! \~russian Временной интервал, используемый для разделения файлов логов в режиме SplitTime.
|
||||||
PISystemTime splitTime() const { return split_time; }
|
PISystemTime splitTime() const { return split_time; }
|
||||||
|
|
||||||
//! Returns current binlog file split size
|
//! \~english Returns size threshold for \a SplitSize mode.
|
||||||
|
//! \~russian Возвращает порог размера для режима \a SplitSize.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The maximum file size in bytes for splitting log files in SplitSize mode.
|
||||||
|
//! \~russian Максимальный размер файла в байтах для разделения файлов логов в режиме SplitSize.
|
||||||
llong splitFileSize() const { return split_size; }
|
llong splitFileSize() const { return split_size; }
|
||||||
|
|
||||||
//! Returns current binlog file split records count
|
//! \~english Returns record-count threshold for \a SplitCount mode.
|
||||||
|
//! \~russian Возвращает порог количества записей для режима \a SplitCount.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The maximum number of records per file for splitting log files in SplitCount mode.
|
||||||
|
//! \~russian Максимальное количество записей на файл для разделения файлов логов в режиме SplitCount.
|
||||||
int splitRecordCount() const { return split_count; }
|
int splitRecordCount() const { return split_count; }
|
||||||
|
|
||||||
//! Returns if rapid start enabled
|
//! \~english Returns whether the first threaded-read record is emitted without initial delay.
|
||||||
|
//! \~russian Возвращает, выдается ли первая запись потокового чтения без начальной задержки.
|
||||||
bool rapidStart() const { return rapid_start; }
|
bool rapidStart() const { return rapid_start; }
|
||||||
|
|
||||||
//! Returns if index creates while writing
|
//! \~english Returns whether index data is collected while writing.
|
||||||
|
//! \~russian Возвращает, собираются ли данные индекса во время записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if index is created on-the-fly during writing, false otherwise.
|
||||||
|
//! \~russian true, если индекс создается "на лету" во время записи, иначе false.
|
||||||
bool createIndexOnFly() const { return create_index_on_fly; }
|
bool createIndexOnFly() const { return create_index_on_fly; }
|
||||||
|
|
||||||
//! Create binlog file with Filename = path
|
//! \~english Creates or reopens a log file at exact path "path" for writing.
|
||||||
|
//! \~russian Создает или повторно открывает файл лога по точному пути "path" для записи.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Creates a new binary log file at the specified path. If a file already exists, it will be overwritten.
|
||||||
|
//! \~russian Создает новый файл бинарного лога по указанному пути. Если файл уже существует, он будет перезаписан.
|
||||||
void createNewFile(const PIString & path);
|
void createNewFile(const PIString & path);
|
||||||
|
|
||||||
//! Set \a PlayMode
|
//! \~english Sets current \a PlayMode.
|
||||||
|
//! \~russian Устанавливает текущий \a PlayMode.
|
||||||
void setPlayMode(PlayMode mode) { setProperty("playMode", (int)mode); }
|
void setPlayMode(PlayMode mode) { setProperty("playMode", (int)mode); }
|
||||||
|
|
||||||
//! Set \a SplitMode
|
//! \~english Sets current \a SplitMode.
|
||||||
|
//! \~russian Устанавливает текущий \a SplitMode.
|
||||||
void setSplitMode(SplitMode mode) { setProperty("splitMode", (int)mode); }
|
void setSplitMode(SplitMode mode) { setProperty("splitMode", (int)mode); }
|
||||||
|
|
||||||
//! Set path to directory where binlogs will be saved
|
//! \~english Sets directory used for newly created log files.
|
||||||
|
//! \~russian Устанавливает каталог, используемый для вновь создаваемых файлов лога.
|
||||||
void setLogDir(const PIString & path) { setProperty("logDir", path); }
|
void setLogDir(const PIString & path) { setProperty("logDir", path); }
|
||||||
|
|
||||||
//! Set file prefix, used to
|
//! \~english Sets filename prefix used for newly created log files.
|
||||||
|
//! \~russian Устанавливает префикс имени файла для вновь создаваемых файлов лога.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the filename prefix used when generating log file names. Combined with the log directory and timestamp to create
|
||||||
|
//! unique filenames.
|
||||||
|
//! \~russian Устанавливает префикс имени файла, используемый при генерации имен файлов логов. Объединяется с каталогом логов и
|
||||||
|
//! временной меткой для создания уникальных имен файлов.
|
||||||
|
//! \~\param prefix
|
||||||
|
//! \~english The filename prefix.
|
||||||
|
//! \~russian Префикс имени файла.
|
||||||
void setFilePrefix(const PIString & prefix) { setProperty("filePrefix", prefix); }
|
void setFilePrefix(const PIString & prefix) { setProperty("filePrefix", prefix); }
|
||||||
|
|
||||||
//! Set defaultID, used in \a write function
|
//! \~english Sets default record ID used by \a write().
|
||||||
|
//! \~russian Устанавливает идентификатор записи по умолчанию, используемый \a write().
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the default record ID used when calling write without specifying an ID.
|
||||||
|
//! \~russian Устанавливает ID записи по умолчанию, используемый при вызове write без указания ID.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The default record ID. Must be greater than 0.
|
||||||
|
//! \~russian ID записи по умолчанию. Должен быть больше 0.
|
||||||
void setDefaultID(int id) { setProperty("defaultID", id); }
|
void setDefaultID(int id) { setProperty("defaultID", id); }
|
||||||
|
|
||||||
//! If enabled BinLog \a ThreadedRead starts without delay for first record, i.e. first record will be readed immediately
|
//! \~english Enables immediate delivery of the first record in threaded playback.
|
||||||
|
//! \~russian Включает немедленную выдачу первой записи при потоковом воспроизведении.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english When enabled, the first record is read immediately at the start of playback without waiting for its timestamp. This
|
||||||
|
//! reduces initial latency.
|
||||||
|
//! \~russian При включении первая запись читается немедленно при запуске воспроизведения без ожидания её метки времени. Это уменьшает
|
||||||
|
//! начальную задержку.
|
||||||
|
//! \~\param enabled
|
||||||
|
//! \~english true to enable rapid start, false to disable.
|
||||||
|
//! \~russian true для включения быстрого старта, false для отключения.
|
||||||
void setRapidStart(bool enabled) { setProperty("rapidStart", enabled); }
|
void setRapidStart(bool enabled) { setProperty("rapidStart", enabled); }
|
||||||
|
|
||||||
//! Set index creation while writing
|
//! \~english Enables or disables index collection while writing.
|
||||||
|
//! \~russian Включает или выключает сбор индекса во время записи.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Enables or disables automatic index creation during the writing process. When enabled, the index is built incrementally as
|
||||||
|
//! data is written.
|
||||||
|
//! \~russian Включает или отключает автоматическое создание индекса в процессе записи. При включении индекс строится по мере записи
|
||||||
|
//! данных.
|
||||||
|
//! \~\param yes
|
||||||
|
//! \~english true to enable on-the-fly index creation, false to disable.
|
||||||
|
//! \~russian true для включения создания индекса "на лету", false для отключения.
|
||||||
void setCreateIndexOnFly(bool yes);
|
void setCreateIndexOnFly(bool yes);
|
||||||
|
|
||||||
//! Set play speed to "speed", default value is 1.0x
|
//! \~english Sets playback speed multiplier and switches mode to \a PlayVariableSpeed.
|
||||||
//! Also this function set \a playMode to \a PlayVariableSpeed
|
//! \~russian Устанавливает множитель скорости воспроизведения и переключает режим в \a PlayVariableSpeed.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the playback speed multiplier. A value of 1.0 means real-time playback. Values greater than 1.0 speed up playback,
|
||||||
|
//! while values between 0 and 1.0 slow it down.
|
||||||
|
//! \~russian Устанавливает множитель скорости воспроизведения. Значение 1.0 означает воспроизведение в реальном времени. Значения
|
||||||
|
//! больше 1.0 ускоряют воспроизведение, а значения между 0 и 1.0 замедляют его.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This function automatically sets the play mode to \a PlayVariableSpeed.
|
||||||
|
//! \~russian Эта функция автоматически устанавливает режим воспроизведения в \a PlayVariableSpeed.
|
||||||
|
//! \~\param speed
|
||||||
|
//! \~english The playback speed multiplier.
|
||||||
|
//! \~russian Множитель скорости воспроизведения.
|
||||||
void setPlaySpeed(double speed) {
|
void setPlaySpeed(double speed) {
|
||||||
setPlayMode(PlayVariableSpeed);
|
setPlayMode(PlayVariableSpeed);
|
||||||
setProperty("playSpeed", speed);
|
setProperty("playSpeed", speed);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Setting static delay between records, default value is 1 sec
|
//! \~english Sets fixed delay between records and switches mode to \a PlayStaticDelay.
|
||||||
//! Also this function set \a playMode to \a PlayStaticDelay
|
//! \~russian Устанавливает фиксированную задержку между записями и переключает режим в \a PlayStaticDelay.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets a fixed delay between records during playback, ignoring the original timestamps in the log file.
|
||||||
|
//! \~russian Устанавливает фиксированную задержку между записями во время воспроизведения, игнорируя исходные метки времени в файле
|
||||||
|
//! лога.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This function automatically sets the play mode to \a PlayStaticDelay.
|
||||||
|
//! \~russian Эта функция автоматически устанавливает режим воспроизведения в \a PlayStaticDelay.
|
||||||
|
//! \~\param delay
|
||||||
|
//! \~english The static delay between records.
|
||||||
|
//! \~russian Статическая задержка между записями.
|
||||||
void setPlayDelay(const PISystemTime & delay) {
|
void setPlayDelay(const PISystemTime & delay) {
|
||||||
setPlayMode(PlayStaticDelay);
|
setPlayMode(PlayStaticDelay);
|
||||||
setProperty("playDelay", delay);
|
setProperty("playDelay", delay);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set \a playMode to \a PlayRealTime
|
//! \~english Switches playback to \a PlayRealTime.
|
||||||
|
//! \~russian Переключает воспроизведение в режим \a PlayRealTime.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the playback mode to real-time, where records are played at their original timestamps.
|
||||||
|
//! \~russian Устанавливает режим воспроизведения в реальное время, где записи воспроизводятся по их исходным меткам времени.
|
||||||
void setPlayRealTime() { setPlayMode(PlayRealTime); }
|
void setPlayRealTime() { setPlayMode(PlayRealTime); }
|
||||||
|
|
||||||
//! Set binlog file split time
|
//! \~english Sets time threshold for file splitting and switches mode to \a SplitTime.
|
||||||
//! Also this function set \a splitMode to \a SplitTime
|
//! \~russian Устанавливает порог времени для разделения файлов и переключает режим в \a SplitTime.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the time interval for splitting log files. When the time difference between records exceeds this value, a new file is
|
||||||
|
//! created.
|
||||||
|
//! \~russian Устанавливает временной интервал для разделения файлов логов. Когда разница во времени между записями превышает это
|
||||||
|
//! значение, создается новый файл.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This function automatically sets the split mode to \a SplitTime.
|
||||||
|
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitTime.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english The time interval for splitting files.
|
||||||
|
//! \~russian Временной интервал для разделения файлов.
|
||||||
void setSplitTime(const PISystemTime & time) {
|
void setSplitTime(const PISystemTime & time) {
|
||||||
setSplitMode(SplitTime);
|
setSplitMode(SplitTime);
|
||||||
setProperty("splitTime", time);
|
setProperty("splitTime", time);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set binlog file split size
|
//! \~english Sets size threshold for file splitting and switches mode to \a SplitSize.
|
||||||
//! Also this function set \a splitMode to \a SplitSize
|
//! \~russian Устанавливает порог размера для разделения файлов и переключает режим в \a SplitSize.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the maximum file size in bytes for splitting log files. When a file reaches this size, a new file is created.
|
||||||
|
//! \~russian Устанавливает максимальный размер файла в байтах для разделения файлов логов. Когда файл достигает этого размера,
|
||||||
|
//! создается новый файл.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This function automatically sets the split mode to \a SplitSize.
|
||||||
|
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitSize.
|
||||||
|
//! \~\param size
|
||||||
|
//! \~english The maximum file size in bytes.
|
||||||
|
//! \~russian Максимальный размер файла в байтах.
|
||||||
void setSplitFileSize(llong size) {
|
void setSplitFileSize(llong size) {
|
||||||
setSplitMode(SplitSize);
|
setSplitMode(SplitSize);
|
||||||
setProperty("splitFileSize", size);
|
setProperty("splitFileSize", size);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set binlog file split records count
|
//! \~english Sets record-count threshold for file splitting and switches mode to \a SplitCount.
|
||||||
//! Also this function set \a splitMode to \a SplitCount
|
//! \~russian Устанавливает порог количества записей для разделения файлов и переключает режим в \a SplitCount.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the maximum number of records per file for splitting log files. When a file reaches this record count, a new file is
|
||||||
|
//! created.
|
||||||
|
//! \~russian Устанавливает максимальное количество записей на файл для разделения файлов логов. Когда файл достигает этого количества
|
||||||
|
//! записей, создается новый файл.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This function automatically sets the split mode to \a SplitCount.
|
||||||
|
//! \~russian Эта функция автоматически устанавливает режим разделения в \a SplitCount.
|
||||||
|
//! \~\param count
|
||||||
|
//! \~english The maximum number of records per file.
|
||||||
|
//! \~russian Максимальное количество записей на файл.
|
||||||
void setSplitRecordCount(int count) {
|
void setSplitRecordCount(int count) {
|
||||||
setSplitMode(SplitCount);
|
setSplitMode(SplitCount);
|
||||||
setProperty("splitRecordCount", count);
|
setProperty("splitRecordCount", count);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set pause while playing via \a threadedRead or writing via write
|
//! \~english Pauses or resumes threaded playback and direct writes.
|
||||||
|
//! \~russian Ставит на паузу или возобновляет потоковое воспроизведение и прямую запись.
|
||||||
void setPause(bool pause);
|
void setPause(bool pause);
|
||||||
|
|
||||||
//! Set function wich returns new binlog file path when using split mode.
|
//! \~english Sets custom path generator used for split files and implicit file creation.
|
||||||
//! Overrides internal file path generator (logdir() + prefix() + current_time()).
|
//! \~russian Устанавливает пользовательский генератор путей, используемый для разделяемых файлов и неявного создания файла.
|
||||||
//! To restore internal file path generator set this function to "nullptr".
|
//! \~\details
|
||||||
|
//! \~english Sets a custom callback function that returns the path for the next log file when using split mode. This overrides the
|
||||||
|
//! internal path generator (logdir() + prefix() + current_time()). To restore the internal generator, set this function to nullptr.
|
||||||
|
//! \~russian Устанавливает пользовательскую функцию обратного вызова, возвращающую путь к следующему файлу лога при использовании
|
||||||
|
//! режима разделения. Это переопределяет внутренний генератор путей (logdir() + prefix() + current_time()). Для восстановления
|
||||||
|
//! внутреннего генератора установите эту функцию в nullptr.
|
||||||
|
//! \~\param f
|
||||||
|
//! \~english The callback function returning the next file path, or nullptr to use the internal generator.
|
||||||
|
//! \~russian Функция обратного вызова, возвращающая путь к следующему файлу, или nullptr для использования внутреннего генератора.
|
||||||
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = f; }
|
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = f; }
|
||||||
|
|
||||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
//! \~english Writes one record with explicit ID and payload.
|
||||||
|
//! \~russian Записывает одну запись с явным идентификатором и данными.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes a single record to the binary log file with the specified ID and data.
|
||||||
|
//! \~russian Записывает одну запись в файл бинарного лога с указанным ID и данными.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The record ID. Must be greater than 0.
|
||||||
|
//! \~russian ID записи. Должен быть больше 0.
|
||||||
|
//! \~\param data
|
||||||
|
//! \~english The data to write.
|
||||||
|
//! \~russian Данные для записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Data size on success, negative value on error.
|
||||||
|
//! \~russian Размер данных data в случае успеха, отрицательное значение в случае ошибки.
|
||||||
int writeBinLog(int id, PIByteArray data) { return writeBinLog(id, data.data(), data.size_s()); }
|
int writeBinLog(int id, PIByteArray data) { return writeBinLog(id, data.data(), data.size_s()); }
|
||||||
|
|
||||||
//! Write one record to BinLog file, with ID = id, id must be greather than 0
|
//! \~english Writes one record with explicit ID and payload buffer.
|
||||||
|
//! \~russian Записывает одну запись с явным идентификатором и буфером данных.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Returns written payload size, \c 0 while paused, or negative value on error. ID must be greater than zero.
|
||||||
|
//! \~russian Возвращает размер записанных данных, \c 0 во время паузы или отрицательное значение при ошибке. Идентификатор должен быть
|
||||||
|
//! больше нуля.
|
||||||
int writeBinLog(int id, const void * data, int size);
|
int writeBinLog(int id, const void * data, int size);
|
||||||
|
|
||||||
//! Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
//! \~english Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||||
|
//! \~russian Записать один НЕОБРАБОТАННЫЙ (RAW) запись в файл BinLog, с ID = id, Метка времени = time
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes a single record with an explicit timestamp to the binary log file. The timestamp is stored as-is, without
|
||||||
|
//! modification.
|
||||||
|
//! \~russian Записывает одну запись с явной меткой времени в файл бинарного лога. Метка времени сохраняется как есть, без модификации.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The record ID. Must be greater than 0.
|
||||||
|
//! \~russian ID записи. Должен быть больше 0.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english The timestamp to associate with this record.
|
||||||
|
//! \~russian Метка времени, связанная с этой записью.
|
||||||
|
//! \~\param data
|
||||||
|
//! \~english The data to write.
|
||||||
|
//! \~russian Данные для записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english 0 on success, negative value on error.
|
||||||
|
//! \~russian 0 в случае успеха, отрицательное значение в случае ошибки.
|
||||||
int writeBinLog_raw(int id, const PISystemTime & time, const PIByteArray & data) {
|
int writeBinLog_raw(int id, const PISystemTime & time, const PIByteArray & data) {
|
||||||
return writeBinLog_raw(id, time, data.data(), data.size_s());
|
return writeBinLog_raw(id, time, data.data(), data.size_s());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Write one RAW record to BinLog file, with ID = id, Timestamp = time
|
||||||
|
//! \~russian Записать один НЕОБРАБОТАННЫЙ (RAW) запись в файл BinLog, с ID = id, Метка времени = time
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes a single record with an explicit timestamp to the binary log file. The timestamp is stored as-is, without
|
||||||
|
//! modification.
|
||||||
|
//! \~russian Записывает одну запись с явной меткой времени в файл бинарного лога. Метка времени сохраняется как есть, без модификации.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The record ID. Must be greater than 0.
|
||||||
|
//! \~russian ID записи. Должен быть больше 0.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english The timestamp to associate with this record.
|
||||||
|
//! \~russian Метка времени, связанная с этой записью.
|
||||||
|
//! \~\param data
|
||||||
|
//! \~english Pointer to the data to write.
|
||||||
|
//! \~russian Указатель на данные для записи.
|
||||||
|
//! \~\param size
|
||||||
|
//! \~english Size of the data in bytes.
|
||||||
|
//! \~russian Размер данных в байтах.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english 0 on success, negative value on error.
|
||||||
|
//! \~russian 0 в случае успеха, отрицательное значение в случае ошибки.
|
||||||
int writeBinLog_raw(int id, const PISystemTime & time, const void * data, int size);
|
int writeBinLog_raw(int id, const PISystemTime & time, const void * data, int size);
|
||||||
|
|
||||||
//! Returns count of writed records
|
//! \~english Returns number of records successfully written in current session.
|
||||||
|
//! \~russian Возвращает количество записей, успешно записанных в текущей сессии.
|
||||||
int writeCount() const { return write_count; }
|
int writeCount() const { return write_count; }
|
||||||
|
|
||||||
//! Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
//! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||||
|
//! \~russian Прочитать одну запись из файла BinLog, с ID = id, если id = 0, то будет прочитана любая запись
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Reads a single record from the binary log file. If id is 0, records of any ID can be read. Returns the record data as a
|
||||||
|
//! byte array.
|
||||||
|
//! \~russian Читает одну запись из файла бинарного лога. Если id равен 0, могут быть прочитаны записи любого ID. Возвращает данные
|
||||||
|
//! записи как массив байт.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The record ID to read, or 0 to read any record.
|
||||||
|
//! \~russian ID записи для чтения, или 0 для чтения любой записи.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english Optional pointer to store the record's timestamp.
|
||||||
|
//! \~russian Необязательный указатель для сохранения метки времени записи.
|
||||||
|
//! \~\param readed_id
|
||||||
|
//! \~english Optional pointer to store the record's ID.
|
||||||
|
//! \~russian Необязательный указатель для сохранения ID записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The record data as a byte array.
|
||||||
|
//! \~russian Данные записи как массив байт.
|
||||||
PIByteArray readBinLog(int id = 0, PISystemTime * time = 0, int * readed_id = 0);
|
PIByteArray readBinLog(int id = 0, PISystemTime * time = 0, int * readed_id = 0);
|
||||||
|
|
||||||
//! Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
//! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
|
||||||
|
//! \~russian Прочитать одну запись из файла BinLog, с ID = id, если id = 0 чем любая запись будет прочитана
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Reads a single record from the binary log file into a user-provided buffer. If id is 0, records of any ID can be read.
|
||||||
|
//! \~russian Читает одну запись из файла бинарного лога в пользовательский буфер. Если id равен 0, могут быть прочитаны записи любого
|
||||||
|
//! ID.
|
||||||
|
//! \~\param id
|
||||||
|
//! \~english The record ID to read, or 0 to read any record.
|
||||||
|
//! \~russian ID записи для чтения, или 0 для чтения любой записи.
|
||||||
|
//! \~\param read_to
|
||||||
|
//! \~english Pointer to the buffer where the record data will be stored.
|
||||||
|
//! \~russian Указатель на буфер, куда будут сохранены данные записи.
|
||||||
|
//! \~\param max_size
|
||||||
|
//! \~english Maximum size of the buffer in bytes.
|
||||||
|
//! \~russian Максимальный размер буфера в байтах.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english Optional pointer to store the record's timestamp.
|
||||||
|
//! \~russian Необязательный указатель для сохранения метки времени записи.
|
||||||
|
//! \~\param readed_id
|
||||||
|
//! \~english Optional pointer to store the record's ID.
|
||||||
|
//! \~russian Необязательный указатель для сохранения ID записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The actual number of bytes read, or negative value on error.
|
||||||
|
//! \~russian Фактическое количество прочитанных байт, или отрицательное значение в случае ошибки.
|
||||||
int readBinLog(int id, void * read_to, int max_size, PISystemTime * time = 0, int * readed_id = 0);
|
int readBinLog(int id, void * read_to, int max_size, PISystemTime * time = 0, int * readed_id = 0);
|
||||||
|
|
||||||
//! Returns binary log file size
|
//! \~english Returns current log file size in bytes.
|
||||||
|
//! \~russian Возвращает текущий размер файла лога в байтах.
|
||||||
llong logSize() const { return log_size; }
|
llong logSize() const { return log_size; }
|
||||||
|
|
||||||
//! Return position in current binlog file
|
//! \~english Returns current byte position in the opened log file.
|
||||||
|
//! \~russian Возвращает текущую позицию в байтах в открытом файле лога.
|
||||||
llong logPos() const { return file.pos(); }
|
llong logPos() const { return file.pos(); }
|
||||||
|
|
||||||
//! Return true, if position at the end of BinLog file
|
//! \~english Returns \b true when reading position is at end of file or the log is closed.
|
||||||
|
//! \~russian Возвращает \b true, когда позиция чтения находится в конце файла или лог закрыт.
|
||||||
bool isEnd() const {
|
bool isEnd() const {
|
||||||
if (isClosed()) return true;
|
if (isClosed()) return true;
|
||||||
return file.isEnd();
|
return file.isEnd();
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns if BinLog file is empty
|
//! \~english Returns whether the log contains no records beyond the file header.
|
||||||
|
//! \~russian Возвращает, не содержит ли лог записей сверх заголовка файла.
|
||||||
bool isEmpty() const;
|
bool isEmpty() const;
|
||||||
|
|
||||||
//! Returns BinLog pause status
|
//! \~english Returns current pause state.
|
||||||
|
//! \~russian Возвращает текущее состояние паузы.
|
||||||
bool isPause() const { return is_pause; }
|
bool isPause() const { return is_pause; }
|
||||||
|
|
||||||
//! Returns id of last readed record
|
//! \~english Returns ID of the last record read from the file.
|
||||||
|
//! \~russian Возвращает идентификатор последней записи, прочитанной из файла.
|
||||||
int lastReadedID() const { return lastrecord.id; }
|
int lastReadedID() const { return lastrecord.id; }
|
||||||
|
|
||||||
//! Returns timestamp of last readed record
|
//! \~english Returns timestamp of the last record read from the file.
|
||||||
|
//! \~russian Возвращает временную метку последней записи, прочитанной из файла.
|
||||||
PISystemTime lastReadedTimestamp() const { return lastrecord.timestamp; }
|
PISystemTime lastReadedTimestamp() const { return lastrecord.timestamp; }
|
||||||
|
|
||||||
//! Returns timestamp of log start
|
//! \~english Returns session start timestamp used for playback timing.
|
||||||
|
//! \~russian Возвращает временную метку начала сессии, используемую для тайминга воспроизведения.
|
||||||
PISystemTime logStartTimestamp() const { return startlogtime; }
|
PISystemTime logStartTimestamp() const { return startlogtime; }
|
||||||
|
|
||||||
//! Set custom file header, you can get it back when read this binlog
|
//! \~english Sets custom file header for subsequently created log files.
|
||||||
|
//! \~russian Устанавливает пользовательский заголовок файла для последовательно создаваемых логов.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets custom header data that will be written to the log file and can be retrieved later using getHeader().
|
||||||
|
//! \~russian Устанавливает пользовательские данные заголовка, которые будут записаны в файл лога и могут быть получены позже с помощью
|
||||||
|
//! getHeader().
|
||||||
|
//! \~\param header
|
||||||
|
//! \~english The custom header data to write.
|
||||||
|
//! \~russian Пользовательские данные заголовка для записи.
|
||||||
void setHeader(const PIByteArray & header);
|
void setHeader(const PIByteArray & header);
|
||||||
|
|
||||||
//! Get custom file header
|
//! \~english Returns custom header stored in the currently opened log.
|
||||||
|
//! \~russian Возвращает пользовательский заголовок, сохраненный в текущем открытом логе.
|
||||||
PIByteArray getHeader() const;
|
PIByteArray getHeader() const;
|
||||||
|
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
//! Read one message from binlog file, with ID contains in "filterID" or any ID, if "filterID" is empty
|
//! \~english Reads one message using \a filterID when it is not empty.
|
||||||
|
//! \~russian Читает одно сообщение, используя \a filterID, если он не пуст.
|
||||||
int read(void * read_to, int max_size);
|
int read(void * read_to, int max_size);
|
||||||
|
|
||||||
//! Write one record to BinLog file, with ID = "defaultID"
|
//! \~english Writes one record using \a defaultID().
|
||||||
|
//! \~russian Записывает одну запись, используя \a defaultID().
|
||||||
int write(const void * data, int size);
|
int write(const void * data, int size);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
//! Array of ID, that BinLog can read from binlog file, when use \a read function, or in \a ThreadedRead
|
//! \~english Optional list of record IDs accepted by \a read() and threaded playback.
|
||||||
|
//! \~russian Необязательный список идентификаторов записей, допустимых для \a read() и потокового воспроизведения.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english A list of record IDs to filter when reading. Only records with these IDs will be read. Empty list means all IDs are read.
|
||||||
|
//! \~russian Список ID записей для фильтрации при чтении. Будут прочитаны только записи с этими ID. Пустой список означает чтение всех
|
||||||
|
//! ID.
|
||||||
PIVector<int> filterID;
|
PIVector<int> filterID;
|
||||||
|
|
||||||
//! Go to begin of BinLog file
|
//! \~english Restarts reading and playback from the beginning of the current log.
|
||||||
|
//! \~russian Перезапускает чтение и воспроизведение с начала текущего лога.
|
||||||
void restart();
|
void restart();
|
||||||
|
|
||||||
//! Get binlog info \a BinLogInfo
|
//! \~english Returns cached index info when available, otherwise reparses current file info.
|
||||||
|
//! \~russian Возвращает кэшированную информацию индекса, если она есть, иначе заново разбирает информацию текущего файла.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english A \a BinLogInfo structure containing comprehensive information about the log file.
|
||||||
|
//! \~russian Структура \a BinLogInfo, содержащая исчерпывающую информацию о файле лога.
|
||||||
BinLogInfo logInfo() const {
|
BinLogInfo logInfo() const {
|
||||||
if (is_indexed) return index.info;
|
if (is_indexed) return index.info;
|
||||||
return getLogInfo(path());
|
return getLogInfo(path());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Get binlog index \a BinLogIndex, need \a createIndex before getting index
|
//! \~english Returns current record index data.
|
||||||
|
//! \~russian Возвращает текущие данные индекса записей.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Meaningful data appears after \a createIndex(), \a loadIndex() or indexed writing.
|
||||||
|
//! \~russian Осмысленные данные появляются после \a createIndex(), \a loadIndex() или записи с активным индексированием.
|
||||||
const PIVector<BinLogIndex> & logIndex() const { return index.index; }
|
const PIVector<BinLogIndex> & logIndex() const { return index.index; }
|
||||||
|
|
||||||
//! Create index of current binlog file
|
//! \~english Builds record index for the current log file.
|
||||||
|
//! \~russian Строит индекс записей для текущего файла лога.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Builds an index of the log file for fast random access to records. The index stores position, ID, and timestamp for each
|
||||||
|
//! record.
|
||||||
|
//! \~russian Строит индекс файла лога для быстрого случайного доступа к записям. Индекс хранит позицию, ID и метку времени для каждой
|
||||||
|
//! записи.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if index creation was successful, false otherwise.
|
||||||
|
//! \~russian true, если создание индекса прошло успешно, иначе false.
|
||||||
bool createIndex();
|
bool createIndex();
|
||||||
|
|
||||||
//! Return if current binlog file is indexed
|
//! \~english Returns whether the current log has loaded index data.
|
||||||
|
//! \~russian Возвращает, имеет ли текущий лог загруженные данные индекса.
|
||||||
bool isIndexed() { return is_indexed; }
|
bool isIndexed() { return is_indexed; }
|
||||||
|
|
||||||
//! Find nearest record of time \"time\". Returns -1 if not indexed or time less than first record
|
//! \~english Returns index of the first indexed record at or after "time".
|
||||||
|
//! \~russian Возвращает индекс первой индексированной записи в момент "time" или позже.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Finds the index of the record with the timestamp closest to the specified time. Requires the file to be indexed first.
|
||||||
|
//! \~russian Находит индекс записи с меткой времени, ближайшей к указанному времени. Требует, чтобы файл был проиндексирован заранее.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english The target timestamp to find.
|
||||||
|
//! \~russian Целевая метка времени для поиска.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The index of the nearest record, or -1 if not indexed or the time is before the first record.
|
||||||
|
//! \~russian Индекс ближайшей записи, или -1, если не проиндексировано или время раньше первой записи.
|
||||||
int posForTime(const PISystemTime & time);
|
int posForTime(const PISystemTime & time);
|
||||||
|
|
||||||
//! Go to record #index
|
//! \~english Seeks to indexed record number "rindex".
|
||||||
|
//! \~russian Переходит к индексированной записи номер "rindex".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Seeks to a specific record by its index position in the log file.
|
||||||
|
//! \~russian Переходит к конкретной записи по её индексу в файле лога.
|
||||||
|
//! \~\param rindex
|
||||||
|
//! \~english The index of the record to seek to.
|
||||||
|
//! \~russian Индекс записи, к которой нужно перейти.
|
||||||
void seekTo(int rindex);
|
void seekTo(int rindex);
|
||||||
|
|
||||||
//! Go to nearest record
|
//! \~english Seeks to the first indexed record at or after "time".
|
||||||
|
//! \~russian Переходит к первой индексированной записи в момент "time" или позже.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Seeks to the record with the timestamp closest to the specified time. Requires the file to be indexed first.
|
||||||
|
//! \~russian Переходит к записи с меткой времени, ближайшей к указанному времени. Требует, чтобы файл был проиндексирован заранее.
|
||||||
|
//! \~\param time
|
||||||
|
//! \~english The target timestamp to seek to.
|
||||||
|
//! \~russian Целевая метка времени для перехода.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if the seek was successful, false otherwise.
|
||||||
|
//! \~russian true, если переход прошел успешно, иначе false.
|
||||||
bool seek(const PISystemTime & time);
|
bool seek(const PISystemTime & time);
|
||||||
|
|
||||||
//! Set position in file to reading/playing
|
//! \~english Seeks to the first indexed record whose file position is at or after "filepos".
|
||||||
|
//! \~russian Переходит к первой индексированной записи, чья позиция в файле находится в точке "filepos" или позже.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Seeks to a specific byte position in the log file for reading or playing.
|
||||||
|
//! \~russian Переходит к конкретной байтовой позиции в файле лога для чтения или воспроизведения.
|
||||||
|
//! \~\param filepos
|
||||||
|
//! \~english The byte position in the file.
|
||||||
|
//! \~russian Позиция в байтах в файле.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if the seek was successful, false otherwise.
|
||||||
|
//! \~russian true, если переход прошел успешно, иначе false.
|
||||||
bool seek(llong filepos);
|
bool seek(llong filepos);
|
||||||
|
|
||||||
//! Get current record index (position record in file)
|
//! \~english Returns current indexed record position, or -1 when not indexed.
|
||||||
|
//! \~russian Возвращает текущую позицию индексированной записи или -1, если индекс отсутствует.
|
||||||
int pos() const;
|
int pos() const;
|
||||||
|
|
||||||
|
//! \~english Serializes current index data.
|
||||||
|
//! \~russian Сериализует текущие данные индекса.
|
||||||
PIByteArray saveIndex() const;
|
PIByteArray saveIndex() const;
|
||||||
|
|
||||||
|
//! \~english Loads previously serialized index data for the current readable log.
|
||||||
|
//! \~russian Загружает ранее сериализованные данные индекса для текущего читаемого лога.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Loads an index that was previously saved with saveIndex(). The file must be opened before loading the index.
|
||||||
|
//! \~russian Загружает индекс, который был ранее сохранен с помощью saveIndex(). Файл должен быть открыт перед загрузкой индекса.
|
||||||
|
//! \~\param saved
|
||||||
|
//! \~english The serialized index data to load.
|
||||||
|
//! \~russian Сериализованные данные индекса для загрузки.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if the index was loaded successfully, false otherwise.
|
||||||
|
//! \~russian true, если индекс был загружен успешно, иначе false.
|
||||||
bool loadIndex(PIByteArray saved);
|
bool loadIndex(PIByteArray saved);
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn PIString createNewFile()
|
//! \fn PIString createNewFile()
|
||||||
//! \brief Create new binlog file in \a logDir, if successful returns filename, else returns empty string.
|
//! \~english Creates a new log file in \a logDir() and returns its path, or empty string on failure.
|
||||||
//! Filename is like \a filePrefix + "yyyy_MM_dd__hh_mm_ss.binlog"
|
//! \~russian Создает новый файл лога в \a logDir() и возвращает его путь или пустую строку при ошибке.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Default filenames look like \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog".
|
||||||
|
//! \~russian Имена файлов по умолчанию имеют вид \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog".
|
||||||
|
EVENT_HANDLER(PIString, createNewFile);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void fileEnd()
|
//! \fn void fileEnd()
|
||||||
//! \brief Raise on file end while reading
|
//! \~english Raised when reading reaches the end of file.
|
||||||
|
//! \~russian Вызывается, когда чтение достигает конца файла.
|
||||||
|
EVENT(fileEnd);
|
||||||
|
|
||||||
//! \fn void fileError()
|
//! \fn void fileError()
|
||||||
//! \brief Raise on file creation error
|
//! \~english Raised when file header validation or file creation fails.
|
||||||
|
//! \~russian Вызывается при ошибке проверки заголовка файла или создания файла.
|
||||||
|
EVENT(fileError);
|
||||||
|
|
||||||
//! \fn void newFile(const PIString & filename)
|
//! \fn void newFile(const PIString & filename)
|
||||||
//! \brief Raise on new file created
|
//! \~english Raised after a new log file is successfully created.
|
||||||
|
//! \~russian Вызывается после успешного создания нового файла лога.
|
||||||
|
EVENT1(newFile, const PIString &, filename);
|
||||||
|
|
||||||
|
//! \fn void posChanged(int pos)
|
||||||
|
//! \~english Raised when current indexed playback position changes.
|
||||||
|
//! \~russian Вызывается при изменении текущей индексированной позиции воспроизведения.
|
||||||
|
EVENT1(posChanged, int, pos);
|
||||||
|
|
||||||
|
//! \fn void threadedReadRecord(PIByteArray data, int id, PISystemTime time)
|
||||||
|
//! \~english Raised after threaded playback emits one record.
|
||||||
|
//! \~russian Вызывается после выдачи одной записи потоковым воспроизведением.
|
||||||
|
EVENT3(threadedReadRecord, PIByteArray, data, int, id, PISystemTime, time);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
EVENT_HANDLER(PIString, createNewFile);
|
|
||||||
EVENT(fileEnd);
|
|
||||||
EVENT(fileError);
|
|
||||||
EVENT1(newFile, const PIString &, filename);
|
|
||||||
EVENT1(posChanged, int, pos);
|
|
||||||
EVENT3(threadedReadRecord, PIByteArray, data, int, id, PISystemTime, time);
|
|
||||||
|
|
||||||
//! Get binlog info and statistic
|
//! \~english Get binlog info and statistic
|
||||||
|
//! \~russian Получить информацию и статистику о бинарном логе
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Parses the specified log file and returns comprehensive information including record statistics, file size, and time
|
||||||
|
//! range. This is a static method that can be called without an instance.
|
||||||
|
//! \~russian Анализирует указанный файл лога и возвращает исчерпывающую информацию, включая статистику записей, размер файла и
|
||||||
|
//! временной диапазон. Это статический метод, который можно вызывать без экземпляра.
|
||||||
|
//! \~\param path
|
||||||
|
//! \~english The path to the log file to analyze.
|
||||||
|
//! \~russian Путь к анализируемому файлу лога.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english A \a BinLogInfo structure containing the file information and statistics.
|
||||||
|
//! \~russian Структура \a BinLogInfo, содержащая информацию о файле и статистику.
|
||||||
static BinLogInfo getLogInfo(const PIString & path);
|
static BinLogInfo getLogInfo(const PIString & path);
|
||||||
|
|
||||||
//! Create new binlog from part of "src" with allowed IDs and "from" to "to" file position
|
//! \~english Create new binlog from part of "src" with allowed IDs and "from" to "to" file position
|
||||||
|
//! \~russian Создать новый бинарный лог из части "src" с разрешенными ID и от "from" до "to" позиции файла
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Creates a new log file by extracting records from the source log between the specified file positions. Only records within
|
||||||
|
//! the specified ID filter range are included.
|
||||||
|
//! \~russian Создает новый файл лога путем извлечения записей из исходного лога между указанными позициями файла. Включаются только
|
||||||
|
//! записи в пределах указанного диапазона ID фильтра.
|
||||||
|
//! \~\param src
|
||||||
|
//! \~english The source log information containing the path and metadata.
|
||||||
|
//! \~russian Информация об исходном логе, содержащая путь и метаданные.
|
||||||
|
//! \~\param dst
|
||||||
|
//! \~english The path where the new log file will be created.
|
||||||
|
//! \~russian Путь, где будет создан новый файл лога.
|
||||||
|
//! \~\param from
|
||||||
|
//! \~english The starting file position (inclusive).
|
||||||
|
//! \~russian Начальная позиция файла (включительно).
|
||||||
|
//! \~\param to
|
||||||
|
//! \~english The ending file position (exclusive).
|
||||||
|
//! \~russian Конечная позиция файла (исключительно).
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if the cut operation was successful, false otherwise.
|
||||||
|
//! \~russian true, если операция вырезания прошла успешно, иначе false.
|
||||||
static bool cutBinLog(const BinLogInfo & src, const PIString & dst, int from, int to);
|
static bool cutBinLog(const BinLogInfo & src, const PIString & dst, int from, int to);
|
||||||
|
|
||||||
//! Create new binlog from serial splitted binlogs "src"
|
//! \~english Create new binlog from serial splitted binlogs "src"
|
||||||
|
//! \~russian Создать новый бинарный лог из последовательных разделенных бинарных логов "src"
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Concatenates multiple split log files into a single log file. The source files should be in chronological order. An
|
||||||
|
//! optional progress callback can be provided to track the operation.
|
||||||
|
//! \~russian Конкатенирует несколько разделенных файлов логов в один файл лога. Исходные файлы должны быть в хронологическом порядке.
|
||||||
|
//! Можно предоставить необязательный обратный вызов прогресса для отслеживания операции.
|
||||||
|
//! \~\param src
|
||||||
|
//! \~english List of source log file paths to join.
|
||||||
|
//! \~russian Список путей к исходным файлам лога для объединения.
|
||||||
|
//! \~\param dst
|
||||||
|
//! \~english The path where the combined log file will be created.
|
||||||
|
//! \~russian Путь, где будет создан объединенный файл лога.
|
||||||
|
//! \~\param progress
|
||||||
|
//! \~english Optional callback function that receives the current file path and timestamp, returning true to continue or false to
|
||||||
|
//! cancel.
|
||||||
|
//! \~russian Необязательная функция обратного вызова, получающая текущий путь к файлу и метку времени, возвращающая true для
|
||||||
|
//! продолжения или false для отмены.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english true if the join operation was successful, false otherwise.
|
||||||
|
//! \~russian true, если операция объединения прошла успешно, иначе false.
|
||||||
static bool joinBinLogsSerial(const PIStringList & src,
|
static bool joinBinLogsSerial(const PIStringList & src,
|
||||||
const PIString & dst,
|
const PIString & dst,
|
||||||
std::function<bool(const PIString &, PISystemTime)> progress = nullptr);
|
std::function<bool(const PIString &, PISystemTime)> progress = nullptr);
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
//! \~english Construct full device path
|
||||||
|
//! \~russian Создать полный путь устройства
|
||||||
PIString constructFullPathDevice() const override;
|
PIString constructFullPathDevice() const override;
|
||||||
|
|
||||||
|
//! \~english Configure from full device path
|
||||||
|
//! \~russian Настроить из полного пути устройства
|
||||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||||
|
|
||||||
|
//! \~english Construct variant device properties
|
||||||
|
//! \~russian Создать свойства устройства варианта
|
||||||
PIPropertyStorage constructVariantDevice() const override;
|
PIPropertyStorage constructVariantDevice() const override;
|
||||||
|
|
||||||
|
//! \~english Configure from variant device properties
|
||||||
|
//! \~russian Настроить из свойств устройства варианта
|
||||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||||
|
|
||||||
|
//! \~english Read from device
|
||||||
|
//! \~russian Чтение из устройства
|
||||||
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
ssize_t readDevice(void * read_to, ssize_t max_size) override;
|
||||||
|
|
||||||
|
//! \~english Write to device
|
||||||
|
//! \~russian Запись в устройство
|
||||||
ssize_t writeDevice(const void * data, ssize_t size) override;
|
ssize_t writeDevice(const void * data, ssize_t size) override;
|
||||||
|
|
||||||
|
//! \~english Open device
|
||||||
|
//! \~russian Открыть устройство
|
||||||
bool openDevice() override;
|
bool openDevice() override;
|
||||||
|
|
||||||
|
//! \~english Close device
|
||||||
|
//! \~russian Закрыть устройство
|
||||||
bool closeDevice() override;
|
bool closeDevice() override;
|
||||||
|
|
||||||
|
//! \~english Property changed callback
|
||||||
|
//! \~russian Обратный вызов изменения свойства
|
||||||
void propertyChanged(const char * s) override;
|
void propertyChanged(const char * s) override;
|
||||||
|
|
||||||
|
//! \~english Threaded read callback
|
||||||
|
//! \~russian Обратный вызов потокового чтения
|
||||||
bool threadedRead(const uchar * readed, ssize_t size) override;
|
bool threadedRead(const uchar * readed, ssize_t size) override;
|
||||||
|
|
||||||
|
//! \~english Get device information flags
|
||||||
|
//! \~russian Получить флаги информации об устройстве
|
||||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -436,7 +951,9 @@ BINARY_STREAM_READ(PIBinaryLog::CompleteIndex) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \relatesalso PICout \brief Output operator PIBinaryLog::BinLogInfo to PICout
|
//! \relatesalso PICout
|
||||||
|
//! \~english Writes \a PIBinaryLog::BinLogInfo summary to \a PICout.
|
||||||
|
//! \~russian Выводит сводку \a PIBinaryLog::BinLogInfo в \a PICout.
|
||||||
inline PICout operator<<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
inline PICout operator<<(PICout s, const PIBinaryLog::BinLogInfo & bi) {
|
||||||
s.space();
|
s.space();
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pican.h
|
//! \~\file pican.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english CAN device
|
//! \~english CAN bus device wrapper
|
||||||
* \~russian Устройство CAN
|
//! \~russian Обертка над устройством шины CAN
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
CAN
|
CAN
|
||||||
@@ -29,16 +28,36 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english CAN device based on interface name and frame identifier.
|
||||||
|
//! \~russian CAN-устройство, настраиваемое именем интерфейса и идентификатором кадра.
|
||||||
class PIP_EXPORT PICAN: public PIIODevice {
|
class PIP_EXPORT PICAN: public PIIODevice {
|
||||||
PIIODEVICE(PICAN, "can");
|
PIIODEVICE(PICAN, "can");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a CAN device for interface "path".
|
||||||
|
//! \~russian Создает CAN-устройство для интерфейса "path".
|
||||||
explicit PICAN(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
explicit PICAN(const PIString & path = PIString(), PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the CAN device.
|
||||||
|
//! \~russian Уничтожает CAN-устройство.
|
||||||
virtual ~PICAN();
|
virtual ~PICAN();
|
||||||
|
|
||||||
|
//! \~english Sets CAN frame identifier for subsequent \a write() calls.
|
||||||
|
//! \~russian Устанавливает идентификатор CAN-кадра для последующих вызовов \a write().
|
||||||
void setCANID(int id);
|
void setCANID(int id);
|
||||||
|
|
||||||
|
//! \~english Returns CAN frame identifier used by \a write().
|
||||||
|
//! \~russian Возвращает идентификатор CAN-кадра, используемый методом \a write().
|
||||||
int CANID() const;
|
int CANID() const;
|
||||||
|
|
||||||
|
//! \~english Returns identifier of the last frame received by \a read().
|
||||||
|
//! \~russian Возвращает идентификатор последнего кадра, полученного методом \a read().
|
||||||
int readedCANID() const;
|
int readedCANID() const;
|
||||||
|
|
||||||
|
//! \~english Interrupts a blocking CAN wait operation.
|
||||||
|
//! \~russian Прерывает блокирующее ожидание CAN-кадра.
|
||||||
void interrupt() override;
|
void interrupt() override;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piconfig.h
|
//! \~\file piconfig.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Configuration files parser and writer
|
//! \~english Configuration files parser and writer
|
||||||
* \~russian Разбор и запись конфигурационных файлов
|
//! \~russian Разбор и запись конфигурационных файлов
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Configuration parser and writer
|
Configuration parser and writer
|
||||||
@@ -58,6 +57,17 @@
|
|||||||
Entry & getValue(const PIString & vname, const double def, bool * exists = 0) const {return getValue(vname, PIString::fromNumber(def), exists);}
|
Entry & getValue(const PIString & vname, const double def, bool * exists = 0) const {return getValue(vname, PIString::fromNumber(def), exists);}
|
||||||
// clang-format on
|
// clang-format on
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~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.
|
||||||
|
//! Supports dotted paths, INI-style section prefixes, multiline values and \c include entries resolved during parsing.
|
||||||
|
//! \~russian
|
||||||
|
//! PIConfig предоставляет функциональность для чтения, записи и управления конфигурационными файлами в древовидной структуре.
|
||||||
|
//! Поддерживает точечные пути, префиксы секций в стиле INI, многострочные значения и записи \c include, разрешаемые при разборе.
|
||||||
class PIP_EXPORT PIConfig {
|
class PIP_EXPORT PIConfig {
|
||||||
friend class Entry;
|
friend class Entry;
|
||||||
friend class Branch;
|
friend class Branch;
|
||||||
@@ -65,20 +75,29 @@ class PIP_EXPORT PIConfig {
|
|||||||
public:
|
public:
|
||||||
NO_COPY_CLASS(PIConfig);
|
NO_COPY_CLASS(PIConfig);
|
||||||
|
|
||||||
//! Contructs and read configuration file at path "path" in mode "mode"
|
//! \~english Opens and parses configuration file at "path".
|
||||||
|
//! \~russian Открывает и разбирает файл конфигурации по пути "path".
|
||||||
PIConfig(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
PIConfig(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! Contructs and read configuration string "string" in mode "mode"
|
//! \~english Opens and parses configuration stored in "string".
|
||||||
|
//! \~russian Открывает и разбирает конфигурацию, хранящуюся в "string".
|
||||||
PIConfig(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
PIConfig(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! Contructs and read configuration from custom device "device" in mode "mode"
|
//! \~english Opens and parses configuration from custom device "device".
|
||||||
|
//! \~russian Открывает и разбирает конфигурацию из пользовательского устройства "device".
|
||||||
PIConfig(PIIODevice * device = nullptr, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
PIConfig(PIIODevice * device = nullptr, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the parser and releases owned devices.
|
||||||
|
//! \~russian Уничтожает парсер и освобождает принадлежащие ему устройства.
|
||||||
~PIConfig();
|
~PIConfig();
|
||||||
|
|
||||||
class Entry;
|
class Entry;
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Branch class - container for Entry objects
|
||||||
|
//! \~russian Класс Branch - контейнер для объектов Entry
|
||||||
class PIP_EXPORT Branch: public PIVector<Entry *> {
|
class PIP_EXPORT Branch: public PIVector<Entry *> {
|
||||||
friend class PIConfig;
|
friend class PIConfig;
|
||||||
friend class Entry;
|
friend class Entry;
|
||||||
@@ -90,22 +109,100 @@ public:
|
|||||||
public:
|
public:
|
||||||
Branch() { ; }
|
Branch() { ; }
|
||||||
|
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Get value from branch by name with default value
|
||||||
|
//! \~russian Получить значение из ветки по имени со значением по умолчанию
|
||||||
|
//! \~\details
|
||||||
|
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||||
|
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||||
|
//! указатель передан.
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||||
return const_cast<Branch *>(this)->getValue(vname, def, exists);
|
return const_cast<Branch *>(this)->getValue(vname, def, exists);
|
||||||
}
|
}
|
||||||
|
|
||||||
PICONFIG_GET_VALUE
|
PICONFIG_GET_VALUE
|
||||||
|
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns all leaf descendants reachable from this branch.
|
||||||
|
//! \~russian Возвращает все листовые потомки, достижимые из этой ветви.
|
||||||
Branch allLeaves();
|
Branch allLeaves();
|
||||||
|
|
||||||
|
//! \~english Get all entries with name containing specified substring
|
||||||
|
//! \~russian Получить все записи с именем, содержащим указанную подстроку
|
||||||
Branch getValues(const PIString & name);
|
Branch getValues(const PIString & name);
|
||||||
|
|
||||||
|
//! \~english Returns only entries in this branch that have no children.
|
||||||
|
//! \~russian Возвращает только записи этой ветви без дочерних элементов.
|
||||||
Branch getLeaves();
|
Branch getLeaves();
|
||||||
|
|
||||||
|
//! \~english Returns only entries in this branch that have children.
|
||||||
|
//! \~russian Возвращает только записи этой ветви, имеющие дочерние элементы.
|
||||||
Branch getBranches();
|
Branch getBranches();
|
||||||
|
|
||||||
|
//! \~english Removes entries whose names do not contain "f".
|
||||||
|
//! \~russian Удаляет записи, чьи имена не содержат "f".
|
||||||
Branch & filter(const PIString & f);
|
Branch & filter(const PIString & f);
|
||||||
|
|
||||||
|
//! \~english Returns \b true if any entry in this branch or its descendants has name "name".
|
||||||
|
//! \~russian Возвращает \b true, если какая-либо запись этой ветви или ее потомков имеет имя "name".
|
||||||
bool isEntryExists(const PIString & name) const {
|
bool isEntryExists(const PIString & name) const {
|
||||||
for (const auto * i: *this)
|
for (const auto * i: *this)
|
||||||
if (entryExists(i, name)) return true;
|
if (entryExists(i, name)) return true;
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns position of entry pointer "e" inside this branch, or -1.
|
||||||
|
//! \~russian Возвращает позицию указателя на запись "e" в этой ветви или -1.
|
||||||
int indexOf(const Entry * e) {
|
int indexOf(const Entry * e) {
|
||||||
for (int i = 0; i < size_s(); ++i)
|
for (int i = 0; i < size_s(); ++i)
|
||||||
if (at(i) == e) return i;
|
if (at(i) == e) return i;
|
||||||
@@ -138,175 +235,216 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Node of the parsed configuration tree.
|
||||||
|
//! \~russian Узел разобранного дерева конфигурации.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Stores entry name, value, type mark, inline comment and child entries derived from dotted names.
|
||||||
|
//! \~russian Хранит имя записи, значение, метку типа, встроенный комментарий и дочерние записи, полученные из точечных имен.
|
||||||
class PIP_EXPORT Entry {
|
class PIP_EXPORT Entry {
|
||||||
friend class PIConfig;
|
friend class PIConfig;
|
||||||
friend class Branch;
|
friend class Branch;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an empty detached entry.
|
||||||
|
//! \~russian Создает пустую отсоединенную запись.
|
||||||
Entry() {
|
Entry() {
|
||||||
_parent = 0;
|
_parent = 0;
|
||||||
_line = -1;
|
_line = -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns parent entry, or 0 if there is no parent (root of default value)
|
//! \~english Returns parent entry, or \c 0 for the root and default placeholder entries.
|
||||||
|
//! \~russian Возвращает родительскую запись или \c 0 для корня и внутренних placeholder-записей по умолчанию.
|
||||||
Entry * parent() const { return _parent; }
|
Entry * parent() const { return _parent; }
|
||||||
|
|
||||||
//! Returns children count
|
//! \~english Returns direct children count.
|
||||||
|
//! \~russian Возвращает количество непосредственных дочерних записей.
|
||||||
int childCount() const { return _children.size_s(); }
|
int childCount() const { return _children.size_s(); }
|
||||||
|
|
||||||
//! Returns children as \a PIConfig::Branch
|
//! \~english Returns direct children as \a PIConfig::Branch.
|
||||||
|
//! \~russian Возвращает непосредственных потомков как \a PIConfig::Branch.
|
||||||
Branch & children() const {
|
Branch & children() const {
|
||||||
_children.delim = delim;
|
_children.delim = delim;
|
||||||
return _children;
|
return _children;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns child at index "index"
|
//! \~english Returns direct child at position "index".
|
||||||
|
//! \~russian Возвращает непосредственного потомка с позицией "index".
|
||||||
Entry * child(const int index) const { return _children[index]; }
|
Entry * child(const int index) const { return _children[index]; }
|
||||||
|
|
||||||
//! Returns first child with name "name"
|
//! \~english Returns first direct child named "name".
|
||||||
|
//! \~russian Возвращает первого непосредственного потомка с именем "name".
|
||||||
Entry * findChild(const PIString & name) {
|
Entry * findChild(const PIString & name) {
|
||||||
for (auto * i: _children)
|
for (auto * i: _children)
|
||||||
if (i->_name == name) return i;
|
if (i->_name == name) return i;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns first child with name "name"
|
//! \~english Returns first direct child named "name".
|
||||||
|
//! \~russian Возвращает первого непосредственного потомка с именем "name".
|
||||||
const Entry * findChild(const PIString & name) const {
|
const Entry * findChild(const PIString & name) const {
|
||||||
for (const auto * i: _children)
|
for (const auto * i: _children)
|
||||||
if (i->_name == name) return i;
|
if (i->_name == name) return i;
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns \b true if there is no children
|
//! \~english Returns \b true when the entry has no children.
|
||||||
|
//! \~russian Возвращает \b true, когда у записи нет дочерних элементов.
|
||||||
bool isLeaf() const { return _children.isEmpty(); }
|
bool isLeaf() const { return _children.isEmpty(); }
|
||||||
|
|
||||||
|
|
||||||
//! Returns name
|
//! \~english Returns local entry name without parent prefix.
|
||||||
|
//! \~russian Возвращает локальное имя записи без родительского префикса.
|
||||||
const PIString & name() const { return _name; }
|
const PIString & name() const { return _name; }
|
||||||
|
|
||||||
//! Returns value
|
//! \~english Returns raw stored value.
|
||||||
|
//! \~russian Возвращает исходное сохраненное значение.
|
||||||
const PIString & value() const { return _value; }
|
const PIString & value() const { return _value; }
|
||||||
|
|
||||||
//! Returns type
|
//! \~english Returns one-letter stored type mark.
|
||||||
|
//! \~russian Возвращает сохраненную однобуквенную метку типа.
|
||||||
const PIString & type() const { return _type; }
|
const PIString & type() const { return _type; }
|
||||||
|
|
||||||
//! Returns comment
|
//! \~english Returns inline comment stored after the type mark.
|
||||||
|
//! \~russian Возвращает встроенный комментарий, сохраненный после метки типа.
|
||||||
const PIString & comment() const { return _comment; }
|
const PIString & comment() const { return _comment; }
|
||||||
|
|
||||||
/** \brief Returns full name, i.e. name as it looks in file
|
//! \~\brief
|
||||||
* \details In case of default entry full name always is empty
|
//! \~english Returns full dotted name as it appears in the tree.
|
||||||
* \snippet piconfig.cpp fullName */
|
//! \~russian Возвращает полное точечное имя в дереве.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Default placeholder entries always have empty full name.
|
||||||
|
//! \~russian У placeholder-записей по умолчанию полное имя всегда пустое.
|
||||||
|
//! \snippet piconfig.cpp fullName
|
||||||
const PIString & fullName() const { return _full_name; }
|
const PIString & fullName() const { return _full_name; }
|
||||||
|
|
||||||
//! Set name to "value" and returns this
|
//! \~english Sets local name to "value" and returns this entry.
|
||||||
|
//! \~russian Устанавливает локальное имя в "value" и возвращает эту запись.
|
||||||
Entry & setName(const PIString & value) {
|
Entry & setName(const PIString & value) {
|
||||||
_name = value;
|
_name = value;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set type to "value" and returns this
|
//! \~english Sets stored type mark to "value" and returns this entry.
|
||||||
|
//! \~russian Устанавливает сохраненную метку типа в "value" и возвращает эту запись.
|
||||||
Entry & setType(const PIString & value) {
|
Entry & setType(const PIString & value) {
|
||||||
_type = value;
|
_type = value;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set comment to "value" and returns this
|
//! \~english Sets inline comment to "value" and returns this entry.
|
||||||
|
//! \~russian Устанавливает встроенный комментарий в "value" и возвращает эту запись.
|
||||||
Entry & setComment(const PIString & value) {
|
Entry & setComment(const PIString & value) {
|
||||||
_comment = value;
|
_comment = value;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this
|
//! \~english Sets raw stored value to "value" and returns this entry.
|
||||||
|
//! \~russian Устанавливает исходное сохраненное значение в "value" и возвращает эту запись.
|
||||||
Entry & setValue(const PIString & value) {
|
Entry & setValue(const PIString & value) {
|
||||||
_value = value;
|
_value = value;
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "l"
|
//! \~english Stores string list value and marks entry type as "l".
|
||||||
|
//! \~russian Сохраняет список строк и помечает тип записи как "l".
|
||||||
Entry & setValue(const PIStringList & value) {
|
Entry & setValue(const PIStringList & value) {
|
||||||
setValue(value.join("%|%"));
|
setValue(value.join("%|%"));
|
||||||
setType("l");
|
setType("l");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "s"
|
//! \~english Stores C-string value and marks entry type as "s".
|
||||||
|
//! \~russian Сохраняет значение C-строки и помечает тип записи как "s".
|
||||||
Entry & setValue(const char * value) {
|
Entry & setValue(const char * value) {
|
||||||
setValue(PIString(value));
|
setValue(PIString(value));
|
||||||
setType("s");
|
setType("s");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "b"
|
//! \~english Stores boolean value and marks entry type as "b".
|
||||||
|
//! \~russian Сохраняет логическое значение и помечает тип записи как "b".
|
||||||
Entry & setValue(const bool value) {
|
Entry & setValue(const bool value) {
|
||||||
setValue(PIString::fromBool(value));
|
setValue(PIString::fromBool(value));
|
||||||
setType("b");
|
setType("b");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "s"
|
//! \~english Stores character value and marks entry type as "s".
|
||||||
|
//! \~russian Сохраняет символьное значение и помечает тип записи как "s".
|
||||||
Entry & setValue(const char value) {
|
Entry & setValue(const char value) {
|
||||||
setValue(PIString(1, value));
|
setValue(PIString(1, value));
|
||||||
setType("s");
|
setType("s");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const short value) {
|
Entry & setValue(const short value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const int value) {
|
Entry & setValue(const int value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const long value) {
|
Entry & setValue(const long value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const uchar value) {
|
Entry & setValue(const uchar value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const ushort value) {
|
Entry & setValue(const ushort value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const uint value) {
|
Entry & setValue(const uint value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "n"
|
//! \~english Stores numeric value and marks entry type as "n".
|
||||||
|
//! \~russian Сохраняет числовое значение и помечает тип записи как "n".
|
||||||
Entry & setValue(const ulong value) {
|
Entry & setValue(const ulong value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("n");
|
setType("n");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "f"
|
//! \~english Stores floating-point value and marks entry type as "f".
|
||||||
|
//! \~russian Сохраняет вещественное значение и помечает тип записи как "f".
|
||||||
Entry & setValue(const float value) {
|
Entry & setValue(const float value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("f");
|
setType("f");
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set value to "value" and returns this. Type is set to "f"
|
//! \~english Stores floating-point value and marks entry type as "f".
|
||||||
|
//! \~russian Сохраняет вещественное значение и помечает тип записи как "f".
|
||||||
Entry & setValue(const double value) {
|
Entry & setValue(const double value) {
|
||||||
setValue(PIString::fromNumber(value));
|
setValue(PIString::fromNumber(value));
|
||||||
setType("f");
|
setType("f");
|
||||||
@@ -314,100 +452,128 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** \brief Returns entry with name "vname" and default value "def"
|
//! \~\brief
|
||||||
* \details If there is no suitable entry found, reference to default internal entry with
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
* value = "def" will be returned, and if "exists" not null it will be set to \b false */
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
|
//! \~\details
|
||||||
|
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||||
|
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||||
|
//! указатель передан.
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||||
return const_cast<Entry *>(this)->getValue(vname, def, exists);
|
return const_cast<Entry *>(this)->getValue(vname, def, exists);
|
||||||
}
|
}
|
||||||
PICONFIG_GET_VALUE
|
PICONFIG_GET_VALUE
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||||
//! \brief Returns entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
|
||||||
//! Find all entries with names with substrings "vname" and returns them as \a PIConfig::Branch
|
//! \~english Returns direct children whose names contain substring "vname".
|
||||||
|
//! \~russian Возвращает непосредственных потомков, чьи имена содержат подстроку "vname".
|
||||||
Branch getValues(const PIString & vname);
|
Branch getValues(const PIString & vname);
|
||||||
|
|
||||||
|
|
||||||
//! If there is no children returns if name == "name". Else returns if any child has name == "name"
|
//! \~english Returns \b true if this entry or any descendant has name "name".
|
||||||
|
//! \~russian Возвращает \b true, если эта запись или любой ее потомок имеет имя "name".
|
||||||
bool isEntryExists(const PIString & name) const { return entryExists(this, name); }
|
bool isEntryExists(const PIString & name) const { return entryExists(this, name); }
|
||||||
|
|
||||||
|
|
||||||
//! Convertion to boolean
|
//! \~english Converts stored value to \c bool.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c bool.
|
||||||
bool toBool() const { return _value.toBool(); }
|
bool toBool() const { return _value.toBool(); }
|
||||||
|
|
||||||
//! Convertion to char
|
//! \~english Converts stored value to \c char.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c char.
|
||||||
char toChar() const { return (_value.isEmpty() ? 0 : _value[0].toAscii()); }
|
char toChar() const { return (_value.isEmpty() ? 0 : _value[0].toAscii()); }
|
||||||
|
|
||||||
//! Convertion to short
|
//! \~english Converts stored value to \c short.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c short.
|
||||||
short toShort() const { return _value.toShort(); }
|
short toShort() const { return _value.toShort(); }
|
||||||
|
|
||||||
//! Convertion to int
|
//! \~english Converts stored value to \c int.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c int.
|
||||||
int toInt() const { return _value.toInt(); }
|
int toInt() const { return _value.toInt(); }
|
||||||
|
|
||||||
//! Convertion to long
|
//! \~english Converts stored value to \c long.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c long.
|
||||||
long toLong() const { return _value.toLong(); }
|
long toLong() const { return _value.toLong(); }
|
||||||
|
|
||||||
//! Convertion to uchar
|
//! \~english Converts stored value to \c uchar.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c uchar.
|
||||||
uchar toUChar() const { return _value.toInt(); }
|
uchar toUChar() const { return _value.toInt(); }
|
||||||
|
|
||||||
//! Convertion to ushort
|
//! \~english Converts stored value to \c ushort.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c ushort.
|
||||||
ushort toUShort() const { return _value.toShort(); }
|
ushort toUShort() const { return _value.toShort(); }
|
||||||
|
|
||||||
//! Convertion to uint
|
//! \~english Converts stored value to \c uint.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c uint.
|
||||||
uint toUInt() const { return _value.toInt(); }
|
uint toUInt() const { return _value.toInt(); }
|
||||||
|
|
||||||
//! Convertion to ulong
|
//! \~english Converts stored value to \c ulong.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c ulong.
|
||||||
ulong toULong() const { return _value.toLong(); }
|
ulong toULong() const { return _value.toLong(); }
|
||||||
|
|
||||||
//! Convertion to float
|
//! \~english Converts stored value to \c float.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c float.
|
||||||
float toFloat() const { return _value.toFloat(); }
|
float toFloat() const { return _value.toFloat(); }
|
||||||
|
|
||||||
//! Convertion to double
|
//! \~english Converts stored value to \c double.
|
||||||
|
//! \~russian Преобразует сохраненное значение в \c double.
|
||||||
double toDouble() const { return _value.toDouble(); }
|
double toDouble() const { return _value.toDouble(); }
|
||||||
|
|
||||||
//! Convertion to PIString
|
//! \~english Returns stored value as \a PIString.
|
||||||
|
//! \~russian Возвращает сохраненное значение как \a PIString.
|
||||||
PIString toString() const { return _value; }
|
PIString toString() const { return _value; }
|
||||||
|
|
||||||
//! Convertion to PIStringList
|
//! \~english Splits stored list value into \a PIStringList using internal list separator.
|
||||||
|
//! \~russian Разбивает сохраненное списковое значение в \a PIStringList, используя внутренний разделитель списков.
|
||||||
PIStringList toStringList() const { return _value.split("%|%"); }
|
PIStringList toStringList() const { return _value.split("%|%"); }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
@@ -446,18 +612,28 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! Read configuration from file at path "path" in mode "mode"
|
//! \~english Opens and parses configuration file at "path".
|
||||||
|
//! \~russian Открывает и разбирает файл конфигурации по пути "path".
|
||||||
bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
bool open(const PIString & path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! Read configuration from string "string" in mode "mode"
|
//! \~english Opens and parses configuration stored in "string".
|
||||||
|
//! \~russian Открывает и разбирает конфигурацию, хранящуюся в "string".
|
||||||
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
bool open(PIString * string, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! Read configuration from custom device "device" in mode "mode"
|
//! \~english Opens and parses configuration from custom device "device".
|
||||||
|
//! \~russian Открывает и разбирает конфигурацию из пользовательского устройства "device".
|
||||||
bool open(PIIODevice * device, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
bool open(PIIODevice * device, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Returns whether a backing device is currently opened.
|
||||||
|
//! \~russian Возвращает, открыто ли сейчас базовое устройство.
|
||||||
bool isOpened() const;
|
bool isOpened() const;
|
||||||
|
|
||||||
//! Returns top-level entry with name "vname", if doesn`t exists return entry with value "def" and set *exist to false
|
//! \~english Resolves top-level path "vname".
|
||||||
|
//! \~russian Разрешает путь верхнего уровня "vname".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
|
||||||
|
//! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
|
||||||
|
//! указатель передан.
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0);
|
||||||
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
Entry & getValue(const PIString & vname, const PIString & def = PIString(), bool * exists = 0) const {
|
||||||
return const_cast<PIConfig *>(this)->getValue(vname, def, exists);
|
return const_cast<PIConfig *>(this)->getValue(vname, def, exists);
|
||||||
@@ -465,112 +641,126 @@ public:
|
|||||||
|
|
||||||
PICONFIG_GET_VALUE
|
PICONFIG_GET_VALUE
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
//! \fn Entry & getValue(const PIString & vname, const char * def, bool * exists = 0)
|
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Get top-level entry with name "vname" and default value "def"
|
||||||
|
//! \~russian Получить запись верхнего уровня с именем "vname" и значением по умолчанию "def"
|
||||||
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
|
||||||
//! \brief Returns top-level entry with name "vname" and default value "def"
|
|
||||||
|
|
||||||
|
//! \~english Returns top-level entries whose names contain substring "vname".
|
||||||
//! Returns top-level entries with names with substrings "vname"
|
//! \~russian Возвращает записи верхнего уровня, чьи имена содержат подстроку "vname".
|
||||||
Branch getValues(const PIString & vname);
|
Branch getValues(const PIString & vname);
|
||||||
|
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "type" and if "write" immediate write to file. Add new entry if there
|
//! \~english Sets or creates top-level path "name", stores "value", assigns type mark "type" and optionally writes changes immediately.
|
||||||
//! is no suitable exists
|
//! \~russian Устанавливает или создает путь верхнего уровня "name", сохраняет "value", назначает метку типа "type" и при необходимости
|
||||||
|
//! сразу записывает изменения.
|
||||||
void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
void setValue(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "l" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores string list and marks type as "l".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет список строк и помечает тип как "l".
|
||||||
void setValue(const PIString & name, const PIStringList & value, bool write = true) { setValue(name, value.join("%|%"), "l", write); }
|
void setValue(const PIString & name, const PIStringList & value, bool write = true) { setValue(name, value.join("%|%"), "l", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "s" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores C-string and marks type as "s".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет C-строку и помечает тип как "s".
|
||||||
void setValue(const PIString & name, const char * value, bool write = true) { setValue(name, PIString(value), "s", write); }
|
void setValue(const PIString & name, const char * value, bool write = true) { setValue(name, PIString(value), "s", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "b" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores boolean value and marks type as "b".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет логическое значение и помечает тип как "b".
|
||||||
void setValue(const PIString & name, const bool value, bool write = true) { setValue(name, PIString::fromBool(value), "b", write); }
|
void setValue(const PIString & name, const bool value, bool write = true) { setValue(name, PIString::fromBool(value), "b", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const short value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const short value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const int value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const int value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const long value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const long value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const uchar value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const uchar value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const ushort value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const ushort value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const uint value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const uint value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "n" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores numeric value and marks type as "n".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет числовое значение и помечает тип как "n".
|
||||||
void setValue(const PIString & name, const ulong value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
void setValue(const PIString & name, const ulong value, bool write = true) { setValue(name, PIString::fromNumber(value), "n", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores floating-point value and marks type as "f".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет вещественное значение и помечает тип как "f".
|
||||||
void setValue(const PIString & name, const float value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
void setValue(const PIString & name, const float value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
||||||
|
|
||||||
//! Set top-level entry with name "name" value to "value", type to "f" and if "write" immediate write to file. Add new entry if there is
|
//! \~english Stores floating-point value and marks type as "f".
|
||||||
//! no suitable exists
|
//! \~russian Сохраняет вещественное значение и помечает тип как "f".
|
||||||
void setValue(const PIString & name, const double value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
void setValue(const PIString & name, const double value, bool write = true) { setValue(name, PIString::fromNumber(value), "f", write); }
|
||||||
|
|
||||||
//! Returns root entry
|
//! \~english Returns root entry of the parsed tree.
|
||||||
|
//! \~russian Возвращает корневую запись разобранного дерева.
|
||||||
Entry & rootEntry() { return root; }
|
Entry & rootEntry() { return root; }
|
||||||
|
|
||||||
//! Returns top-level entries count
|
//! \~english Returns total number of parsed entries below the root.
|
||||||
|
//! \~russian Возвращает общее количество разобранных записей ниже корня.
|
||||||
int entriesCount() const { return childCount(&root); }
|
int entriesCount() const { return childCount(&root); }
|
||||||
|
|
||||||
//! Returns if top-level entry with name "name" exists
|
//! \~english Returns \b true if any parsed entry path contains name "name".
|
||||||
|
//! \~russian Возвращает \b true, если среди разобранных путей есть запись с именем "name".
|
||||||
bool isEntryExists(const PIString & name) const { return entryExists(&root, name); }
|
bool isEntryExists(const PIString & name) const { return entryExists(&root, name); }
|
||||||
|
|
||||||
//! Returns all top-level entries
|
//! \~english Returns all direct children of the root entry.
|
||||||
|
//! \~russian Возвращает всех непосредственных потомков корневой записи.
|
||||||
Branch allTree() {
|
Branch allTree() {
|
||||||
Branch b;
|
Branch b;
|
||||||
for (auto * i: root._children)
|
for (auto * i: root._children)
|
||||||
@@ -579,7 +769,8 @@ public:
|
|||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns all entries without children
|
//! \~english Returns all stored leaves and valued branch entries sorted by source order.
|
||||||
|
//! \~russian Возвращает все сохраненные листья и ветви со значением, отсортированные по порядку в источнике.
|
||||||
Branch allLeaves() {
|
Branch allLeaves() {
|
||||||
Branch b;
|
Branch b;
|
||||||
allLeaves(b, &root);
|
allLeaves(b, &root);
|
||||||
@@ -588,35 +779,74 @@ public:
|
|||||||
return b;
|
return b;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns index of path "name" inside \a allLeaves(), or -1.
|
||||||
|
//! \~russian Возвращает индекс пути "name" внутри \a allLeaves() или -1.
|
||||||
int entryIndex(const PIString & name);
|
int entryIndex(const PIString & name);
|
||||||
|
|
||||||
|
//! \~english Returns entry name by \a allLeaves() index.
|
||||||
|
//! \~russian Возвращает имя записи по индексу в \a allLeaves().
|
||||||
PIString getName(uint number) { return entryByIndex(number)._name; }
|
PIString getName(uint number) { return entryByIndex(number)._name; }
|
||||||
|
|
||||||
|
//! \~english Returns entry value by \a allLeaves() index.
|
||||||
|
//! \~russian Возвращает значение записи по индексу в \a allLeaves().
|
||||||
PIString getValueByIndex(uint number) { return entryByIndex(number)._value; }
|
PIString getValueByIndex(uint number) { return entryByIndex(number)._value; }
|
||||||
|
|
||||||
|
//! \~english Returns entry type mark by \a allLeaves() index.
|
||||||
|
//! \~russian Возвращает метку типа записи по индексу в \a allLeaves().
|
||||||
PIChar getType(uint number) { return entryByIndex(number)._type[0]; }
|
PIChar getType(uint number) { return entryByIndex(number)._type[0]; }
|
||||||
|
|
||||||
|
//! \~english Returns entry comment by \a allLeaves() index.
|
||||||
|
//! \~russian Возвращает комментарий записи по индексу в \a allLeaves().
|
||||||
PIString getComment(uint number) { return entryByIndex(number)._comment; }
|
PIString getComment(uint number) { return entryByIndex(number)._comment; }
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Creates new path "name" when it does not already exist and optionally writes changes immediately.
|
||||||
|
//! \~russian Создает новый путь "name", если он еще не существует, и при необходимости сразу записывает изменения.
|
||||||
void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
void addEntry(const PIString & name, const PIString & value, const PIString & type = "s", bool write = true);
|
||||||
|
|
||||||
|
//! \~english Renames entry referenced by \a allLeaves() index "number".
|
||||||
|
//! \~russian Переименовывает запись, на которую ссылается индекс "number" в \a allLeaves().
|
||||||
void setName(uint number, const PIString & name, bool write = true);
|
void setName(uint number, const PIString & name, bool write = true);
|
||||||
|
|
||||||
|
//! \~english Replaces stored value of entry referenced by \a allLeaves() index "number".
|
||||||
|
//! \~russian Заменяет сохраненное значение записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||||
void setValue(uint number, const PIString & value, bool write = true);
|
void setValue(uint number, const PIString & value, bool write = true);
|
||||||
|
|
||||||
|
//! \~english Replaces type mark of entry referenced by \a allLeaves() index "number".
|
||||||
|
//! \~russian Заменяет метку типа записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||||
void setType(uint number, const PIString & type, bool write = true);
|
void setType(uint number, const PIString & type, bool write = true);
|
||||||
|
|
||||||
|
//! \~english Replaces comment of entry referenced by \a allLeaves() index "number".
|
||||||
|
//! \~russian Заменяет комментарий записи, на которую ссылается индекс "number" в \a allLeaves().
|
||||||
void setComment(uint number, const PIString & comment, bool write = true);
|
void setComment(uint number, const PIString & comment, bool write = true);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Removes entry path "name" and its subtree when needed.
|
||||||
|
//! \~russian Удаляет путь записи "name" и при необходимости его поддерево.
|
||||||
void removeEntry(const PIString & name, bool write = true);
|
void removeEntry(const PIString & name, bool write = true);
|
||||||
|
|
||||||
|
//! \~english Removes entry referenced by \a allLeaves() index "number".
|
||||||
|
//! \~russian Удаляет запись, на которую ссылается индекс "number" в \a allLeaves().
|
||||||
void removeEntry(uint number, bool write = true);
|
void removeEntry(uint number, bool write = true);
|
||||||
|
|
||||||
//! Remove all tree and device content
|
//! \~english Removes all parsed entries and clears the backing device content.
|
||||||
|
//! \~russian Удаляет все разобранные записи и очищает содержимое базового устройства.
|
||||||
void clear();
|
void clear();
|
||||||
|
|
||||||
//! Parse device and build internal tree
|
//! \~english Rebuilds internal tree from current device contents.
|
||||||
|
//! \~russian Перестраивает внутреннее дерево из текущего содержимого устройства.
|
||||||
void readAll();
|
void readAll();
|
||||||
|
|
||||||
//! Write all internal tree to device
|
//! \~english Writes current tree back to the device and reparses it.
|
||||||
|
//! \~russian Записывает текущее дерево обратно в устройство и разбирает его заново.
|
||||||
void writeAll();
|
void writeAll();
|
||||||
|
|
||||||
//! Returns current tree delimiter, default "."
|
//! \~english Returns current path delimiter, "." by default.
|
||||||
|
//! \~russian Возвращает текущий разделитель путей, по умолчанию ".".
|
||||||
const PIString & delimiter() const { return delim; }
|
const PIString & delimiter() const { return delim; }
|
||||||
|
|
||||||
//! Set current tree delimiter
|
//! \~english Sets path delimiter for subsequent parsing and reparses the device.
|
||||||
|
//! \~russian Устанавливает разделитель путей для последующего разбора и заново разбирает устройство.
|
||||||
void setDelimiter(const PIString & d) {
|
void setDelimiter(const PIString & d) {
|
||||||
delim = d;
|
delim = d;
|
||||||
setEntryDelim(&root, d);
|
setEntryDelim(&root, d);
|
||||||
@@ -692,30 +922,45 @@ private:
|
|||||||
|
|
||||||
|
|
||||||
#ifdef PIP_STD_IOSTREAM
|
#ifdef PIP_STD_IOSTREAM
|
||||||
|
|
||||||
|
//! \~english Writes branch contents to \a std::ostream in tree form.
|
||||||
|
//! \~russian Выводит содержимое ветви в \a std::ostream в виде дерева.
|
||||||
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Branch & v);
|
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Branch & v);
|
||||||
|
|
||||||
|
//! \~english Writes entry value to \a std::ostream.
|
||||||
|
//! \~russian Выводит значение записи в \a std::ostream.
|
||||||
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Entry & v);
|
PIP_EXPORT std::ostream & operator<<(std::ostream & s, const PIConfig::Entry & v);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
//! \~english Writes branch contents to \a PICout in tree form.
|
||||||
|
//! \~russian Выводит содержимое ветви в \a PICout в виде дерева.
|
||||||
inline PICout operator<<(PICout s, const PIConfig::Branch & v) {
|
inline PICout operator<<(PICout s, const PIConfig::Branch & v) {
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
v.piCoutt(s, "");
|
v.piCoutt(s, "");
|
||||||
s.restoreControls();
|
s.restoreControls();
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Writes entry value, type and comment to \a PICout.
|
||||||
|
//! \~russian Выводит значение, тип и комментарий записи в \a PICout.
|
||||||
inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
|
inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
|
||||||
s << v.value() << "(" << v.type() << v.comment() << ")";
|
s << v.value() << "(" << v.type() << v.comment() << ")";
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/** \relatesalso PIConfig \relatesalso PIIODevice
|
//! \relatesalso PIConfig
|
||||||
* \brief Service function. useful for configuring devices
|
//! \relatesalso PIIODevice
|
||||||
* \details Function takes entry name "name", default value "def" and two
|
//! \~\brief
|
||||||
* \a PIConfig::Entry sections: "em" and their parent "ep". If there is no
|
//! \~english Helper for reading device settings from configuration entries.
|
||||||
* parent ep = 0. If "ep" is not null and entry "name" exists in "ep" function
|
//! \~russian Вспомогательная функция для чтения настроек устройства из записей конфигурации.
|
||||||
* returns this value. Else returns value of entry "name" in section "em" or
|
//! \~\details
|
||||||
* "def" if entry doesn`t exists. \n This function useful to read settings
|
//! \~english
|
||||||
* from configuration file in implementation \a PIIODevice::configureDevice() function */
|
//! Tries to read "name" from parent section \a ep first, then from local section \a em, and falls back to "def" when neither exists.
|
||||||
|
//! \~russian
|
||||||
|
//! Сначала пытается прочитать "name" из родительской секции \a ep, затем из локальной секции \a em и возвращает "def", если запись не
|
||||||
|
//! найдена.
|
||||||
template<typename T>
|
template<typename T>
|
||||||
T readDeviceSetting(const PIString & name, const T & def, const PIConfig::Entry * em, const PIConfig::Entry * ep) {
|
T readDeviceSetting(const PIString & name, const T & def, const PIConfig::Entry * em, const PIConfig::Entry * ep) {
|
||||||
PIVariant v = PIVariant::fromValue<T>(def);
|
PIVariant v = PIVariant::fromValue<T>(def);
|
||||||
|
|||||||
@@ -30,177 +30,177 @@
|
|||||||
#include "piregularexpression.h"
|
#include "piregularexpression.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Local directory.
|
//! \~english Local directory.
|
||||||
//! \~russian Локальная директория.
|
//! \~russian Локальная директория.
|
||||||
class PIP_EXPORT PIDir {
|
class PIP_EXPORT PIDir {
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs directory with path "dir"
|
//! \~english Constructs directory with path "dir".
|
||||||
//! \~russian Создает директорию с путём "dir"
|
//! \~russian Создает директорию с путём "dir".
|
||||||
PIDir(const PIString & dir = PIString());
|
PIDir(const PIString & dir = PIString());
|
||||||
|
|
||||||
//! \~english Constructs directory with "file" directory path
|
//! \~english Constructs directory with "file" directory path.
|
||||||
//! \~russian Создает директорию с путём директории файла "file"
|
//! \~russian Создает директорию с путём директории файла "file".
|
||||||
PIDir(const PIFile & file);
|
PIDir(const PIFile & file);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns if this directory exists
|
//! \~english Returns if this directory exists.
|
||||||
//! \~russian Возвращает существует ли эта директория
|
//! \~russian Возвращает, существует ли эта директория.
|
||||||
bool isExists() const { return PIDir::isExists(path()); }
|
bool isExists() const { return PIDir::isExists(path()); }
|
||||||
|
|
||||||
//! \~english Returns if path of this directory is absolute
|
//! \~english Returns if path of this directory is absolute.
|
||||||
//! \~russian Возвращает абсолютный ли путь у директории
|
//! \~russian Возвращает, абсолютный ли путь у директории.
|
||||||
bool isAbsolute() const;
|
bool isAbsolute() const;
|
||||||
|
|
||||||
//! \~english Returns if path of this directory is relative
|
//! \~english Returns if path of this directory is relative.
|
||||||
//! \~russian Возвращает относительный ли путь у директории
|
//! \~russian Возвращает, относительный ли путь у директории.
|
||||||
bool isRelative() const { return !isAbsolute(); }
|
bool isRelative() const { return !isAbsolute(); }
|
||||||
|
|
||||||
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions
|
//! \~english Returns path of current reading directory. This path valid only while \a allEntries() functions.
|
||||||
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries()
|
//! \~russian Возвращает путь текущей директории чтения. Этот путь действителен только во время выполнения метода \a allEntries().
|
||||||
const PIString & scanDir() const { return scan_; }
|
const PIString & scanDir() const { return scan_; }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns name of this directory
|
//! \~english Returns name of this directory.
|
||||||
//! \~russian Возвращает имя директории
|
//! \~russian Возвращает имя директории.
|
||||||
PIString name() const;
|
PIString name() const;
|
||||||
|
|
||||||
//! \~english Returns path of this directory
|
//! \~english Returns path of this directory.
|
||||||
//! \~russian Возвращает путь директории
|
//! \~russian Возвращает путь директории.
|
||||||
PIString path() const;
|
PIString path() const;
|
||||||
|
|
||||||
//! \~english Returns absolute path of this directory
|
//! \~english Returns absolute path of this directory.
|
||||||
//! \~russian Возвращает абсолютный путь директории
|
//! \~russian Возвращает абсолютный путь директории.
|
||||||
PIString absolutePath() const;
|
PIString absolutePath() const;
|
||||||
|
|
||||||
//! \~english Simplify path of this directory
|
//! \~english Simplify path of this directory.
|
||||||
//! \~russian Упрощает путь директории
|
//! \~russian Упрощает путь директории.
|
||||||
PIDir & cleanPath();
|
PIDir & cleanPath();
|
||||||
|
|
||||||
//! \~english Returns %PIDir with simplified path of this directory
|
//! \~english Returns %PIDir with simplified path of this directory.
|
||||||
//! \~russian Возвращает %PIDir с упрощённым путём директории
|
//! \~russian Возвращает %PIDir с упрощённым путём директории.
|
||||||
PIDir cleanedPath() const {
|
PIDir cleanedPath() const {
|
||||||
PIDir d(path());
|
PIDir d(path());
|
||||||
d.cleanPath();
|
d.cleanPath();
|
||||||
return d;
|
return d;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns relative to this directory path "path"
|
//! \~english Returns relative to this directory path "path".
|
||||||
//! \~russian Возвращает путь "path" относительно этой директории
|
//! \~russian Возвращает путь "path" относительно этой директории.
|
||||||
PIString relative(const PIString & path) const;
|
PIString relative(const PIString & path) const;
|
||||||
|
|
||||||
//! \~english Returns relative to this directory path "path" as absolute path
|
//! \~english Returns relative to this directory path "path" as absolute path.
|
||||||
//! \~russian Возвращает путь "path" относительно этой директории в виде абсолютного пути
|
//! \~russian Возвращает путь "path" относительно этой директории в виде абсолютного пути.
|
||||||
PIString absolute(const PIString & path) const;
|
PIString absolute(const PIString & path) const;
|
||||||
|
|
||||||
//! \~english Set this directory path to simplified "path"
|
//! \~english Set this directory path to simplified "path".
|
||||||
//! \~russian Устанавливает путь директории упрощённым "path"
|
//! \~russian Устанавливает путь директории упрощённым "path".
|
||||||
PIDir & setDir(const PIString & path);
|
PIDir & setDir(const PIString & path);
|
||||||
|
|
||||||
//! \~english Set this directory path as current for application
|
//! \~english Set this directory path as current for application.
|
||||||
//! \~russian Устанавливает путь директории текущим путём приложения
|
//! \~russian Устанавливает путь директории текущим путём приложения.
|
||||||
bool setCurrent() { return PIDir::setCurrent(path()); }
|
bool setCurrent() { return PIDir::setCurrent(path()); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns this directory content
|
//! \~english Returns this directory content.
|
||||||
//! \~russian Возвращает содержимое этой директории
|
//! \~russian Возвращает содержимое этой директории.
|
||||||
PIVector<PIFile::FileInfo> entries(const PIRegularExpression & regexp = {});
|
PIVector<PIFile::FileInfo> entries(const PIRegularExpression & regexp = {});
|
||||||
|
|
||||||
//! \~english Returns this directory content recursively
|
//! \~english Returns this directory content recursively.
|
||||||
//! \~russian Возвращает содержимое этой директории рекурсивно
|
//! \~russian Возвращает содержимое этой директории рекурсивно.
|
||||||
PIVector<PIFile::FileInfo> allEntries(const PIRegularExpression & regexp = {});
|
PIVector<PIFile::FileInfo> allEntries(const PIRegularExpression & regexp = {});
|
||||||
|
|
||||||
//! \~english Make this directory, recursively if "withParents"
|
//! \~english Make this directory, recursively if "withParents".
|
||||||
//! \~russian Создаёт эту директорию, рекурсивно если "withParents"
|
//! \~russian Создаёт эту директорию, рекурсивно если "withParents".
|
||||||
bool make(bool withParents = true);
|
bool make(bool withParents = true);
|
||||||
|
|
||||||
//! \~english Remove this directory
|
//! \~english Remove this directory.
|
||||||
//! \~russian Удаляет эту директорию
|
//! \~russian Удаляет эту директорию.
|
||||||
bool remove() { return PIDir::remove(path()); }
|
bool remove() { return PIDir::remove(path()); }
|
||||||
|
|
||||||
//! \~english Rename this directory
|
//! \~english Rename this directory.
|
||||||
//! \~russian Переименовывает эту директорию
|
//! \~russian Переименовывает эту директорию.
|
||||||
bool rename(const PIString & new_name);
|
bool rename(const PIString & new_name);
|
||||||
|
|
||||||
//! \~english Change this directory to relative path "path"
|
//! \~english Change this directory to relative path "path".
|
||||||
//! \~russian Изменяет директорию на относительный путь "path"
|
//! \~russian Изменяет директорию на относительный путь "path".
|
||||||
PIDir & cd(const PIString & path);
|
PIDir & cd(const PIString & path);
|
||||||
|
|
||||||
//! \~english Change this directory to parent
|
//! \~english Change this directory to parent.
|
||||||
//! \~russian Изменяет директорию на родительскую
|
//! \~russian Изменяет директорию на родительскую.
|
||||||
PIDir & up() { return cd(".."); }
|
PIDir & up() { return cd(".."); }
|
||||||
|
|
||||||
//! \~english Compare operator
|
//! \~english Compare operator.
|
||||||
//! \~russian Оператор сравнения
|
//! \~russian Оператор сравнения.
|
||||||
bool operator==(const PIDir & d) const;
|
bool operator==(const PIDir & d) const;
|
||||||
|
|
||||||
//! \~english Compare operator
|
//! \~english Compare operator.
|
||||||
//! \~russian Оператор сравнения
|
//! \~russian Оператор сравнения.
|
||||||
bool operator!=(const PIDir & d) const { return !((*this) == d); }
|
bool operator!=(const PIDir & d) const { return !((*this) == d); }
|
||||||
|
|
||||||
static const PIChar separator;
|
static const PIChar separator;
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns current directory for application
|
//! \~english Returns current directory for application.
|
||||||
//! \~russian Возвращает текущую директорию приложения
|
//! \~russian Возвращает текущую директорию приложения.
|
||||||
static PIDir current();
|
static PIDir current();
|
||||||
|
|
||||||
//! \~english Returns user home directory
|
//! \~english Returns user home directory.
|
||||||
//! \~russian Возвращает домашнюю директорию пользователя
|
//! \~russian Возвращает домашнюю директорию пользователя.
|
||||||
static PIDir home();
|
static PIDir home();
|
||||||
|
|
||||||
//! \~english Returns temporary directory
|
//! \~english Returns temporary directory.
|
||||||
//! \~russian Возвращает временную директорию
|
//! \~russian Возвращает временную директорию.
|
||||||
static PIDir temporary();
|
static PIDir temporary();
|
||||||
|
|
||||||
//! \~english Returns directory "path" content recursively
|
//! \~english Returns directory "path" content recursively.
|
||||||
//! \~russian Возвращает содержимое директории "path" рекурсивно
|
//! \~russian Возвращает содержимое директории "path" рекурсивно.
|
||||||
static PIVector<PIFile::FileInfo> allEntries(const PIString & path, const PIRegularExpression & regexp = {});
|
static PIVector<PIFile::FileInfo> allEntries(const PIString & path, const PIRegularExpression & regexp = {});
|
||||||
|
|
||||||
//! \~english Returns if directory "path" exists
|
//! \~english Returns if directory "path" exists.
|
||||||
//! \~russian Возвращает существует ли эта директория
|
//! \~russian Возвращает, существует ли эта директория.
|
||||||
static bool isExists(const PIString & path);
|
static bool isExists(const PIString & path);
|
||||||
|
|
||||||
//! \~english Make directory "path", recursively if "withParents"
|
//! \~english Make directory "path", recursively if "withParents".
|
||||||
//! \~russian Создаёт директорию "path", рекурсивно если "withParents"
|
//! \~russian Создаёт директорию "path", рекурсивно если "withParents".
|
||||||
static bool make(const PIString & path, bool withParents = true);
|
static bool make(const PIString & path, bool withParents = true);
|
||||||
|
|
||||||
//! \~english Remove directory "path"
|
//! \~english Remove directory "path".
|
||||||
//! \~russian Удаляет директорию "path"
|
//! \~russian Удаляет директорию "path".
|
||||||
static bool remove(const PIString & path) { return removeDir(path); }
|
static bool remove(const PIString & path) { return removeDir(path); }
|
||||||
|
|
||||||
//! \~english Rename directory "path"
|
//! \~english Rename directory "path".
|
||||||
//! \~russian Переименовывает директорию "path"
|
//! \~russian Переименовывает директорию "path".
|
||||||
static bool rename(const PIString & path, const PIString & new_name) { return PIDir::renameDir(path, new_name); }
|
static bool rename(const PIString & path, const PIString & new_name) { return PIDir::renameDir(path, new_name); }
|
||||||
|
|
||||||
//! \~english Set path "path" as current for application
|
//! \~english Set path "path" as current for application.
|
||||||
//! \~russian Устанавливает путь "path" текущим путём приложения
|
//! \~russian Устанавливает путь "path" текущим путём приложения.
|
||||||
static bool setCurrent(const PIString & path);
|
static bool setCurrent(const PIString & path);
|
||||||
|
|
||||||
//! \~english Set directory "dir" path as current for application
|
//! \~english Set directory "dir" path as current for application.
|
||||||
//! \~russian Устанавливает путь директории "dir" текущим путём приложения
|
//! \~russian Устанавливает путь директории "dir" текущим путём приложения.
|
||||||
static bool setCurrent(const PIDir & dir) { return setCurrent(dir.path()); }
|
static bool setCurrent(const PIDir & dir) { return setCurrent(dir.path()); }
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Temporarily change working directory.
|
//! \~english Temporarily change working directory.
|
||||||
//! \~russian Временная смена рабочей директории.
|
//! \~russian Временная смена рабочей директории.
|
||||||
class PIP_EXPORT CurrentDirOverrider {
|
class PIP_EXPORT CurrentDirOverrider {
|
||||||
public:
|
public:
|
||||||
//! \~english Change working directory dir or file with relative or absolute path "path"
|
//! \~english Change working directory dir or file with relative or absolute path "path".
|
||||||
//! \~russian Меняет рабочую директорию на другую директорию или файл с относительным или абсолютным путём "path"
|
//! \~russian Меняет рабочую директорию на другую директорию или файл с относительным или абсолютным путём "path".
|
||||||
CurrentDirOverrider(const PIString & path);
|
CurrentDirOverrider(const PIString & path);
|
||||||
|
|
||||||
//! \~english Change working directory to dir or file "info"
|
//! \~english Change working directory to dir or file "info".
|
||||||
//! \~russian Меняет рабочую директорию на директорию или файл "info"
|
//! \~russian Меняет рабочую директорию на директорию или файл "info".
|
||||||
CurrentDirOverrider(const PIFile::FileInfo & info);
|
CurrentDirOverrider(const PIFile::FileInfo & info);
|
||||||
|
|
||||||
~CurrentDirOverrider() { restore(); }
|
~CurrentDirOverrider() { restore(); }
|
||||||
|
|
||||||
//! \~english Restore previous working directory
|
//! \~english Restore previous working directory.
|
||||||
//! \~russian Восстанавливает предыдущую рабочую директорию
|
//! \~russian Восстанавливает предыдущую рабочую директорию.
|
||||||
void restore();
|
void restore();
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piethernet.h
|
//! \~\file piethernet.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Ethernet device
|
//! \~english Ethernet-backed UDP and TCP device
|
||||||
* \~russian Устройство Ethernet
|
//! \~russian Устройство UDP и TCP поверх Ethernet
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Ethernet, UDP/TCP Broadcast/Multicast
|
Ethernet, UDP/TCP Broadcast/Multicast
|
||||||
@@ -36,371 +35,498 @@ class
|
|||||||
#endif
|
#endif
|
||||||
sockaddr;
|
sockaddr;
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english %PIIODevice implementation for UDP sockets, TCP clients and TCP servers.
|
||||||
|
//! \~russian Реализация %PIIODevice для UDP-сокетов, TCP-клиентов и TCP-серверов.
|
||||||
class PIP_EXPORT PIEthernet: public PIIODevice {
|
class PIP_EXPORT PIEthernet: public PIIODevice {
|
||||||
PIIODEVICE(PIEthernet, "eth");
|
PIIODEVICE(PIEthernet, "eth");
|
||||||
friend class PIPeer;
|
friend class PIPeer;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! Contructs UDP %PIEthernet with empty read address
|
//! \~english Constructs a UDP device with an empty read address.
|
||||||
|
//! \~russian Создает UDP-устройство с пустым адресом чтения.
|
||||||
explicit PIEthernet();
|
explicit PIEthernet();
|
||||||
|
|
||||||
//! \brief Type of %PIEthernet
|
//! \~english Operating mode of %PIEthernet.
|
||||||
|
//! \~russian Режим работы %PIEthernet.
|
||||||
enum Type {
|
enum Type {
|
||||||
UDP /** UDP - User Datagram Protocol */,
|
UDP /** \~english UDP datagram socket \~russian UDP-сокет датаграмм */,
|
||||||
TCP_Client /** TCP client - allow connection to TCP server */,
|
TCP_Client /** \~english TCP client socket \~russian TCP-клиент */,
|
||||||
TCP_Server /** TCP server - receive connections from TCP clients */
|
TCP_Server /** \~english TCP server socket \~russian TCP-сервер */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \brief Parameters of %PIEthernet
|
//! \~english Extra socket parameters for %PIEthernet.
|
||||||
|
//! \~russian Дополнительные параметры сокета %PIEthernet.
|
||||||
enum Parameters {
|
enum Parameters {
|
||||||
ReuseAddress /** Rebind address if there is already binded. Enabled by default */ = 0x1,
|
ReuseAddress = 0x1 /** \~english Allow rebinding an already bound address; enabled by default \~russian Разрешает повторную привязку
|
||||||
Broadcast /** Broadcast send. Disabled by default */ = 0x2,
|
уже занятого адреса; включено по умолчанию */
|
||||||
SeparateSockets /** If this parameter is set, %PIEthernet will initialize two different sockets,
|
,
|
||||||
for receive and send, instead of single one. Disabled by default */
|
Broadcast = 0x2 /** \~english Enable broadcast sending; disabled by default \~russian Включает отправку broadcast-пакетов; выключено
|
||||||
= 0x4,
|
по умолчанию */
|
||||||
MulticastLoop /** Enable receiving multicast packets from same host. Enabled by default */ = 0x8,
|
,
|
||||||
KeepConnection /** Automatic reconnect TCP connection on disconnect. Enabled by default */ = 0x10,
|
SeparateSockets = 0x4 /** \~english Use separate sockets for receiving and sending instead of a single one; disabled by default
|
||||||
DisonnectOnTimeout /** Disconnect TCP connection on read timeout expired. Disabled by default */ = 0x20,
|
\~russian Использует отдельные сокеты для приема и передачи вместо одного общего; выключено по умолчанию */
|
||||||
NoDelay /** Use NO_DELAY option. Disabled by default */ = 0x40
|
,
|
||||||
|
MulticastLoop = 0x8 /** \~english Receive multicast packets sent by the same host; enabled by default \~russian Разрешает получать
|
||||||
|
multicast-пакеты от того же хоста; включено по умолчанию */
|
||||||
|
,
|
||||||
|
KeepConnection = 0x10 /** \~english Reconnect TCP connection automatically after disconnect; enabled by default \~russian
|
||||||
|
Автоматически переподключает TCP-соединение после разрыва; включено по умолчанию */
|
||||||
|
,
|
||||||
|
DisonnectOnTimeout = 0x20 /** \~english Disconnect TCP connection when read timeout expires; disabled by default \~russian Разрывает
|
||||||
|
TCP-соединение при истечении таймаута чтения; выключено по умолчанию */
|
||||||
|
,
|
||||||
|
NoDelay = 0x40 /** \~english Enable the TCP no-delay option; disabled by default \~russian Включает опцию TCP no-delay; выключено по
|
||||||
|
умолчанию */
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Deprecated alias for \a PINetworkAddress.
|
||||||
|
//! \~russian Устаревший псевдоним для \a PINetworkAddress.
|
||||||
typedef ::PINetworkAddress Address DEPRECATEDM("use PINetworkAddress instead");
|
typedef ::PINetworkAddress Address DEPRECATEDM("use PINetworkAddress instead");
|
||||||
|
|
||||||
//! Contructs %PIEthernet with type "type", read address "ip_port" and parameters "params"
|
//! \~english Constructs a device with mode "type", read address "ip_port" and socket "params".
|
||||||
|
//! \~russian Создает устройство с режимом "type", адресом чтения "ip_port" и параметрами сокета "params".
|
||||||
explicit PIEthernet(Type type,
|
explicit PIEthernet(Type type,
|
||||||
const PIString & ip_port = PIString(),
|
const PIString & ip_port = PIString(),
|
||||||
const PIFlags<Parameters> params = PIEthernet::ReuseAddress | PIEthernet::MulticastLoop |
|
const PIFlags<Parameters> params = PIEthernet::ReuseAddress | PIEthernet::MulticastLoop |
|
||||||
PIEthernet::KeepConnection);
|
PIEthernet::KeepConnection);
|
||||||
|
|
||||||
|
//! \~english Destroys the ethernet device.
|
||||||
|
//! \~russian Уничтожает ethernet-устройство.
|
||||||
virtual ~PIEthernet();
|
virtual ~PIEthernet();
|
||||||
|
|
||||||
|
|
||||||
//! Set read address
|
//! \~english Sets the read address from IP and port.
|
||||||
|
//! \~russian Устанавливает адрес чтения по IP и порту.
|
||||||
void setReadAddress(const PIString & ip, int port) {
|
void setReadAddress(const PIString & ip, int port) {
|
||||||
addr_r.set(ip, port);
|
addr_r.set(ip, port);
|
||||||
setPath(addr_r.toString());
|
setPath(addr_r.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set read address in format "i.i.i.i:p"
|
//! \~english Sets the read address from string "i.i.i.i:p".
|
||||||
|
//! \~russian Устанавливает адрес чтения из строки "i.i.i.i:p".
|
||||||
void setReadAddress(const PIString & ip_port) {
|
void setReadAddress(const PIString & ip_port) {
|
||||||
addr_r.set(ip_port);
|
addr_r.set(ip_port);
|
||||||
setPath(addr_r.toString());
|
setPath(addr_r.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set read address
|
//! \~english Sets the read address from \a PINetworkAddress.
|
||||||
|
//! \~russian Устанавливает адрес чтения из \a PINetworkAddress.
|
||||||
void setReadAddress(const PINetworkAddress & addr) {
|
void setReadAddress(const PINetworkAddress & addr) {
|
||||||
addr_r = addr;
|
addr_r = addr;
|
||||||
setPath(addr_r.toString());
|
setPath(addr_r.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set read IP
|
//! \~english Sets only the read IP.
|
||||||
|
//! \~russian Устанавливает только IP-адрес чтения.
|
||||||
void setReadIP(const PIString & ip) {
|
void setReadIP(const PIString & ip) {
|
||||||
addr_r.setIP(ip);
|
addr_r.setIP(ip);
|
||||||
setPath(addr_r.toString());
|
setPath(addr_r.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set read port
|
//! \~english Sets only the read port.
|
||||||
|
//! \~russian Устанавливает только порт чтения.
|
||||||
void setReadPort(int port) {
|
void setReadPort(int port) {
|
||||||
addr_r.setPort(port);
|
addr_r.setPort(port);
|
||||||
setPath(addr_r.toString());
|
setPath(addr_r.toString());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! Set send address
|
//! \~english Sets the send address from IP and port.
|
||||||
|
//! \~russian Устанавливает адрес отправки по IP и порту.
|
||||||
void setSendAddress(const PIString & ip, int port) { addr_s.set(ip, port); }
|
void setSendAddress(const PIString & ip, int port) { addr_s.set(ip, port); }
|
||||||
|
|
||||||
//! Set send address in format "i.i.i.i:p"
|
//! \~english Sets the send address from string "i.i.i.i:p".
|
||||||
|
//! \~russian Устанавливает адрес отправки из строки "i.i.i.i:p".
|
||||||
void setSendAddress(const PIString & ip_port) { addr_s.set(ip_port); }
|
void setSendAddress(const PIString & ip_port) { addr_s.set(ip_port); }
|
||||||
|
|
||||||
//! Set send address
|
//! \~english Sets the send address from \a PINetworkAddress.
|
||||||
|
//! \~russian Устанавливает адрес отправки из \a PINetworkAddress.
|
||||||
void setSendAddress(const PINetworkAddress & addr) { addr_s = addr; }
|
void setSendAddress(const PINetworkAddress & addr) { addr_s = addr; }
|
||||||
|
|
||||||
//! Set send IP
|
//! \~english Sets only the send IP.
|
||||||
|
//! \~russian Устанавливает только IP-адрес отправки.
|
||||||
void setSendIP(const PIString & ip) { addr_s.setIP(ip); }
|
void setSendIP(const PIString & ip) { addr_s.setIP(ip); }
|
||||||
|
|
||||||
//! Set send port
|
//! \~english Sets only the send port.
|
||||||
|
//! \~russian Устанавливает только порт отправки.
|
||||||
void setSendPort(int port) { addr_s.setPort(port); }
|
void setSendPort(int port) { addr_s.setPort(port); }
|
||||||
|
|
||||||
|
|
||||||
//! Returns read address in format "i.i.i.i:p"
|
//! \~english Returns the current read address.
|
||||||
|
//! \~russian Возвращает текущий адрес чтения.
|
||||||
PINetworkAddress readAddress() const { return addr_r; }
|
PINetworkAddress readAddress() const { return addr_r; }
|
||||||
|
|
||||||
//! Returns read IP
|
//! \~english Returns the current read IP.
|
||||||
|
//! \~russian Возвращает текущий IP-адрес чтения.
|
||||||
PIString readIP() const { return addr_r.ipString(); }
|
PIString readIP() const { return addr_r.ipString(); }
|
||||||
|
|
||||||
//! Returns read port
|
//! \~english Returns the current read port.
|
||||||
|
//! \~russian Возвращает текущий порт чтения.
|
||||||
int readPort() const { return addr_r.port(); }
|
int readPort() const { return addr_r.port(); }
|
||||||
|
|
||||||
|
|
||||||
//! Returns send address in format "i.i.i.i:p"
|
//! \~english Returns the current send address.
|
||||||
|
//! \~russian Возвращает текущий адрес отправки.
|
||||||
PINetworkAddress sendAddress() const { return addr_s; }
|
PINetworkAddress sendAddress() const { return addr_s; }
|
||||||
|
|
||||||
//! Returns send IP
|
//! \~english Returns the current send IP.
|
||||||
|
//! \~russian Возвращает текущий IP-адрес отправки.
|
||||||
PIString sendIP() const { return addr_s.ipString(); }
|
PIString sendIP() const { return addr_s.ipString(); }
|
||||||
|
|
||||||
//! Returns send port
|
//! \~english Returns the current send port.
|
||||||
|
//! \~russian Возвращает текущий порт отправки.
|
||||||
int sendPort() const { return addr_s.port(); }
|
int sendPort() const { return addr_s.port(); }
|
||||||
|
|
||||||
|
|
||||||
//! Returns address of last received UDP packet in format "i.i.i.i:p"
|
//! \~english Returns the source address of the last received UDP packet.
|
||||||
|
//! \~russian Возвращает адрес источника последнего принятого UDP-пакета.
|
||||||
PINetworkAddress lastReadAddress() const { return addr_lr; }
|
PINetworkAddress lastReadAddress() const { return addr_lr; }
|
||||||
|
|
||||||
//! Returns IP of last received UDP packet
|
//! \~english Returns the IP of the last received UDP packet.
|
||||||
|
//! \~russian Возвращает IP-адрес последнего принятого UDP-пакета.
|
||||||
PIString lastReadIP() const { return addr_lr.ipString(); }
|
PIString lastReadIP() const { return addr_lr.ipString(); }
|
||||||
|
|
||||||
//! Returns port of last received UDP packet
|
//! \~english Returns the port of the last received UDP packet.
|
||||||
|
//! \~russian Возвращает порт последнего принятого UDP-пакета.
|
||||||
int lastReadPort() const { return addr_lr.port(); }
|
int lastReadPort() const { return addr_lr.port(); }
|
||||||
|
|
||||||
|
|
||||||
//! Set parameters to "parameters_". You should to reopen %PIEthernet to apply them
|
//! \~english Replaces all socket parameters with "parameters_".
|
||||||
|
//! \~russian Полностью заменяет параметры сокета на "parameters_".
|
||||||
|
//! \~english Some parameters may require reopening the device to take full effect.
|
||||||
|
//! \~russian Для полного применения некоторых параметров может потребоваться переоткрытие устройства.
|
||||||
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) {
|
void setParameters(PIFlags<PIEthernet::Parameters> parameters_) {
|
||||||
params = parameters_;
|
params = parameters_;
|
||||||
applyParameters();
|
applyParameters();
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Set parameter "parameter" to state "on". You should to reopen %PIEthernet to apply this
|
//! \~english Sets socket parameter "parameter" to state "on".
|
||||||
|
//! \~russian Устанавливает параметр сокета "parameter" в состояние "on".
|
||||||
|
//! \~english Some parameters may require reopening the device to take full effect.
|
||||||
|
//! \~russian Для полного применения некоторых параметров может потребоваться переоткрытие устройства.
|
||||||
void setParameter(PIEthernet::Parameters parameter, bool on = true) {
|
void setParameter(PIEthernet::Parameters parameter, bool on = true) {
|
||||||
params.setFlag(parameter, on);
|
params.setFlag(parameter, on);
|
||||||
applyParameters();
|
applyParameters();
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns if parameter "parameter" is set
|
//! \~english Returns whether parameter "parameter" is enabled.
|
||||||
|
//! \~russian Возвращает, включен ли параметр "parameter".
|
||||||
bool isParameterSet(PIEthernet::Parameters parameter) const { return params[parameter]; }
|
bool isParameterSet(PIEthernet::Parameters parameter) const { return params[parameter]; }
|
||||||
|
|
||||||
//! Returns parameters
|
//! \~english Returns current socket parameters.
|
||||||
|
//! \~russian Возвращает текущие параметры сокета.
|
||||||
PIFlags<PIEthernet::Parameters> parameters() const { return params; }
|
PIFlags<PIEthernet::Parameters> parameters() const { return params; }
|
||||||
|
|
||||||
//! Returns %PIEthernet type
|
//! \~english Returns the current ethernet mode.
|
||||||
|
//! \~russian Возвращает текущий режим ethernet-устройства.
|
||||||
Type type() const { return eth_type; }
|
Type type() const { return eth_type; }
|
||||||
|
|
||||||
//! Returns read timeout
|
//! \~english Returns the configured read timeout.
|
||||||
|
//! \~russian Возвращает настроенный таймаут чтения.
|
||||||
PISystemTime readTimeout() const { return property("readTimeout").toSystemTime(); }
|
PISystemTime readTimeout() const { return property("readTimeout").toSystemTime(); }
|
||||||
|
|
||||||
//! Returns write timeout
|
//! \~english Returns the configured write timeout.
|
||||||
|
//! \~russian Возвращает настроенный таймаут записи.
|
||||||
PISystemTime writeTimeout() const { return property("writeTimeout").toSystemTime(); }
|
PISystemTime writeTimeout() const { return property("writeTimeout").toSystemTime(); }
|
||||||
|
|
||||||
//! Set timeout for read
|
//! \~english Sets the read timeout.
|
||||||
|
//! \~russian Устанавливает таймаут чтения.
|
||||||
void setReadTimeout(PISystemTime tm);
|
void setReadTimeout(PISystemTime tm);
|
||||||
|
|
||||||
//! Set timeout for write
|
//! \~english Sets the write timeout.
|
||||||
|
//! \~russian Устанавливает таймаут записи.
|
||||||
void setWriteTimeout(PISystemTime tm);
|
void setWriteTimeout(PISystemTime tm);
|
||||||
|
|
||||||
|
|
||||||
//! Set socket receive buffer size
|
//! \~english Sets the socket receive buffer size in bytes.
|
||||||
|
//! \~russian Устанавливает размер приемного буфера сокета в байтах.
|
||||||
void setReadBufferSize(int bytes);
|
void setReadBufferSize(int bytes);
|
||||||
|
|
||||||
//! Set socket send buffer size
|
//! \~english Sets the socket send buffer size in bytes.
|
||||||
|
//! \~russian Устанавливает размер буфера передачи сокета в байтах.
|
||||||
void setWriteBufferSize(int bytes);
|
void setWriteBufferSize(int bytes);
|
||||||
|
|
||||||
|
|
||||||
//! Returns TTL (Time To Live)
|
//! \~english Returns the IP packet TTL.
|
||||||
|
//! \~russian Возвращает TTL IP-пакетов.
|
||||||
int TTL() const { return property("TTL").toInt(); }
|
int TTL() const { return property("TTL").toInt(); }
|
||||||
|
|
||||||
//! Returns multicast TTL (Time To Live)
|
//! \~english Returns the multicast TTL.
|
||||||
|
//! \~russian Возвращает TTL multicast-пакетов.
|
||||||
int multicastTTL() const { return property("MulticastTTL").toInt(); }
|
int multicastTTL() const { return property("MulticastTTL").toInt(); }
|
||||||
|
|
||||||
//! Set TTL (Time To Live), default is 64
|
//! \~english Sets the IP packet TTL, default is 64.
|
||||||
|
//! \~russian Устанавливает TTL IP-пакетов, по умолчанию 64.
|
||||||
void setTTL(int ttl) { setProperty("TTL", ttl); }
|
void setTTL(int ttl) { setProperty("TTL", ttl); }
|
||||||
|
|
||||||
//! Set multicast TTL (Time To Live), default is 1
|
//! \~english Sets the multicast TTL, default is 1.
|
||||||
|
//! \~russian Устанавливает TTL multicast-пакетов, по умолчанию 1.
|
||||||
void setMulticastTTL(int ttl) { setProperty("MulticastTTL", ttl); }
|
void setMulticastTTL(int ttl) { setProperty("MulticastTTL", ttl); }
|
||||||
|
|
||||||
|
|
||||||
//! Join to multicast group with address "group". Use only for UDP
|
//! \~english Joins multicast group "group". Use only with \a UDP.
|
||||||
|
//! \~russian Подключается к multicast-группе "group". Используйте только с \a UDP.
|
||||||
bool joinMulticastGroup(const PIString & group);
|
bool joinMulticastGroup(const PIString & group);
|
||||||
|
|
||||||
//! Leave multicast group with address "group". Use only for UDP
|
//! \~english Leaves multicast group "group". Use only with \a UDP.
|
||||||
|
//! \~russian Покидает multicast-группу "group". Используйте только с \a UDP.
|
||||||
bool leaveMulticastGroup(const PIString & group);
|
bool leaveMulticastGroup(const PIString & group);
|
||||||
|
|
||||||
//! Returns joined multicast groups. Use only for UDP
|
//! \~english Returns joined multicast groups. Use only with \a UDP.
|
||||||
|
//! \~russian Возвращает список подключенных multicast-групп. Используйте только с \a UDP.
|
||||||
const PIStringList & multicastGroups() const { return mcast_groups; }
|
const PIStringList & multicastGroups() const { return mcast_groups; }
|
||||||
|
|
||||||
|
|
||||||
//! If \"threaded\" queue connect to TCP server with address \a readAddress() in
|
//! \~english Connects to the TCP server at \a readAddress().
|
||||||
//! any \a read() or \a write() call. Otherwise connect immediate.
|
//! \~russian Подключается к TCP-серверу по адресу \a readAddress().
|
||||||
//! Use only for TCP_Client
|
//! \~\details
|
||||||
|
//! \~english If "threaded" is true, connection is queued and completed from subsequent \a read() or \a write() calls.
|
||||||
|
//! \~russian Если "threaded" равно true, подключение ставится в очередь и завершается из последующих вызовов \a read() или \a write().
|
||||||
bool connect(bool threaded = true);
|
bool connect(bool threaded = true);
|
||||||
|
|
||||||
//! Connect to TCP server with address "ip":"port". Use only for TCP_Client
|
//! \~english Connects to the TCP server at "ip":"port".
|
||||||
|
//! \~russian Подключается к TCP-серверу по адресу "ip":"port".
|
||||||
bool connect(const PIString & ip, int port, bool threaded = true) {
|
bool connect(const PIString & ip, int port, bool threaded = true) {
|
||||||
setPath(ip + PIStringAscii(":") + PIString::fromNumber(port));
|
setPath(ip + PIStringAscii(":") + PIString::fromNumber(port));
|
||||||
return connect(threaded);
|
return connect(threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Connect to TCP server with address "ip_port". Use only for TCP_Client
|
//! \~english Connects to the TCP server at "ip_port".
|
||||||
|
//! \~russian Подключается к TCP-серверу по адресу "ip_port".
|
||||||
bool connect(const PIString & ip_port, bool threaded = true) {
|
bool connect(const PIString & ip_port, bool threaded = true) {
|
||||||
setPath(ip_port);
|
setPath(ip_port);
|
||||||
return connect(threaded);
|
return connect(threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Connect to TCP server with address "addr". Use only for TCP_Client
|
//! \~english Connects to the TCP server at "addr". Use only for TCP_Client
|
||||||
|
//! \~russian Подключается к TCP-серверу по адресу "addr". Только для TCP_Client
|
||||||
bool connect(const PINetworkAddress & addr, bool threaded = true) {
|
bool connect(const PINetworkAddress & addr, bool threaded = true) {
|
||||||
setPath(addr.toString());
|
setPath(addr.toString());
|
||||||
return connect(threaded);
|
return connect(threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Returns if %PIEthernet connected to TCP server. Use only for TCP_Client
|
//! \~english Returns whether the TCP client is connected. Use only for TCP_Client
|
||||||
|
//! \~russian Возвращает, подключен ли TCP-клиент. Только для TCP_Client
|
||||||
bool isConnected() const { return connected_; }
|
bool isConnected() const { return connected_; }
|
||||||
|
|
||||||
//! Returns if %PIEthernet is connecting to TCP server. Use only for TCP_Client
|
//! \~english Returns whether the TCP client is currently connecting. Use only for TCP_Client
|
||||||
|
//! \~russian Возвращает, выполняется ли сейчас подключение TCP-клиента. Только для TCP_Client
|
||||||
bool isConnecting() const { return connecting_; }
|
bool isConnecting() const { return connecting_; }
|
||||||
|
|
||||||
|
|
||||||
//! Start listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
|
//! \~english Starts listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
|
||||||
|
//! \~russian Начинает прослушивание входящих TCP подключений на адресе \a readAddress(). Только для TCP_Server
|
||||||
bool listen(bool threaded = false);
|
bool listen(bool threaded = false);
|
||||||
|
|
||||||
//! Start listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
|
//! \~english Starts listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
|
||||||
|
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "ip":"port". Только для TCP_Server
|
||||||
bool listen(const PIString & ip, int port, bool threaded = false) { return listen(PINetworkAddress(ip, port), threaded); }
|
bool listen(const PIString & ip, int port, bool threaded = false) { return listen(PINetworkAddress(ip, port), threaded); }
|
||||||
|
|
||||||
//! Start listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
|
//! \~english Starts listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
|
||||||
|
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "ip_port". Только для TCP_Server
|
||||||
bool listen(const PIString & ip_port, bool threaded = false) { return listen(PINetworkAddress(ip_port), threaded); }
|
bool listen(const PIString & ip_port, bool threaded = false) { return listen(PINetworkAddress(ip_port), threaded); }
|
||||||
|
|
||||||
//! Start listen for incoming TCP connections on address "addr". Use only for TCP_Server
|
//! \~english Starts listen for incoming TCP connections on address "addr". Use only for TCP_Server
|
||||||
|
//! \~russian Начинает прослушивание входящих TCP подключений на адресе "addr". Только для TCP_Server
|
||||||
bool listen(const PINetworkAddress & addr, bool threaded = false);
|
bool listen(const PINetworkAddress & addr, bool threaded = false);
|
||||||
|
|
||||||
|
//! \~english Stops the background listen loop started with threaded listening.
|
||||||
|
//! \~russian Останавливает фоновый цикл прослушивания, запущенный в потоковом режиме.
|
||||||
void stopThreadedListen();
|
void stopThreadedListen();
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns accepted TCP client by index.
|
||||||
|
//! \~russian Возвращает принятый TCP-клиент по индексу.
|
||||||
PIEthernet * client(int index);
|
PIEthernet * client(int index);
|
||||||
|
|
||||||
|
//! \~english Returns the number of accepted TCP clients.
|
||||||
|
//! \~russian Возвращает количество принятых TCP-клиентов.
|
||||||
int clientsCount() const;
|
int clientsCount() const;
|
||||||
|
|
||||||
|
//! \~english Returns all accepted TCP clients.
|
||||||
|
//! \~russian Возвращает всех принятых TCP-клиентов.
|
||||||
PIVector<PIEthernet *> clients() const;
|
PIVector<PIEthernet *> clients() const;
|
||||||
|
|
||||||
|
|
||||||
//! Send data "data" with size "size" to address \a sendAddress() for UDP or \a readAddress() for TCP_Client
|
//! \~english Sends raw buffer "data" of size "size".
|
||||||
|
//! \~russian Отправляет сырой буфер "data" размером "size".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english For \a UDP it uses \a sendAddress(), for \a TCP_Client it sends through the connected peer.
|
||||||
|
//! \~russian Для \a UDP использует \a sendAddress(), для \a TCP_Client отправляет данные через подключенного пира.
|
||||||
bool send(const void * data, int size, bool threaded = false);
|
bool send(const void * data, int size, bool threaded = false);
|
||||||
|
|
||||||
//! Send data "data" with size "size" to address "ip":"port"
|
//! \~english Sends raw buffer "data" to address "ip":"port".
|
||||||
|
//! \~russian Отправляет сырой буфер "data" по адресу "ip":"port".
|
||||||
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {
|
bool send(const PIString & ip, int port, const void * data, int size, bool threaded = false) {
|
||||||
return send(PINetworkAddress(ip, port), data, size, threaded);
|
return send(PINetworkAddress(ip, port), data, size, threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Send data "data" with size "size" to address "ip_port"
|
//! \~english Sends raw buffer "data" to address "ip_port".
|
||||||
|
//! \~russian Отправляет сырой буфер "data" по адресу "ip_port".
|
||||||
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {
|
bool send(const PIString & ip_port, const void * data, int size, bool threaded = false) {
|
||||||
return send(PINetworkAddress(ip_port), data, size, threaded);
|
return send(PINetworkAddress(ip_port), data, size, threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Send data "data" with size "size" to address "addr"
|
//! \~english Sends raw buffer "data" to address "addr".
|
||||||
|
//! \~russian Отправляет сырой буфер "data" по адресу "addr".
|
||||||
bool send(const PINetworkAddress & addr, const void * data, int size, bool threaded = false);
|
bool send(const PINetworkAddress & addr, const void * data, int size, bool threaded = false);
|
||||||
|
|
||||||
//! Send data "data" to address \a sendAddress() for UDP or \a readAddress() for TCP_Client
|
//! \~english Sends byte array "data" using the default destination.
|
||||||
|
//! \~russian Отправляет массив байт "data" по адресу назначения по умолчанию.
|
||||||
bool send(const PIByteArray & data, bool threaded = false);
|
bool send(const PIByteArray & data, bool threaded = false);
|
||||||
|
|
||||||
//! Send data "data" to address "ip":"port" for UDP
|
//! \~english Sends byte array "data" to address "ip":"port".
|
||||||
|
//! \~russian Отправляет массив байт "data" по адресу "ip":"port".
|
||||||
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {
|
bool send(const PIString & ip, int port, const PIByteArray & data, bool threaded = false) {
|
||||||
return send(PINetworkAddress(ip, port), data, threaded);
|
return send(PINetworkAddress(ip, port), data, threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Send data "data" to address "ip_port" for UDP
|
//! \~english Sends byte array "data" to address "ip_port".
|
||||||
|
//! \~russian Отправляет массив байт "data" по адресу "ip_port".
|
||||||
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {
|
bool send(const PIString & ip_port, const PIByteArray & data, bool threaded = false) {
|
||||||
return send(PINetworkAddress(ip_port), data, threaded);
|
return send(PINetworkAddress(ip_port), data, threaded);
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Send data "data" to address "addr" for UDP
|
//! \~english Sends byte array "data" to address "addr".
|
||||||
|
//! \~russian Отправляет массив байт "data" по адресу "addr".
|
||||||
bool send(const PINetworkAddress & addr, const PIByteArray & data, bool threaded = false);
|
bool send(const PINetworkAddress & addr, const PIByteArray & data, bool threaded = false);
|
||||||
|
|
||||||
|
//! \~english Returns whether writing is currently allowed.
|
||||||
|
//! \~russian Возвращает, разрешена ли сейчас запись.
|
||||||
bool canWrite() const override { return mode() & WriteOnly; }
|
bool canWrite() const override { return mode() & WriteOnly; }
|
||||||
|
|
||||||
|
//! \~english Interrupts a blocking socket operation.
|
||||||
|
//! \~russian Прерывает блокирующую операцию сокета.
|
||||||
void interrupt() override;
|
void interrupt() override;
|
||||||
|
|
||||||
|
//! \~english Returns the underlying native socket descriptor.
|
||||||
|
//! \~russian Возвращает дескриптор нативного сокета.
|
||||||
int socket() const { return sock; }
|
int socket() const { return sock; }
|
||||||
|
|
||||||
EVENT1(newConnection, PIEthernet *, client);
|
|
||||||
EVENT0(connected);
|
|
||||||
EVENT1(disconnected, bool, withError);
|
|
||||||
|
|
||||||
|
//! \~english Flags describing a network interface.
|
||||||
//! Flags of network interface
|
//! \~russian Флаги, описывающие сетевой интерфейс.
|
||||||
enum InterfaceFlag {
|
enum InterfaceFlag {
|
||||||
ifActive /** Is active */ = 0x1,
|
ifActive = 0x1 /** \~english Interface is active \~russian Интерфейс активен */,
|
||||||
ifRunning /** Is running */ = 0x2,
|
ifRunning = 0x2 /** \~english Interface is running \~russian Интерфейс работает */,
|
||||||
ifBroadcast /** Support broadcast */ = 0x4,
|
ifBroadcast = 0x4 /** \~english Interface supports broadcast \~russian Интерфейс поддерживает broadcast */,
|
||||||
ifMulticast /** Support multicast */ = 0x8,
|
ifMulticast = 0x8 /** \~english Interface supports multicast \~russian Интерфейс поддерживает multicast */,
|
||||||
ifLoopback /** Is loopback */ = 0x10,
|
ifLoopback = 0x10 /** \~english Interface is loopback \~russian Интерфейс является loopback */,
|
||||||
ifPTP /** Is point-to-point */ = 0x20
|
ifPTP = 0x20 /** \~english Interface is point-to-point \~russian Интерфейс работает в режиме point-to-point */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! %PIFlags of network interface flags
|
//! \~english Bitmask of \a InterfaceFlag values.
|
||||||
|
//! \~russian Битовая маска значений \a InterfaceFlag.
|
||||||
typedef PIFlags<InterfaceFlag> InterfaceFlags;
|
typedef PIFlags<InterfaceFlag> InterfaceFlags;
|
||||||
|
|
||||||
|
|
||||||
//! Network interface descriptor
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Public descriptor of a system network interface.
|
||||||
|
//! \~russian Публичное описание системного сетевого интерфейса.
|
||||||
struct PIP_EXPORT Interface {
|
struct PIP_EXPORT Interface {
|
||||||
//! System index
|
//! \~english System interface index.
|
||||||
|
//! \~russian Системный индекс интерфейса.
|
||||||
int index = -1;
|
int index = -1;
|
||||||
|
|
||||||
//! MTU
|
//! \~english Interface MTU.
|
||||||
|
//! \~russian MTU интерфейса.
|
||||||
int mtu = 0;
|
int mtu = 0;
|
||||||
|
|
||||||
//! System name
|
//! \~english System interface name.
|
||||||
|
//! \~russian Системное имя интерфейса.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
//! MAC address in format "hh:hh:hh:hh:hh:hh" or empty if there is no MAC address
|
//! \~english MAC address in format "hh:hh:hh:hh:hh:hh", or empty if unavailable.
|
||||||
|
//! \~russian MAC-адрес в формате "hh:hh:hh:hh:hh:hh", либо пустая строка если он недоступен.
|
||||||
PIString mac;
|
PIString mac;
|
||||||
|
|
||||||
//! IP address in format "i.i.i.i" or empty if there is no IP address
|
//! \~english IPv4 address in format "i.i.i.i", or empty if unavailable.
|
||||||
|
//! \~russian IPv4-адрес в формате "i.i.i.i", либо пустая строка если он недоступен.
|
||||||
PIString address;
|
PIString address;
|
||||||
|
|
||||||
//! Netmask of IP address in format "i.i.i.i" or empty if there is no netmask
|
//! \~english Netmask in format "i.i.i.i", or empty if unavailable.
|
||||||
|
//! \~russian Маска сети в формате "i.i.i.i", либо пустая строка если она недоступна.
|
||||||
PIString netmask;
|
PIString netmask;
|
||||||
|
|
||||||
//! Broadcast address in format "i.i.i.i" or empty if there is no broadcast address
|
//! \~english Broadcast address in format "i.i.i.i", or empty if unavailable.
|
||||||
|
//! \~russian Broadcast-адрес в формате "i.i.i.i", либо пустая строка если он недоступен.
|
||||||
PIString broadcast;
|
PIString broadcast;
|
||||||
|
|
||||||
//! Point-to-point address or empty if there is no point-to-point address
|
//! \~english Point-to-point peer address, or empty if unavailable.
|
||||||
|
//! \~russian Адрес point-to-point-пира, либо пустая строка если он недоступен.
|
||||||
PIString ptp;
|
PIString ptp;
|
||||||
|
|
||||||
//! Flags of interface
|
//! \~english Interface capability flags.
|
||||||
|
//! \~russian Флаги возможностей интерфейса.
|
||||||
InterfaceFlags flags;
|
InterfaceFlags flags;
|
||||||
|
|
||||||
//! Returns if interface is active
|
//! \~english Returns whether the descriptor contains a valid interface.
|
||||||
|
//! \~russian Возвращает, содержит ли описание валидный интерфейс.
|
||||||
bool isValid() const { return name.isNotEmpty(); }
|
bool isValid() const { return name.isNotEmpty(); }
|
||||||
|
|
||||||
//! Returns if interface is active
|
//! \~english Returns whether the interface is active.
|
||||||
|
//! \~russian Возвращает, активен ли интерфейс.
|
||||||
bool isActive() const { return flags[PIEthernet::ifActive]; }
|
bool isActive() const { return flags[PIEthernet::ifActive]; }
|
||||||
|
|
||||||
//! Returns if interface is running
|
//! \~english Returns whether the interface is running.
|
||||||
|
//! \~russian Возвращает, работает ли интерфейс.
|
||||||
bool isRunning() const { return flags[PIEthernet::ifRunning]; }
|
bool isRunning() const { return flags[PIEthernet::ifRunning]; }
|
||||||
|
|
||||||
//! Returns if interface support broadcast
|
//! \~english Returns whether broadcast is supported.
|
||||||
|
//! \~russian Возвращает, поддерживается ли broadcast.
|
||||||
bool isBroadcast() const { return flags[PIEthernet::ifBroadcast]; }
|
bool isBroadcast() const { return flags[PIEthernet::ifBroadcast]; }
|
||||||
|
|
||||||
//! Returns if interface support multicast
|
//! \~english Returns whether multicast is supported.
|
||||||
|
//! \~russian Возвращает, поддерживается ли multicast.
|
||||||
bool isMulticast() const { return flags[PIEthernet::ifMulticast]; }
|
bool isMulticast() const { return flags[PIEthernet::ifMulticast]; }
|
||||||
|
|
||||||
//! Returns if interface is loopback
|
//! \~english Returns whether the interface is loopback.
|
||||||
|
//! \~russian Возвращает, является ли интерфейс loopback.
|
||||||
bool isLoopback() const { return flags[PIEthernet::ifLoopback]; }
|
bool isLoopback() const { return flags[PIEthernet::ifLoopback]; }
|
||||||
|
|
||||||
//! Returns if interface is point-to-point
|
//! \~english Returns whether the interface is point-to-point.
|
||||||
|
//! \~russian Возвращает, работает ли интерфейс в режиме point-to-point.
|
||||||
bool isPTP() const { return flags[PIEthernet::ifPTP]; }
|
bool isPTP() const { return flags[PIEthernet::ifPTP]; }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! Array of \a Interface with some features
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Collection of \a Interface descriptors with lookup helpers.
|
||||||
|
//! \~russian Коллекция описаний \a Interface с методами поиска.
|
||||||
class PIP_EXPORT InterfaceList: public PIVector<PIEthernet::Interface> {
|
class PIP_EXPORT InterfaceList: public PIVector<PIEthernet::Interface> {
|
||||||
public:
|
public:
|
||||||
InterfaceList(): PIVector<PIEthernet::Interface>() {}
|
InterfaceList(): PIVector<PIEthernet::Interface>() {}
|
||||||
|
|
||||||
//! Get interface with system index "index" or 0 if there is no one
|
//! \~english Returns interface with system index "index", or 0 if absent.
|
||||||
|
//! \~russian Возвращает интерфейс с системным индексом "index", либо 0 если он не найден.
|
||||||
const Interface * getByIndex(int index) const {
|
const Interface * getByIndex(int index) const {
|
||||||
for (int i = 0; i < size_s(); ++i)
|
for (int i = 0; i < size_s(); ++i)
|
||||||
if ((*this)[i].index == index) return &((*this)[i]);
|
if ((*this)[i].index == index) return &((*this)[i]);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Get interface with system name "name" or 0 if there is no one
|
//! \~english Returns interface with system name "name", or 0 if absent.
|
||||||
|
//! \~russian Возвращает интерфейс с системным именем "name", либо 0 если он не найден.
|
||||||
const Interface * getByName(const PIString & name) const {
|
const Interface * getByName(const PIString & name) const {
|
||||||
for (int i = 0; i < size_s(); ++i)
|
for (int i = 0; i < size_s(); ++i)
|
||||||
if ((*this)[i].name == name) return &((*this)[i]);
|
if ((*this)[i].name == name) return &((*this)[i]);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Get interface with IP address "address" or 0 if there is no one
|
//! \~english Returns interface with IP address "address", or 0 if absent.
|
||||||
|
//! \~russian Возвращает интерфейс с IP-адресом "address", либо 0 если он не найден.
|
||||||
const Interface * getByAddress(const PIString & address) const {
|
const Interface * getByAddress(const PIString & address) const {
|
||||||
for (int i = 0; i < size_s(); ++i)
|
for (int i = 0; i < size_s(); ++i)
|
||||||
if ((*this)[i].address == address) return &((*this)[i]);
|
if ((*this)[i].address == address) return &((*this)[i]);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! Get loopback interface or 0 if there is no one
|
//! \~english Returns the loopback interface, or 0 if absent.
|
||||||
|
//! \~russian Возвращает loopback-интерфейс, либо 0 если он не найден.
|
||||||
const Interface * getLoopback() const {
|
const Interface * getLoopback() const {
|
||||||
for (int i = 0; i < size_s(); ++i)
|
for (int i = 0; i < size_s(); ++i)
|
||||||
if ((*this)[i].isLoopback()) return &((*this)[i]);
|
if ((*this)[i].isLoopback()) return &((*this)[i]);
|
||||||
@@ -409,57 +535,94 @@ public:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! Returns all system network interfaces
|
//! \~english Returns all detected system network interfaces.
|
||||||
|
//! \~russian Возвращает все обнаруженные системные сетевые интерфейсы.
|
||||||
static InterfaceList interfaces();
|
static InterfaceList interfaces();
|
||||||
|
|
||||||
|
//! \~english Returns the address currently assigned to interface "interface_".
|
||||||
|
//! \~russian Возвращает адрес, назначенный интерфейсу "interface_".
|
||||||
static PINetworkAddress interfaceAddress(const PIString & interface_);
|
static PINetworkAddress interfaceAddress(const PIString & interface_);
|
||||||
|
|
||||||
//! Returns all system network IP addresses
|
//! \~english Returns all detected system IP addresses.
|
||||||
|
//! \~russian Возвращает все обнаруженные системные IP-адреса.
|
||||||
static PIVector<PINetworkAddress> allAddresses();
|
static PIVector<PINetworkAddress> allAddresses();
|
||||||
|
|
||||||
|
//! \~english Converts a MAC address byte array to text form.
|
||||||
|
//! \~russian Преобразует массив байт MAC-адреса в текстовый вид.
|
||||||
static PIString macFromBytes(const PIByteArray & mac);
|
static PIString macFromBytes(const PIByteArray & mac);
|
||||||
|
|
||||||
|
//! \~english Converts a textual MAC address to bytes.
|
||||||
|
//! \~russian Преобразует текстовый MAC-адрес в массив байт.
|
||||||
static PIByteArray macToBytes(const PIString & mac);
|
static PIByteArray macToBytes(const PIString & mac);
|
||||||
|
|
||||||
|
//! \~english Applies network mask "mask" to IPv4 string "ip".
|
||||||
|
//! \~russian Применяет сетевую маску "mask" к строковому IPv4-адресу "ip".
|
||||||
static PIString applyMask(const PIString & ip, const PIString & mask);
|
static PIString applyMask(const PIString & ip, const PIString & mask);
|
||||||
|
|
||||||
|
//! \~english Applies network mask "mask" to address "ip".
|
||||||
|
//! \~russian Применяет сетевую маску "mask" к адресу "ip".
|
||||||
static PINetworkAddress applyMask(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
static PINetworkAddress applyMask(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
||||||
|
|
||||||
|
//! \~english Calculates broadcast address from IPv4 string and mask.
|
||||||
|
//! \~russian Вычисляет broadcast-адрес по строковому IPv4-адресу и маске.
|
||||||
static PIString getBroadcast(const PIString & ip, const PIString & mask);
|
static PIString getBroadcast(const PIString & ip, const PIString & mask);
|
||||||
|
|
||||||
|
//! \~english Calculates broadcast address from address and mask.
|
||||||
|
//! \~russian Вычисляет broadcast-адрес по адресу и маске.
|
||||||
static PINetworkAddress getBroadcast(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
static PINetworkAddress getBroadcast(const PINetworkAddress & ip, const PINetworkAddress & mask);
|
||||||
|
|
||||||
|
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void newConnection(PIEthernet * client)
|
//! \fn void newConnection(PIEthernet * client)
|
||||||
//! \brief Raise on new TCP connection received
|
//! \~english Raised when a new TCP client connection is accepted.
|
||||||
|
//! \~russian Вызывается при принятии нового TCP-клиентского соединения.
|
||||||
|
EVENT1(newConnection, PIEthernet *, client);
|
||||||
|
|
||||||
//! \fn void connected()
|
//! \fn void connected()
|
||||||
//! \brief Raise if succesfull TCP connection
|
//! \~english Raised after a successful TCP client connection.
|
||||||
|
//! \~russian Вызывается после успешного подключения TCP-клиента.
|
||||||
|
EVENT0(connected);
|
||||||
|
|
||||||
//! \fn void disconnected(bool withError)
|
//! \fn void disconnected(bool withError)
|
||||||
//! \brief Raise if TCP connection was closed
|
//! \~english Raised when the TCP connection is closed.
|
||||||
|
//! \~russian Вызывается при закрытии TCP-соединения.
|
||||||
|
EVENT1(disconnected, bool, withError);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \ioparams
|
//! \ioparams
|
||||||
//! \{
|
//! \{
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
//! \brief read ip, default ""
|
|
||||||
|
//! \~english Read IP address, default ""
|
||||||
|
//! \~russian IP-адрес чтения, по умолчанию ""
|
||||||
string ip;
|
string ip;
|
||||||
|
|
||||||
//! \brief read port, default 0
|
//! \~english Read port, default 0
|
||||||
|
//! \~russian Порт чтения, по умолчанию 0
|
||||||
int port;
|
int port;
|
||||||
|
|
||||||
//! \brief ethernet parameters
|
//! \~english Bitmask of \a Parameters values
|
||||||
|
//! \~russian Битовая маска значений \a Parameters
|
||||||
int parameters;
|
int parameters;
|
||||||
|
|
||||||
//! \brief read timeout, default 10 s
|
//! \~english Read timeout, default 10 s
|
||||||
|
//! \~russian Таймаут чтения, по умолчанию 10 с
|
||||||
PISystemTime readTimeout;
|
PISystemTime readTimeout;
|
||||||
|
|
||||||
//! \brief write timeout, default 10 s
|
//! \~english Write timeout, default 10 s
|
||||||
|
//! \~russian Таймаут записи, по умолчанию 10 с
|
||||||
PISystemTime writeTimeout;
|
PISystemTime writeTimeout;
|
||||||
|
|
||||||
//! \brief time-to-live, default 64
|
//! \~english IP packet TTL, default 64
|
||||||
|
//! \~russian TTL IP-пакетов, по умолчанию 64
|
||||||
int TTL;
|
int TTL;
|
||||||
|
|
||||||
//! \brief time-to-live for multicast, default 1
|
//! \~english Multicast TTL, default 1
|
||||||
|
//! \~russian TTL multicast-пакетов, по умолчанию 1
|
||||||
int multicastTTL;
|
int multicastTTL;
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
@@ -478,7 +641,11 @@ protected:
|
|||||||
DeviceInfoFlags deviceInfoFlags() const override;
|
DeviceInfoFlags deviceInfoFlags() const override;
|
||||||
void applyParameters();
|
void applyParameters();
|
||||||
|
|
||||||
//! Executes when any read function was successful. Default implementation does nothing
|
//! \~english Called after any successful receive operation.
|
||||||
|
//! \~russian Вызывается после любой успешной операции приема.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Default implementation does nothing.
|
||||||
|
//! \~russian Реализация по умолчанию ничего не делает.
|
||||||
virtual void received(const void * data, int size) { ; }
|
virtual void received(const void * data, int size) { ; }
|
||||||
|
|
||||||
void construct();
|
void construct();
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
/*! \file pifile.h
|
//! \~\ingroup IO
|
||||||
* \ingroup IO
|
//! \~\{
|
||||||
* \~\brief
|
//! \~\file pifile.h
|
||||||
* \~english Local file
|
//! \~\brief
|
||||||
* \~russian Локальный файл
|
//! \~english Local file
|
||||||
*/
|
//! \~russian Локальный файл
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
File
|
File
|
||||||
@@ -30,40 +31,47 @@
|
|||||||
#include "pipropertystorage.h"
|
#include "pipropertystorage.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Local file.
|
//! \~english Local file.
|
||||||
//! \~russian Локальный файл.
|
//! \~russian Локальный файл.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english PIFile provides interface for local file operations including reading, writing, seeking, and file management.
|
||||||
|
//! \~russian PIFile предоставляет интерфейс для операций с локальными файлами, включая чтение, запись, позиционирование и управление
|
||||||
|
//! файлами.
|
||||||
class PIP_EXPORT PIFile: public PIIODevice {
|
class PIP_EXPORT PIFile: public PIIODevice {
|
||||||
PIIODEVICE(PIFile, "file");
|
PIIODEVICE(PIFile, "file");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs file with empty path
|
//! \~english Constructs file with empty path.
|
||||||
//! \~russian Создает файл с пустым путём
|
//! \~russian Создает файл с пустым путём.
|
||||||
explicit PIFile();
|
explicit PIFile();
|
||||||
|
|
||||||
//! \~english Constructs a file with path "path" and open mode "mode". Open if "path" is not empty
|
//! \~english Constructs a file with path "path" and open mode "mode". Opens if "path" is not empty.
|
||||||
//! \~russian Создает файл с путём "path" и режимом открытия "mode". Открывает если "path" не пустой
|
//! \~russian Создает файл с путём "path" и режимом открытия "mode". Открывает если "path" не пустой.
|
||||||
explicit PIFile(const PIString & path, DeviceMode mode = ReadWrite);
|
explicit PIFile(const PIString & path, DeviceMode mode = ReadWrite);
|
||||||
|
|
||||||
virtual ~PIFile();
|
virtual ~PIFile();
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Local file or directory information.
|
//! \~english Local file or directory information.
|
||||||
//! \~russian Информация о локальном файле или директории.
|
//! \~russian Информация о локальном файле или директории.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Contains detailed information about a file or directory including path, size, permissions, timestamps, and flags.
|
||||||
|
//! \~russian Содержит подробную информацию о файле или директории, включая путь, размер, разрешения, временные метки и флаги.
|
||||||
struct PIP_EXPORT FileInfo {
|
struct PIP_EXPORT FileInfo {
|
||||||
//! \~english Constructs %FileInfo with path "path_". No information gathered
|
//! \~english Constructs %FileInfo with path "path_". No information gathered.
|
||||||
//! \~russian Создает %FileInfo с путём "path_". Информация не собирается
|
//! \~russian Создает %FileInfo с путём "path_". Информация не собирается.
|
||||||
FileInfo(const PIString & path_ = PIString()) {
|
FileInfo(const PIString & path_ = PIString()) {
|
||||||
path = path_;
|
path = path_;
|
||||||
size = 0;
|
size = 0;
|
||||||
id_group = id_user = 0;
|
id_group = id_user = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Type flags
|
//! \~english Type flags.
|
||||||
//! \~russian Флаги типа
|
//! \~russian Флаги типа.
|
||||||
enum Flag {
|
enum Flag {
|
||||||
File /*! \~english File \~russian Файл */ = 0x01,
|
File /*! \~english File \~russian Файл */ = 0x01,
|
||||||
Dir /*! \~english Directory \~russian Директория */ = 0x02,
|
Dir /*! \~english Directory \~russian Директория */ = 0x02,
|
||||||
@@ -74,10 +82,13 @@ public:
|
|||||||
};
|
};
|
||||||
typedef PIFlags<FileInfo::Flag> Flags;
|
typedef PIFlags<FileInfo::Flag> Flags;
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Local file or directory permissions.
|
//! \~english Local file or directory permissions.
|
||||||
//! \~russian Разрешения локального файла или директории.
|
//! \~russian Разрешения локального файла или директории.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Contains read, write, and execute permissions for user, group, and others.
|
||||||
|
//! \~russian Содержит разрешения на чтение, запись и выполнение для пользователя, группы и остальных.
|
||||||
struct PIP_EXPORT Permissions {
|
struct PIP_EXPORT Permissions {
|
||||||
Permissions(uchar r = 0): raw(r) {}
|
Permissions(uchar r = 0): raw(r) {}
|
||||||
Permissions(bool r, bool w, bool e): raw(0) {
|
Permissions(bool r, bool w, bool e): raw(0) {
|
||||||
@@ -86,12 +97,12 @@ public:
|
|||||||
exec = e;
|
exec = e;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns as string (from "---" to "rwx")
|
//! \~english Returns as string (from "---" to "rwx").
|
||||||
//! \~russian Возвращает как строку (от "---" до "rwx")
|
//! \~russian Возвращает как строку (от "---" до "rwx").
|
||||||
PIString toString() const { return PIString(read ? "r" : "-") + PIString(write ? "w" : "-") + PIString(exec ? "x" : "-"); }
|
PIString toString() const { return PIString(read ? "r" : "-") + PIString(write ? "w" : "-") + PIString(exec ? "x" : "-"); }
|
||||||
|
|
||||||
//! \~english Convertion to \c int
|
//! \~english Conversion to \c int.
|
||||||
//! \~russian Преобразование в \c int
|
//! \~russian Преобразование в \c int.
|
||||||
operator int() const { return raw; }
|
operator int() const { return raw; }
|
||||||
Permissions & operator=(int v) {
|
Permissions & operator=(int v) {
|
||||||
raw = v;
|
raw = v;
|
||||||
@@ -107,219 +118,224 @@ public:
|
|||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Path
|
//! \~english Path.
|
||||||
//! \~russian Путь
|
//! \~russian Путь.
|
||||||
PIString path;
|
PIString path;
|
||||||
|
|
||||||
//! \~english File size
|
//! \~english File size.
|
||||||
//! \~russian Размер файла
|
//! \~russian Размер файла.
|
||||||
llong size;
|
llong size;
|
||||||
|
|
||||||
//! \~english Last access time
|
//! \~english Last access time.
|
||||||
//! \~russian Время последнего доступа
|
//! \~russian Время последнего доступа.
|
||||||
PIDateTime time_access;
|
PIDateTime time_access;
|
||||||
|
|
||||||
//! \~english Last modification time
|
//! \~english Last modification time.
|
||||||
//! \~russian Время последнего изменения
|
//! \~russian Время последнего изменения.
|
||||||
PIDateTime time_modification;
|
PIDateTime time_modification;
|
||||||
|
|
||||||
//! \~english Flags
|
//! \~english Flags.
|
||||||
//! \~russian Флаги
|
//! \~russian Флаги.
|
||||||
Flags flags;
|
Flags flags;
|
||||||
|
|
||||||
//! \~english User ID
|
//! \~english User ID.
|
||||||
//! \~russian ID пользователя
|
//! \~russian ID пользователя.
|
||||||
uint id_user;
|
uint id_user;
|
||||||
|
|
||||||
//! \~english Group ID
|
//! \~english Group ID.
|
||||||
//! \~russian ID группы
|
//! \~russian ID группы.
|
||||||
uint id_group;
|
uint id_group;
|
||||||
|
|
||||||
//! \~english Permissions for user
|
//! \~english Permissions for user.
|
||||||
//! \~russian Разрешения для пользователя
|
//! \~russian Разрешения для пользователя.
|
||||||
Permissions perm_user;
|
Permissions perm_user;
|
||||||
|
|
||||||
//! \~english Permissions for group
|
//! \~english Permissions for group.
|
||||||
//! \~russian Разрешения для группы
|
//! \~russian Разрешения для группы.
|
||||||
Permissions perm_group;
|
Permissions perm_group;
|
||||||
|
|
||||||
//! \~english Permissions for other
|
//! \~english Permissions for other.
|
||||||
//! \~russian Разрешения для остальных
|
//! \~russian Разрешения для остальных.
|
||||||
Permissions perm_other;
|
Permissions perm_other;
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns name, without directory
|
//! \~english Returns name, without directory.
|
||||||
//! \~russian Возвращает имя, без директории
|
//! \~russian Возвращает имя, без директории.
|
||||||
|
//! \~\sa dir()
|
||||||
PIString name() const;
|
PIString name() const;
|
||||||
|
|
||||||
//! \~english Returns base name, without directory and extension
|
//! \~english Returns base name, without directory and extension.
|
||||||
//! \~russian Возвращает базовое имя, без директории и расширения
|
//! \~russian Возвращает базовое имя, без директории и расширения.
|
||||||
|
//! \~\sa name(), extension()
|
||||||
PIString baseName() const;
|
PIString baseName() const;
|
||||||
|
|
||||||
//! \~english Returns extension
|
//! \~english Returns extension.
|
||||||
//! \~russian Возвращает расширение
|
//! \~russian Возвращает расширение.
|
||||||
|
//! \~\sa baseName()
|
||||||
PIString extension() const;
|
PIString extension() const;
|
||||||
|
|
||||||
//! \~english Returns directory
|
//! \~english Returns directory.
|
||||||
//! \~russian Возвращает директорию
|
//! \~russian Возвращает директорию.
|
||||||
|
//! \~\sa name()
|
||||||
PIString dir() const;
|
PIString dir() const;
|
||||||
|
|
||||||
//! \~english Returns if it`s directory
|
//! \~english Returns if it's directory.
|
||||||
//! \~russian Возвращает директория ли это
|
//! \~russian Возвращает директория ли это.
|
||||||
bool isDir() const { return flags[Dir]; }
|
bool isDir() const { return flags[Dir]; }
|
||||||
|
|
||||||
//! \~english Returns if it`s file
|
//! \~english Returns if it's file.
|
||||||
//! \~russian Возвращает файл ли это
|
//! \~russian Возвращает файл ли это.
|
||||||
bool isFile() const { return flags[File]; }
|
bool isFile() const { return flags[File]; }
|
||||||
|
|
||||||
//! \~english Returns if it`s symbolic link
|
//! \~english Returns if it's symbolic link.
|
||||||
//! \~russian Возвращает символическая ссылка ли это
|
//! \~russian Возвращает символическая ссылка ли это.
|
||||||
bool isSymbolicLink() const { return flags[SymbolicLink]; }
|
bool isSymbolicLink() const { return flags[SymbolicLink]; }
|
||||||
|
|
||||||
//! \~english Returns if Hidden flag set
|
//! \~english Returns if Hidden flag set.
|
||||||
//! \~russian Возвращает установлен ли флаг Hidden
|
//! \~russian Возвращает установлен ли флаг Hidden.
|
||||||
bool isHidden() const { return flags[Hidden]; }
|
bool isHidden() const { return flags[Hidden]; }
|
||||||
|
|
||||||
//! \~english Returns if path is absolute
|
//! \~english Returns if path is absolute.
|
||||||
//! \~russian Возвращает абсолютный ли путь
|
//! \~russian Возвращает абсолютный ли путь.
|
||||||
bool isAbsolute() const;
|
bool isAbsolute() const;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \~english Open temporary file with open mode "mode"
|
//! \~english Opens temporary file with open mode "mode".
|
||||||
//! \~russian Открывает временный файл с режимом открытия "mode"
|
//! \~russian Открывает временный файл с режимом открытия "mode".
|
||||||
bool openTemporary(PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
bool openTemporary(PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! \~english Immediate write all buffered data to disk
|
//! \~english Immediately writes all buffered data to disk.
|
||||||
//! \~russian Немедленно записывает все буферизированные данные на диск
|
//! \~russian Немедленно записывает все буферизированные данные на диск.
|
||||||
void flush() override;
|
void flush() override;
|
||||||
|
|
||||||
//! \~english Move read/write position to "position"
|
//! \~english Moves read/write position to "position".
|
||||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
//! \~russian Перемещает позицию чтения/записи на "position".
|
||||||
void seek(llong position);
|
void seek(llong position);
|
||||||
|
|
||||||
//! \~english Move read/write position to the begin of the file
|
//! \~english Moves read/write position to the beginning of the file.
|
||||||
//! \~russian Перемещает позицию чтения/записи на начало файла
|
//! \~russian Перемещает позицию чтения/записи на начало файла.
|
||||||
void seekToBegin();
|
void seekToBegin();
|
||||||
|
|
||||||
//! \~english Move read/write position to the end of the file
|
//! \~english Moves read/write position to the end of the file.
|
||||||
//! \~russian Перемещает позицию чтения/записи на конец файла
|
//! \~russian Перемещает позицию чтения/записи на конец файла.
|
||||||
void seekToEnd();
|
void seekToEnd();
|
||||||
|
|
||||||
//! \~english Move read/write position to text line number "line" beginning
|
//! \~english Moves read/write position to text line number "line" beginning.
|
||||||
//! \~russian Перемещает позицию чтения/записи на начало текстовой строки номер "line"
|
//! \~russian Перемещает позицию чтения/записи на начало текстовой строки номер "line".
|
||||||
void seekToLine(llong line);
|
void seekToLine(llong line);
|
||||||
|
|
||||||
//! \~english Skip "bytes" bytes (move position next to "bytes" bytes)
|
//! \~english Skips "bytes" bytes (moves position next to "bytes" bytes).
|
||||||
//! \~russian Пропускает "bytes" байт (перемещает позицию на "bytes" байт вперёд)
|
//! \~russian Пропускает "bytes" байт (перемещает позицию на "bytes" байт вперёд).
|
||||||
void skip(llong bytes);
|
void skip(llong bytes);
|
||||||
|
|
||||||
//! \~english Read one char and return it
|
//! \~english Reads one byte and returns it.
|
||||||
//! \~russian Читает один байт и возвращает его
|
//! \~russian Читает один байт и возвращает его.
|
||||||
char readChar();
|
char readChar();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Read all file content to "data" and return readed bytes count. Position leaved unchanged
|
//! \~english Reads all file content to "data" and returns read bytes count. Position left unchanged.
|
||||||
//! \~russian Читает всё содержимое файла в "data" и возвращает количество прочитанных байт. Позиция остаётся неизменной
|
//! \~russian Читает всё содержимое файла в "data" и возвращает количество прочитанных байт. Позиция остаётся неизменной.
|
||||||
llong readAll(void * data);
|
llong readAll(void * data);
|
||||||
|
|
||||||
//! \~english Read all file content to byte array and return it. Position leaved unchanged
|
//! \~english Reads all file content to byte array and returns it. Position left unchanged.
|
||||||
//! \~russian Читает всё содержимое файла и возвращает его как массив байтов. Позиция остаётся неизменной
|
//! \~russian Читает всё содержимое файла и возвращает его как массив байтов. Позиция остаётся неизменной.
|
||||||
PIByteArray readAll();
|
PIByteArray readAll();
|
||||||
|
|
||||||
//! \~english Set file path to "path" and reopen file if need
|
//! \~english Sets file path to "path" and reopens file if needed.
|
||||||
//! \~russian Устанавливает путь файла на "path" и переоткрывает его при необходимости
|
//! \~russian Устанавливает путь файла на "path" и переоткрывает его при необходимости.
|
||||||
void setPath(const PIString & path);
|
void setPath(const PIString & path);
|
||||||
|
|
||||||
//! \~english Returns file size in bytes
|
//! \~english Returns file size in bytes.
|
||||||
//! \~russian Возвращает размер файла в байтах
|
//! \~russian Возвращает размер файла в байтах.
|
||||||
llong size() const;
|
llong size() const;
|
||||||
|
|
||||||
ssize_t bytesAvailable() const override { return size() - pos(); }
|
ssize_t bytesAvailable() const override { return size() - pos(); }
|
||||||
|
|
||||||
//! \~english Returns read/write position
|
//! \~english Returns read/write position.
|
||||||
//! \~russian Возвращает позицию чтения/записи
|
//! \~russian Возвращает позицию чтения/записи.
|
||||||
llong pos() const;
|
llong pos() const;
|
||||||
|
|
||||||
//! \~english Returns if position is at the end of file
|
//! \~english Returns if position is at the end of file.
|
||||||
//! \~russian Возвращает достигнут ли конец файла
|
//! \~russian Возвращает достигнут ли конец файла.
|
||||||
bool isEnd() const;
|
bool isEnd() const;
|
||||||
|
|
||||||
//! \~english Returns if file is empty
|
//! \~english Returns if file is empty.
|
||||||
//! \~russian Возвращает пустой ли файл
|
//! \~russian Возвращает пустой ли файл.
|
||||||
bool isEmpty() const { return (size() <= 0); }
|
bool isEmpty() const { return (size() <= 0); }
|
||||||
|
|
||||||
//! \~english Returns \a PIFile::FileInfo of current file
|
//! \~english Returns \a PIFile::FileInfo of current file.
|
||||||
//! \~russian Возвращает \a PIFile::FileInfo текущего файла
|
//! \~russian Возвращает \a PIFile::FileInfo текущего файла.
|
||||||
FileInfo fileInfo() const { return fileInfo(path()); }
|
FileInfo fileInfo() const { return fileInfo(path()); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Write size and content of "v" (serialize)
|
//! \~english Writes size and content of "v" (serialization).
|
||||||
//! \~russian Пишет в файл размер и содержимое "v" (сериализация)
|
//! \~russian Пишет в файл размер и содержимое "v" (сериализация).
|
||||||
PIFile & put(const PIByteArray & v);
|
PIFile & put(const PIByteArray & v);
|
||||||
|
|
||||||
//! \~english Read size of byte array and it content (deserialize)
|
//! \~english Reads size of byte array and its content (deserialization).
|
||||||
//! \~russian Читает из файла размер байтового массива и его содержимое (десериализация)
|
//! \~russian Читает из файла размер байтового массива и его содержимое (десериализация).
|
||||||
PIByteArray get();
|
PIByteArray get();
|
||||||
|
|
||||||
EVENT_HANDLER(void, clear);
|
|
||||||
EVENT_HANDLER(void, remove);
|
|
||||||
EVENT_HANDLER1(void, resize, llong, new_size) { resize(new_size, 0); }
|
|
||||||
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns if file with path "path" exists
|
|
||||||
//! \~russian Возвращает существует ли файл с путём "path"
|
|
||||||
static bool isExists(const PIString & path);
|
|
||||||
|
|
||||||
//! \~english Remove file with path "path" and returns if remove successful
|
|
||||||
//! \~russian Удаляет файл с путём "path" и возвращает успешность операции
|
|
||||||
static bool remove(const PIString & path);
|
|
||||||
|
|
||||||
//! \~english Rename file with path "from" to path "to" and returns if rename successful
|
|
||||||
//! \~russian Переименовывает файл с путём "path" на "to" и возвращает успешность операции
|
|
||||||
static bool rename(const PIString & from, const PIString & to);
|
|
||||||
|
|
||||||
//! \~english Returns \a PIFile::FileInfo of file or dir with path "path"
|
|
||||||
//! \~russian Возвращает \a PIFile::FileInfo файла или директории с путём "path"
|
|
||||||
static FileInfo fileInfo(const PIString & path);
|
|
||||||
|
|
||||||
//! \~english Apply "info" parameters to file or dir with path "path"
|
|
||||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "path"
|
|
||||||
static bool applyFileInfo(const PIString & path, const FileInfo & info);
|
|
||||||
|
|
||||||
//! \~english Apply "info" parameters to file or dir with path "info".path
|
|
||||||
//! \~russian Применяет параметры "info" к файлу или директории с путём "info".path
|
|
||||||
static bool applyFileInfo(const FileInfo & info) { return applyFileInfo(info.path, info); }
|
|
||||||
|
|
||||||
//! \~english Read all file content at path "path" to byte array and return it.
|
|
||||||
//! \~russian Читает всё содержимое файла по пути "path" и возвращает его как массив байтов.
|
|
||||||
static PIByteArray readAll(const PIString & path);
|
|
||||||
|
|
||||||
//! \~english Clear file at path "path" and write "data", returns written bytes.
|
|
||||||
//! \~russian Очищает файл по пути "path", пишет туда "data" и возвращает количество записанных байт.
|
|
||||||
static int writeAll(const PIString & path, const PIByteArray & data);
|
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void clear()
|
//! \fn void clear()
|
||||||
//! \~english Clear content of file
|
//! \~english Clears content of file.
|
||||||
//! \~russian Очищает содержимое файла
|
//! \~russian Очищает содержимое файла.
|
||||||
|
EVENT_HANDLER(void, clear);
|
||||||
//! \fn void resize(llong new_size)
|
|
||||||
//! \~english Resize file to "new_size" with null-byte fill
|
|
||||||
//! \~russian Изменяет размер файла на "new_size" с заполнением нулевыми байтами
|
|
||||||
|
|
||||||
//! \fn void resize(llong new_size, uchar fill)
|
|
||||||
//! \~english Resize file to "new_size" with "fill" fill
|
|
||||||
//! \~russian Изменяет размер файла на "new_size" с заполнением байтами "fill"
|
|
||||||
|
|
||||||
//! \fn void remove()
|
//! \fn void remove()
|
||||||
//! \~english Remove file
|
//! \~english Removes file.
|
||||||
//! \~russian Удаляет файл
|
//! \~russian Удаляет файл.
|
||||||
|
EVENT_HANDLER(void, remove);
|
||||||
|
|
||||||
|
//! \fn void resize(llong new_size)
|
||||||
|
//! \~english Resizes file to "new_size" with null-byte fill.
|
||||||
|
//! \~russian Изменяет размер файла на "new_size" с заполнением нулевыми байтами.
|
||||||
|
EVENT_HANDLER1(void, resize, llong, new_size) { resize(new_size, 0); }
|
||||||
|
|
||||||
|
//! \fn void resize(llong new_size, uchar fill)
|
||||||
|
//! \~english Resizes file to "new_size" with "fill" fill.
|
||||||
|
//! \~russian Изменяет размер файла на "new_size" с заполнением байтами "fill".
|
||||||
|
EVENT_HANDLER2(void, resize, llong, new_size, uchar, fill);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns if file with path "path" exists.
|
||||||
|
//! \~russian Возвращает существует ли файл с путём "path".
|
||||||
|
static bool isExists(const PIString & path);
|
||||||
|
|
||||||
|
//! \~english Removes file with path "path" and returns if remove successful.
|
||||||
|
//! \~russian Удаляет файл с путём "path" и возвращает успешность операции.
|
||||||
|
static bool remove(const PIString & path);
|
||||||
|
|
||||||
|
//! \~english Renames file with path "from" to path "to" and returns if rename successful.
|
||||||
|
//! \~russian Переименовывает файл с путём "from" на "to" и возвращает успешность операции.
|
||||||
|
static bool rename(const PIString & from, const PIString & to);
|
||||||
|
|
||||||
|
//! \~english Returns \a PIFile::FileInfo of file or dir with path "path".
|
||||||
|
//! \~russian Возвращает \a PIFile::FileInfo файла или директории с путём "path".
|
||||||
|
static FileInfo fileInfo(const PIString & path);
|
||||||
|
|
||||||
|
//! \~english Applies "info" parameters to file or dir with path "path".
|
||||||
|
//! \~russian Применяет параметры "info" к файлу или директории с путём "path".
|
||||||
|
static bool applyFileInfo(const PIString & path, const FileInfo & info);
|
||||||
|
|
||||||
|
//! \~english Applies "info" parameters to file or dir with path "info".path.
|
||||||
|
//! \~russian Применяет параметры "info" к файлу или директории с путём "info".path.
|
||||||
|
static bool applyFileInfo(const FileInfo & info) { return applyFileInfo(info.path, info); }
|
||||||
|
|
||||||
|
//! \~english Reads all file content at path "path" to byte array and returns it.
|
||||||
|
//! \~russian Читает всё содержимое файла по пути "path" и возвращает его как массив байтов.
|
||||||
|
static PIByteArray readAll(const PIString & path);
|
||||||
|
|
||||||
|
//! \~english Clears file at path "path" and writes "data", returns written bytes.
|
||||||
|
//! \~russian Очищает файл по пути "path", пишет туда "data" и возвращает количество записанных байт.
|
||||||
|
static int writeAll(const PIString & path, const PIByteArray & data);
|
||||||
|
|
||||||
|
|
||||||
//! \ioparams
|
//! \ioparams
|
||||||
//! \{
|
//! \{
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
@@ -348,8 +364,8 @@ private:
|
|||||||
|
|
||||||
|
|
||||||
//! \relatesalso PICout
|
//! \relatesalso PICout
|
||||||
//! \~english Output operator to \a PICout
|
//! \~english Output operator to \a PICout.
|
||||||
//! \~russian Оператор вывода в \a PICout
|
//! \~russian Оператор вывода в \a PICout.
|
||||||
inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " "
|
s << "FileInfo(\"" << v.path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " "
|
||||||
@@ -363,6 +379,7 @@ inline PICout operator<<(PICout s, const PIFile::FileInfo & v) {
|
|||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Store operator.
|
//! \~english Store operator.
|
||||||
//! \~russian Оператор сохранения.
|
//! \~russian Оператор сохранения.
|
||||||
|
//! \~\sa BINARY_STREAM_READ
|
||||||
BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
||||||
s << v.path << v.size << v.time_access << v.time_modification << v.flags << v.id_user << v.id_group << v.perm_user.raw
|
s << v.path << v.size << v.time_access << v.time_modification << v.flags << v.id_user << v.id_group << v.perm_user.raw
|
||||||
<< v.perm_group.raw << v.perm_other.raw;
|
<< v.perm_group.raw << v.perm_other.raw;
|
||||||
@@ -372,6 +389,7 @@ BINARY_STREAM_WRITE(PIFile::FileInfo) {
|
|||||||
//! \relatesalso PIBinaryStream
|
//! \relatesalso PIBinaryStream
|
||||||
//! \~english Restore operator.
|
//! \~english Restore operator.
|
||||||
//! \~russian Оператор извлечения.
|
//! \~russian Оператор извлечения.
|
||||||
|
//! \~\sa BINARY_STREAM_WRITE
|
||||||
BINARY_STREAM_READ(PIFile::FileInfo) {
|
BINARY_STREAM_READ(PIFile::FileInfo) {
|
||||||
s >> v.path >> v.size >> v.time_access >> v.time_modification >> v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >>
|
s >> v.path >> v.size >> v.time_access >> v.time_modification >> v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >>
|
||||||
v.perm_group.raw >> v.perm_other.raw;
|
v.perm_group.raw >> v.perm_other.raw;
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/*! \file pigpio.h
|
/*! \file pigpio.h
|
||||||
* \ingroup IO
|
* \ingroup IO
|
||||||
* \~\brief
|
* \~\brief
|
||||||
* \~english GPIO
|
* \~english GPIO support.
|
||||||
* \~russian GPIO
|
* \~russian Поддержка GPIO.
|
||||||
*/
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
@@ -29,23 +29,28 @@
|
|||||||
#include "pithread.h"
|
#include "pithread.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english GPIO support.
|
//! \~english GPIO support library.
|
||||||
//! \~russian Поддержка GPIO.
|
//! \~russian Библиотека поддержки GPIO.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english The PIGPIO class provides functions for GPIO pin initialization, reading, writing, and monitoring.
|
||||||
|
//! \~russian Класс PIGPIO предоставляет функции для инициализации, чтения, записи и мониторинга GPIO пинов.
|
||||||
class PIP_EXPORT PIGPIO: public PIThread {
|
class PIP_EXPORT PIGPIO: public PIThread {
|
||||||
PIOBJECT_SUBCLASS(PIGPIO, PIThread);
|
PIOBJECT_SUBCLASS(PIGPIO, PIThread);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Work mode for pin
|
//! \~english Work mode for pin.
|
||||||
//! \~russian Режим работы пина
|
//! \~russian Режим работы пина.
|
||||||
|
//! \~\sa initPin(), pinSet()
|
||||||
enum Direction {
|
enum Direction {
|
||||||
In /** \~english Input direction (read) \~russian Входной (чтение) */,
|
In /** \~english Input direction (read) \~russian Входной (чтение) */,
|
||||||
Out /** \~english Output direction (write) \~russian Выходной (запись) */
|
Out /** \~english Output direction (write) \~russian Выходной (запись) */
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Returns singleton object of %PIGPIO
|
//! \~english Returns singleton object of %PIGPIO.
|
||||||
//! \~russian Возвращает синглтон объекта %PIGPIO
|
//! \~russian Возвращает синглтон объекта %PIGPIO.
|
||||||
|
//! \~\sa instance()
|
||||||
static PIGPIO * instance();
|
static PIGPIO * instance();
|
||||||
|
|
||||||
//! \~english Initialize pin "gpio_num" for "dir" mode
|
//! \~english Initialize pin "gpio_num" for "dir" mode
|
||||||
@@ -56,29 +61,39 @@ public:
|
|||||||
//! \~russian Устанавливает значение пина "gpio_num" в "value"
|
//! \~russian Устанавливает значение пина "gpio_num" в "value"
|
||||||
void pinSet(int gpio_num, bool value);
|
void pinSet(int gpio_num, bool value);
|
||||||
|
|
||||||
//! \~english Set pin "gpio_num" value to \b true
|
//! \~english Set pin "gpio_num" value to \b true.
|
||||||
//! \~russian Устанавливает значение пина "gpio_num" в \b true
|
//! \~russian Устанавливает значение пина "gpio_num" в \b true.
|
||||||
|
//! \~\sa pinSet()
|
||||||
void pinHigh(int gpio_num) { pinSet(gpio_num, true); }
|
void pinHigh(int gpio_num) { pinSet(gpio_num, true); }
|
||||||
|
|
||||||
//! \~english Set pin "gpio_num" value to \b false
|
//! \~english Set pin "gpio_num" value to \b false.
|
||||||
//! \~russian Устанавливает значение пина "gpio_num" в \b false
|
//! \~russian Устанавливает значение пина "gpio_num" в \b false.
|
||||||
|
//! \~\sa pinSet()
|
||||||
void pinLow(int gpio_num) { pinSet(gpio_num, false); }
|
void pinLow(int gpio_num) { pinSet(gpio_num, false); }
|
||||||
|
|
||||||
//!
|
|
||||||
//! \~english Returns pin "gpio_num" state
|
//! \~english Returns pin "gpio_num" state
|
||||||
//! \~russian Возвращает значение пина "gpio_num"
|
//! \~russian Возвращает значение пина "gpio_num"
|
||||||
bool pinState(int gpio_num);
|
bool pinState(int gpio_num);
|
||||||
|
|
||||||
//! \~english Starts watch for pin "gpio_num"
|
//! \~english Start watch for pin "gpio_num".
|
||||||
//! \~russian Начинает наблюдение за пином "gpio_num"
|
//! \~russian Начинает наблюдение за пином "gpio_num".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||||
|
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||||
void pinBeginWatch(int gpio_num);
|
void pinBeginWatch(int gpio_num);
|
||||||
|
|
||||||
//! \~english End watch for pin "gpio_num"
|
//! \~english End watch for pin "gpio_num".
|
||||||
//! \~russian Заканчивает наблюдение за пином "gpio_num"
|
//! \~russian Заканчивает наблюдение за пином "gpio_num".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||||
|
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||||
void pinEndWatch(int gpio_num);
|
void pinEndWatch(int gpio_num);
|
||||||
|
|
||||||
//! \~english End watch for all pins
|
//! \~english End watch for all pins.
|
||||||
//! \~russian Заканчивает наблюдение за всеми пинами
|
//! \~russian Заканчивает наблюдение за всеми пинами.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This function doesn't affect thread state. Pins watching starts only with \a PIThread::start().
|
||||||
|
//! \~russian Этот метод не меняет состояние потока наблюдения. Наблюдение за пинами начинается методом \a PIThread::start().
|
||||||
void clearWatch();
|
void clearWatch();
|
||||||
|
|
||||||
EVENT2(pinChanged, int, gpio_num, bool, new_value);
|
EVENT2(pinChanged, int, gpio_num, bool, new_value);
|
||||||
@@ -87,12 +102,15 @@ public:
|
|||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void pinChanged(int gpio_num, bool new_value)
|
//! \fn void pinChanged(int gpio_num, bool new_value)
|
||||||
//! \~english Raise on pin "gpio_num" state changes to "new_value"
|
//! \~english Raised when pin "gpio_num" state changes to "new_value".
|
||||||
//! \~russian Вызывается по смене состояния пина "gpio_num" на "new_value"
|
//! \~russian Вызывается при смене состояния пина "gpio_num" на "new_value".
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~\warning
|
//! \~\warning
|
||||||
//! \~english This event raised only when thread started.
|
//! \~english This event is raised only when the thread is started.
|
||||||
//! \~russian Это событие вызывается только при запущенном потоке.
|
//! \~russian Это событие вызывается только при запущенном потоке.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Use \a PIThread::start() to begin watching pins.
|
||||||
|
//! \~russian Используйте \a PIThread::start() для начала наблюдения за пинами.
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
/*! \file piiobytearray.h
|
/*! \file piiobytearray.h
|
||||||
* \ingroup IO
|
* \ingroup IO
|
||||||
* \~\brief
|
* \~\brief
|
||||||
* \~english PIIODevice wrapper around PIByteArray
|
* \~english PIIODevice wrapper around PIByteArray.
|
||||||
* \~russian Обертка PIIODevice вокруг PIByteArray
|
* \~russian Обертка PIIODevice вокруг PIByteArray.
|
||||||
*/
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
@@ -29,70 +29,72 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english PIIODevice wrapper around PIByteArray
|
//! \~english PIIODevice wrapper around PIByteArray.
|
||||||
//! \~russian Обёртка PIIODevice вокруг PIByteArray
|
//! \~russian Обёртка PIIODevice вокруг PIByteArray.
|
||||||
class PIP_EXPORT PIIOByteArray: public PIIODevice {
|
class PIP_EXPORT PIIOByteArray: public PIIODevice {
|
||||||
PIIODEVICE(PIIOByteArray, "");
|
PIIODEVICE(PIIOByteArray, "");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs %PIIOByteArray with "buffer" content and "mode" open mode
|
//! \~english Constructs %PIIOByteArray with "buffer" content and "mode" open mode.
|
||||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode"
|
//! \~russian Создает %PIIOByteArray с содержимым "buffer" и режимом открытия "mode".
|
||||||
explicit PIIOByteArray(PIByteArray * buffer = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
explicit PIIOByteArray(PIByteArray * buffer = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! \~english Contructs %PIIOByteArray with "buffer" content only for read
|
//! \~english Constructs %PIIOByteArray with "buffer" content only for read.
|
||||||
//! \~russian Создает %PIIOByteArray с содержимым "buffer" только для чтения
|
//! \~russian Создает %PIIOByteArray с содержимым "buffer" только для чтения.
|
||||||
explicit PIIOByteArray(const PIByteArray & buffer);
|
explicit PIIOByteArray(const PIByteArray & buffer);
|
||||||
|
|
||||||
//! \~english Returns content
|
//! \~english Returns content.
|
||||||
//! \~russian Возвращает содержимое
|
//! \~russian Возвращает содержимое.
|
||||||
PIByteArray * byteArray() const { return data_; }
|
PIByteArray * byteArray() const { return data_; }
|
||||||
|
|
||||||
//! \~english Clear content buffer
|
//! \~english Clears content buffer.
|
||||||
//! \~russian Очищает содержимое буфера
|
//! \~russian Очищает содержимое буфера.
|
||||||
void clear() {
|
void clear() {
|
||||||
if (data_) data_->clear();
|
if (data_) data_->clear();
|
||||||
pos = 0;
|
pos = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Open "buffer" content with "mode" open mode
|
//! \~english Opens "buffer" content with "mode" open mode.
|
||||||
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode"
|
//! \~russian Открывает содержимое "buffer" с режимом открытия "mode".
|
||||||
bool open(PIByteArray * buffer, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
bool open(PIByteArray * buffer, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
//! \~english Open "buffer" content only for read
|
//! \~english Opens "buffer" content only for read.
|
||||||
//! \~russian Открывает содержимое "buffer" только для чтения
|
//! \~russian Открывает содержимое "buffer" только для чтения.
|
||||||
bool open(const PIByteArray & buffer);
|
bool open(const PIByteArray & buffer);
|
||||||
|
|
||||||
//! \~english Returns if position is at the end of content
|
//! \~english Returns true if position is at the end of content.
|
||||||
//! \~russian Возвращает в конце содержимого ли позиция
|
//! \~russian Возвращает true, если позиция в конце содержимого.
|
||||||
bool isEnd() const {
|
bool isEnd() const {
|
||||||
if (!data_) return true;
|
if (!data_) return true;
|
||||||
return pos >= data_->size_s();
|
return pos >= data_->size_s();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Move read/write position to "position"
|
//! \~english Moves read/write position to "position".
|
||||||
//! \~russian Перемещает позицию чтения/записи на "position"
|
//! \~russian Перемещает позицию чтения/записи на "position".
|
||||||
void seek(llong position) { pos = position; }
|
void seek(llong position) { pos = position; }
|
||||||
|
|
||||||
//! \~english Move read/write position to the beginning of the buffer
|
//! \~english Moves read/write position to the beginning of the buffer.
|
||||||
//! \~russian Перемещает позицию чтения/записи на начало буфера
|
//! \~russian Перемещает позицию чтения/записи на начало буфера.
|
||||||
void seekToBegin() {
|
void seekToBegin() {
|
||||||
if (data_) pos = 0;
|
if (data_) pos = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Move read/write position to the end of the buffer
|
//! \~english Moves read/write position to the end of the buffer.
|
||||||
//! \~russian Перемещает позицию чтения/записи на конец буфера
|
//! \~russian Перемещает позицию чтения/записи на конец буфера.
|
||||||
void seekToEnd() {
|
void seekToEnd() {
|
||||||
if (data_) pos = data_->size_s();
|
if (data_) pos = data_->size_s();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Insert data "ba" into content at current position
|
//! \~english Inserts data "ba" into content at current position.
|
||||||
//! \~russian Вставляет данные "ba" в содержимое буфера в текущую позицию
|
//! \~russian Вставляет данные "ba" в содержимое буфера в текущую позицию.
|
||||||
int writeByteArray(const PIByteArray & ba);
|
int writeByteArray(const PIByteArray & ba);
|
||||||
|
|
||||||
|
//! \~english Returns number of bytes available for reading.
|
||||||
|
//! \~russian Возвращает количество доступных для чтения байт.
|
||||||
ssize_t bytesAvailable() const override {
|
ssize_t bytesAvailable() const override {
|
||||||
if (data_)
|
if (data_)
|
||||||
return data_->size();
|
return data_->size();
|
||||||
@@ -101,12 +103,28 @@ public:
|
|||||||
}
|
}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
//! \~english Opens the device.
|
||||||
|
//! \~russian Открывает устройство.
|
||||||
bool openDevice() override;
|
bool openDevice() override;
|
||||||
|
|
||||||
|
//! \~english Reads data from the device.
|
||||||
|
//! \~russian Читает данные из устройства.
|
||||||
ssize_t readDevice(void * read_to, ssize_t size) override;
|
ssize_t readDevice(void * read_to, ssize_t size) override;
|
||||||
|
|
||||||
|
//! \~english Writes data to the device.
|
||||||
|
//! \~russian Записывает данные в устройство.
|
||||||
ssize_t writeDevice(const void * data_, ssize_t size) override;
|
ssize_t writeDevice(const void * data_, ssize_t size) override;
|
||||||
|
|
||||||
|
//! \~english Returns device info flags.
|
||||||
|
//! \~russian Возвращает флаги информации об устройстве.
|
||||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential | PIIODevice::Reliable; }
|
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential | PIIODevice::Reliable; }
|
||||||
|
|
||||||
|
//! \~english Current read/write position.
|
||||||
|
//! \~russian Текущая позиция чтения/записи.
|
||||||
ssize_t pos;
|
ssize_t pos;
|
||||||
|
|
||||||
|
//! \~english Pointer to data buffer.
|
||||||
|
//! \~russian Указатель на буфер данных.
|
||||||
PIByteArray * data_;
|
PIByteArray * data_;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piiodevice.h
|
//! \~\file piiodevice.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Abstract input/output device
|
//! \~english Core abstraction for configurable input/output devices
|
||||||
* \~russian Базовый класс утройств ввода/вывода
|
//! \~russian Базовая абстракция для настраиваемых устройств ввода/вывода
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Abstract input/output device
|
Abstract input/output device
|
||||||
@@ -30,14 +29,18 @@
|
|||||||
#include "piqueue.h"
|
#include "piqueue.h"
|
||||||
#include "pithread.h"
|
#include "pithread.h"
|
||||||
|
|
||||||
/// TODO: написать документацию, тут ничего не понятно
|
//! \~english Callback used by \a setThreadedReadSlot().
|
||||||
// function executed from threaded read, pass readedData, sizeOfData, ThreadedReadData
|
//! \~russian Callback, используемый методом \a setThreadedReadSlot().
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Receives pointer to data read by the background thread, number of bytes and user data set by \a setThreadedReadData().
|
||||||
|
//! \~russian Принимает указатель на данные, прочитанные фоновым потоком, количество байт и пользовательские данные, заданные через \a
|
||||||
|
//! setThreadedReadData().
|
||||||
typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
||||||
|
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
|
|
||||||
//! \relatesalso PIIODevice
|
//! \relatesalso PIIODevice
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Enable device instances creation with \a PIIODevice::createFromFullPath() function.
|
//! \~english Enable device instances creation with \a PIIODevice::createFromFullPath() function.
|
||||||
//! \~russian Включить создание экземпляров устройства с помощью метода \a PIIODevice::createFromFullPath().
|
//! \~russian Включить создание экземпляров устройства с помощью метода \a PIIODevice::createFromFullPath().
|
||||||
//! \~\details
|
//! \~\details
|
||||||
@@ -46,12 +49,12 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
|||||||
# define REGISTER_DEVICE(class)
|
# define REGISTER_DEVICE(class)
|
||||||
|
|
||||||
//! \relatesalso PIIODevice
|
//! \relatesalso PIIODevice
|
||||||
//! \brief
|
//! \~\brief
|
||||||
//! \~english Use this macro instead of PIOBJECT when describe your own PIIODevice.
|
//! \~english Use this macro instead of PIOBJECT when describe your own PIIODevice.
|
||||||
//! \~russian Используйте этот макрос вместо PIOBJECT при объявлении своего PIIODevice.
|
//! \~russian Используйте этот макрос вместо PIOBJECT при объявлении своего PIIODevice.
|
||||||
//! \~\param "prefix"
|
//! \~\details
|
||||||
//! \~english Unique device prefix in quotes, may be ""
|
//! \~english "prefix" is a unique device prefix used in \a createFromFullPath().
|
||||||
//! \~russian Уникальный префикс устройства в кавычках, может быть ""
|
//! \~russian "prefix" это уникальный префикс устройства, используемый в \a createFromFullPath().
|
||||||
# define PIIODEVICE(class, "prefix")
|
# define PIIODEVICE(class, "prefix")
|
||||||
|
|
||||||
#else
|
#else
|
||||||
@@ -80,10 +83,10 @@ typedef std::function<bool(const uchar *, int, void *)> ReadRetFunc;
|
|||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Base class for input/output devices.
|
//! \~english Base class for input/output devices.
|
||||||
//! \~russian Базовый класс утройств ввода/вывода.
|
//! \~russian Базовый класс устройств ввода/вывода.
|
||||||
class PIP_EXPORT PIIODevice: public PIObject {
|
class PIP_EXPORT PIIODevice: public PIObject {
|
||||||
PIOBJECT_SUBCLASS(PIIODevice, PIObject);
|
PIOBJECT_SUBCLASS(PIIODevice, PIObject);
|
||||||
friend void __DevicePool_threadReadDP(void * ddp);
|
friend void __DevicePool_threadReadDP(void * ddp);
|
||||||
@@ -91,20 +94,20 @@ class PIP_EXPORT PIIODevice: public PIObject {
|
|||||||
public:
|
public:
|
||||||
NO_COPY_CLASS(PIIODevice);
|
NO_COPY_CLASS(PIIODevice);
|
||||||
|
|
||||||
//! \~english Constructs a empty %PIIODevice
|
//! \~english Constructs an empty %PIIODevice.
|
||||||
//! \~russian Создает пустой %PIIODevice
|
//! \~russian Создает пустой %PIIODevice.
|
||||||
explicit PIIODevice();
|
explicit PIIODevice();
|
||||||
|
|
||||||
//! \~english Open modes for PIIODevice
|
//! \~english Open modes for %PIIODevice.
|
||||||
//! \~russian Режимы открытия для PIIODevice
|
//! \~russian Режимы открытия %PIIODevice.
|
||||||
enum DeviceMode {
|
enum DeviceMode {
|
||||||
ReadOnly /*! \~english Device can only read \~russian Устройство может только читать */ = 0x01,
|
ReadOnly /*! \~english Device can only read \~russian Устройство может только читать */ = 0x01,
|
||||||
WriteOnly /*! \~english Device can only write \~russian Устройство может только писать */ = 0x02,
|
WriteOnly /*! \~english Device can only write \~russian Устройство может только писать */ = 0x02,
|
||||||
ReadWrite /*! \~english Device can both read and write \~russian Устройство может читать и писать */ = 0x03
|
ReadWrite /*! \~english Device can both read and write \~russian Устройство может читать и писать */ = 0x03
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Options for PIIODevice, works with some devices
|
//! \~english Generic options supported by some devices.
|
||||||
//! \~russian Опции для PIIODevice, работает для некоторых устройств
|
//! \~russian Общие опции, поддерживаемые некоторыми устройствами.
|
||||||
enum DeviceOption {
|
enum DeviceOption {
|
||||||
BlockingRead /*! \~english \a read() block until data is received, default off \~russian \a read() блокируется, пока данные не
|
BlockingRead /*! \~english \a read() block until data is received, default off \~russian \a read() блокируется, пока данные не
|
||||||
поступят, по умолчанию выключено */
|
поступят, по умолчанию выключено */
|
||||||
@@ -114,8 +117,8 @@ public:
|
|||||||
= 0x02
|
= 0x02
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \~english Characteristics of PIIODevice channel
|
//! \~english Characteristics of the device channel.
|
||||||
//! \~russian Характеристики канала PIIODevice
|
//! \~russian Характеристики канала устройства.
|
||||||
enum DeviceInfoFlag {
|
enum DeviceInfoFlag {
|
||||||
Sequential /*! \~english Continuous bytestream without packets \~russian Непрерывный поток байт, без пакетирования */ = 0x01,
|
Sequential /*! \~english Continuous bytestream without packets \~russian Непрерывный поток байт, без пакетирования */ = 0x01,
|
||||||
Reliable /*! \~english Channel without data errors or corruptions \~russian Канал без ошибок или повреждений данных */ = 0x02
|
Reliable /*! \~english Channel without data errors or corruptions \~russian Канал без ошибок или повреждений данных */ = 0x02
|
||||||
@@ -127,136 +130,143 @@ public:
|
|||||||
PIIODevice * (*fabricator)() = nullptr;
|
PIIODevice * (*fabricator)() = nullptr;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Bitmask of \a DeviceOption values.
|
||||||
|
//! \~russian Битовая маска значений \a DeviceOption.
|
||||||
typedef PIFlags<DeviceOption> DeviceOptions;
|
typedef PIFlags<DeviceOption> DeviceOptions;
|
||||||
|
|
||||||
|
//! \~english Bitmask of \a DeviceInfoFlag values.
|
||||||
|
//! \~russian Битовая маска значений \a DeviceInfoFlag.
|
||||||
typedef PIFlags<DeviceInfoFlag> DeviceInfoFlags;
|
typedef PIFlags<DeviceInfoFlag> DeviceInfoFlags;
|
||||||
|
|
||||||
//! \~english Constructs %PIIODevice with path "path" and open mode "mode"
|
//! \~english Constructs %PIIODevice with path "path" and open mode "mode".
|
||||||
//! \~russian Создает %PIIODevice с путём "path" и режимом открытия "mode"
|
//! \~russian Создает %PIIODevice с путём "path" и режимом открытия "mode".
|
||||||
explicit PIIODevice(const PIString & path, DeviceMode mode = ReadWrite);
|
explicit PIIODevice(const PIString & path, DeviceMode mode = ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the device base object.
|
||||||
|
//! \~russian Уничтожает базовый объект устройства.
|
||||||
virtual ~PIIODevice();
|
virtual ~PIIODevice();
|
||||||
|
|
||||||
//! \~english Returns current open mode of device
|
//! \~english Returns current open mode.
|
||||||
//! \~russian Возвращает текущий режим открытия устройства
|
//! \~russian Возвращает текущий режим открытия.
|
||||||
DeviceMode mode() const { return mode_; }
|
DeviceMode mode() const { return mode_; }
|
||||||
|
|
||||||
//! \~english Set open mode of device. Don`t reopen device
|
//! \~english Sets open mode without reopening the device.
|
||||||
//! \~russian Устанавливает режим открытия устройства. Не переоткрывает устройство
|
//! \~russian Устанавливает режим открытия без переоткрытия устройства.
|
||||||
void setMode(DeviceMode m) { mode_ = m; }
|
void setMode(DeviceMode m) { mode_ = m; }
|
||||||
|
|
||||||
//! \~english Returns current device options
|
//! \~english Returns current device options.
|
||||||
//! \~russian Возвращает текущие опции устройства
|
//! \~russian Возвращает текущие опции устройства.
|
||||||
DeviceOptions options() const { return options_; }
|
DeviceOptions options() const { return options_; }
|
||||||
|
|
||||||
//! \~english Returns current device option "o" state
|
//! \~english Returns whether option "o" is enabled.
|
||||||
//! \~russian Возвращает текущее состояние опции "o"
|
//! \~russian Возвращает, включена ли опция "o".
|
||||||
bool isOptionSet(DeviceOption o) const { return options_[o]; }
|
bool isOptionSet(DeviceOption o) const { return options_[o]; }
|
||||||
|
|
||||||
//! \~english Set device options
|
//! \~english Replaces all current device options with "o".
|
||||||
//! \~russian Устанавливает опции устройства
|
//! \~russian Полностью заменяет текущие опции устройства на "o".
|
||||||
void setOptions(DeviceOptions o);
|
void setOptions(DeviceOptions o);
|
||||||
|
|
||||||
//! \~english Set device option "o" to "yes" and returns previous state
|
//! \~english Sets option "o" to "yes" and returns its previous state.
|
||||||
//! \~russian Устанавливает опцию "o" устройства в "yes" и возвращает предыдущее состояние опции
|
//! \~russian Устанавливает опцию "o" в состояние "yes" и возвращает её предыдущее состояние.
|
||||||
bool setOption(DeviceOption o, bool yes = true);
|
bool setOption(DeviceOption o, bool yes = true);
|
||||||
|
|
||||||
//! \~english Returns device characteristic flags
|
//! \~english Returns device channel characteristics.
|
||||||
//! \~russian Возвращает характеристики канала
|
//! \~russian Возвращает характеристики канала устройства.
|
||||||
DeviceInfoFlags infoFlags() const { return deviceInfoFlags(); }
|
DeviceInfoFlags infoFlags() const { return deviceInfoFlags(); }
|
||||||
|
|
||||||
//! \~english Returns current path of device
|
//! \~english Returns current device path.
|
||||||
//! \~russian Возвращает текущий путь устройства
|
//! \~russian Возвращает текущий путь устройства.
|
||||||
PIString path() const { return property("path").toString(); }
|
PIString path() const { return property("path").toString(); }
|
||||||
|
|
||||||
//! \~english Set path of device. Don`t reopen device
|
//! \~english Sets device path without reopening the device.
|
||||||
//! \~russian Устанавливает путь устройства. Не переоткрывает устройство
|
//! \~russian Устанавливает путь устройства без его переоткрытия.
|
||||||
void setPath(const PIString & path) { setProperty("path", path); }
|
void setPath(const PIString & path) { setProperty("path", path); }
|
||||||
|
|
||||||
//! \~english Returns if mode is ReadOnly or ReadWrite
|
//! \~english Returns whether the current mode allows reading.
|
||||||
//! \~russian Возвращает равен ли режим открытия ReadOnly или ReadWrite
|
//! \~russian Возвращает, разрешает ли текущий режим чтение.
|
||||||
bool isReadable() const { return (mode_ & ReadOnly); }
|
bool isReadable() const { return (mode_ & ReadOnly); }
|
||||||
|
|
||||||
//! \~english Returns if mode is WriteOnly or ReadWrite
|
//! \~english Returns whether the current mode allows writing.
|
||||||
//! \~russian Возвращает равен ли режим открытия WriteOnly или ReadWrite
|
//! \~russian Возвращает, разрешает ли текущий режим запись.
|
||||||
bool isWriteable() const { return (mode_ & WriteOnly); }
|
bool isWriteable() const { return (mode_ & WriteOnly); }
|
||||||
|
|
||||||
//! \~english Returns if device is successfully opened
|
//! \~english Returns whether the device is currently opened.
|
||||||
//! \~russian Возвращает успешно ли открыто устройство
|
//! \~russian Возвращает, открыто ли сейчас устройство.
|
||||||
bool isOpened() const { return opened_; }
|
bool isOpened() const { return opened_; }
|
||||||
|
|
||||||
//! \~english Returns if device is closed
|
//! \~english Returns whether the device is currently closed.
|
||||||
//! \~russian Возвращает закрыто ли устройство
|
//! \~russian Возвращает, закрыто ли сейчас устройство.
|
||||||
bool isClosed() const { return !opened_; }
|
bool isClosed() const { return !opened_; }
|
||||||
|
|
||||||
//! \~english Returns if device can read \b now
|
//! \~english Returns whether reading is possible right now.
|
||||||
//! \~russian Возвращает может ли устройство читать \b сейчас
|
//! \~russian Возвращает, возможно ли чтение прямо сейчас.
|
||||||
virtual bool canRead() const { return opened_ && (mode_ & ReadOnly); }
|
virtual bool canRead() const { return opened_ && (mode_ & ReadOnly); }
|
||||||
|
|
||||||
//! \~english Returns if device can write \b now
|
//! \~english Returns whether writing is possible right now.
|
||||||
//! \~russian Возвращает может ли устройство писать \b сейчас
|
//! \~russian Возвращает, возможна ли запись прямо сейчас.
|
||||||
virtual bool canWrite() const { return opened_ && (mode_ & WriteOnly); }
|
virtual bool canWrite() const { return opened_ && (mode_ & WriteOnly); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Set calling of \a open() enabled while threaded read on closed device
|
//! \~english Enables or disables automatic reopen attempts during threaded read.
|
||||||
//! \~russian Устанавливает возможность вызова \a open() при потоковом чтении на закрытом устройстве
|
//! \~russian Включает или выключает автоматические попытки переоткрытия при потоковом чтении.
|
||||||
void setReopenEnabled(bool yes = true);
|
void setReopenEnabled(bool yes = true);
|
||||||
|
|
||||||
//! \~english Set timeout between \a open() tryings if reopen is enabled
|
//! \~english Sets delay between automatic reopen attempts.
|
||||||
//! \~russian Устанавливает задержку между вызовами \a open() если переоткрытие активно
|
//! \~russian Устанавливает задержку между автоматическими попытками переоткрытия.
|
||||||
void setReopenTimeout(PISystemTime timeout);
|
void setReopenTimeout(PISystemTime timeout);
|
||||||
|
|
||||||
//! \~english Returns reopen enable
|
//! \~english Returns whether automatic reopen is enabled.
|
||||||
//! \~russian Возвращает активно ли переоткрытие
|
//! \~russian Возвращает, включено ли автоматическое переоткрытие.
|
||||||
bool isReopenEnabled() const { return property("reopenEnabled").toBool(); }
|
bool isReopenEnabled() const { return property("reopenEnabled").toBool(); }
|
||||||
|
|
||||||
//! \~english Returns reopen timeout
|
//! \~english Returns delay between automatic reopen attempts.
|
||||||
//! \~russian Возвращает задержку переоткрытия
|
//! \~russian Возвращает задержку между автоматическими попытками переоткрытия.
|
||||||
PISystemTime reopenTimeout() { return property("reopenTimeout").toSystemTime(); }
|
PISystemTime reopenTimeout() { return property("reopenTimeout").toSystemTime(); }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Set threaded read callback
|
//! \~english Sets callback invoked after successful threaded reads.
|
||||||
//! \~russian Устанавливает callback потокового чтения
|
//! \~russian Устанавливает callback, вызываемый после успешного потокового чтения.
|
||||||
void setThreadedReadSlot(ReadRetFunc func);
|
void setThreadedReadSlot(ReadRetFunc func);
|
||||||
|
|
||||||
//! \~english Set custom data that will be passed to threaded read callback
|
//! \~english Sets custom user data passed to threaded read callback.
|
||||||
//! \~russian Устанавливает произвольный указатель, который будет передан в callback потокового чтения
|
//! \~russian Устанавливает пользовательские данные, передаваемые в callback потокового чтения.
|
||||||
void setThreadedReadData(void * d) { ret_data_ = d; }
|
void setThreadedReadData(void * d) { ret_data_ = d; }
|
||||||
|
|
||||||
//! \~english Set size of threaded read buffer
|
//! \~english Sets background read buffer size in bytes.
|
||||||
//! \~russian Устанавливает размер буфера потокового чтения
|
//! \~russian Устанавливает размер буфера фонового чтения в байтах.
|
||||||
void setThreadedReadBufferSize(int new_size);
|
void setThreadedReadBufferSize(int new_size);
|
||||||
|
|
||||||
//! \~english Returns size of threaded read buffer
|
//! \~english Returns background read buffer size in bytes.
|
||||||
//! \~russian Возвращает размер буфера потокового чтения
|
//! \~russian Возвращает размер буфера фонового чтения в байтах.
|
||||||
int threadedReadBufferSize() const { return threaded_read_buffer_size; }
|
int threadedReadBufferSize() const { return threaded_read_buffer_size; }
|
||||||
|
|
||||||
//! \~english Returns content of threaded read buffer
|
//! \~english Returns pointer to the internal threaded-read buffer.
|
||||||
//! \~russian Возвращает содержимое буфера потокового чтения
|
//! \~russian Возвращает указатель на внутренний буфер потокового чтения.
|
||||||
const uchar * threadedReadBuffer() const { return buffer_tr.data(); }
|
const uchar * threadedReadBuffer() const { return buffer_tr.data(); }
|
||||||
|
|
||||||
//! \~english Returns custom data that will be passed to threaded read callback
|
//! \~english Returns custom data passed to threaded read callback.
|
||||||
//! \~russian Возвращает произвольный указатель, который будет передан в callback потокового чтения
|
//! \~russian Возвращает пользовательские данные, передаваемые в callback потокового чтения.
|
||||||
void * threadedReadData() const { return ret_data_; }
|
void * threadedReadData() const { return ret_data_; }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns if threaded read is started
|
//! \~english Returns whether threaded read is running.
|
||||||
//! \~russian Возвращает запущен ли поток чтения
|
//! \~russian Возвращает, запущено ли потоковое чтение.
|
||||||
bool isThreadedRead() const;
|
bool isThreadedRead() const;
|
||||||
|
|
||||||
//! \~english Returns if threaded read is stopping
|
//! \~english Returns whether threaded read is stopping.
|
||||||
//! \~russian Возвращает останавливается ли поток чтения
|
//! \~russian Возвращает, находится ли потоковое чтение в процессе остановки.
|
||||||
bool isThreadedReadStopping() const { return read_thread.isStopping(); }
|
bool isThreadedReadStopping() const { return read_thread.isStopping(); }
|
||||||
|
|
||||||
//! \~english Start threaded read
|
//! \~english Starts threaded read.
|
||||||
//! \~russian Запускает потоковое чтение
|
//! \~russian Запускает потоковое чтение.
|
||||||
void startThreadedRead();
|
void startThreadedRead();
|
||||||
|
|
||||||
//! \~english Start threaded read and assign threaded read callback to "func"
|
//! \~english Sets threaded read callback to "func" and starts threaded read.
|
||||||
//! \~russian Запускает потоковое чтение и устанавливает callback потокового чтения в "func"
|
//! \~russian Устанавливает callback потокового чтения в "func" и запускает потоковое чтение.
|
||||||
void startThreadedRead(ReadRetFunc func);
|
void startThreadedRead(ReadRetFunc func);
|
||||||
|
|
||||||
//! \~english Stop threaded read.
|
//! \~english Requests threaded read stop.
|
||||||
//! \~russian Останавливает потоковое чтение.
|
//! \~russian Запрашивает остановку потокового чтения.
|
||||||
void stopThreadedRead();
|
void stopThreadedRead();
|
||||||
|
|
||||||
//! \~english Terminate threaded read.
|
//! \~english Terminate threaded read.
|
||||||
@@ -266,25 +276,30 @@ public:
|
|||||||
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
||||||
void terminateThreadedRead();
|
void terminateThreadedRead();
|
||||||
|
|
||||||
//! \~english Wait for threaded read finish no longer than "timeout".
|
//! \~english Waits until threaded read finishes or "timeout" expires.
|
||||||
//! \~russian Ожидает завершения потокового чтения в течении не более "timeout".
|
//! \~russian Ожидает завершения потокового чтения, но не дольше "timeout".
|
||||||
bool waitThreadedReadFinished(PISystemTime timeout = {});
|
bool waitThreadedReadFinished(PISystemTime timeout = {});
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns delay between unsuccessful threaded read attempts in milliseconds.
|
||||||
|
//! \~russian Возвращает задержку между безуспешными попытками потокового чтения в миллисекундах.
|
||||||
uint threadedReadTimeout() const { return threaded_read_timeout_ms; }
|
uint threadedReadTimeout() const { return threaded_read_timeout_ms; }
|
||||||
|
|
||||||
|
//! \~english Sets delay between unsuccessful threaded read attempts in milliseconds.
|
||||||
|
//! \~russian Устанавливает задержку между безуспешными попытками потокового чтения в миллисекундах.
|
||||||
void setThreadedReadTimeout(uint ms) { threaded_read_timeout_ms = ms; }
|
void setThreadedReadTimeout(uint ms) { threaded_read_timeout_ms = ms; }
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns if threaded write is started
|
//! \~english Returns whether threaded write is running.
|
||||||
//! \~russian Возвращает запущен ли поток записи
|
//! \~russian Возвращает, запущена ли потоковая запись.
|
||||||
bool isThreadedWrite() const;
|
bool isThreadedWrite() const;
|
||||||
|
|
||||||
//! \~english Start threaded write
|
//! \~english Starts threaded write.
|
||||||
//! \~russian Запускает потоковую запись
|
//! \~russian Запускает потоковую запись.
|
||||||
void startThreadedWrite();
|
void startThreadedWrite();
|
||||||
|
|
||||||
//! \~english Stop threaded write.
|
//! \~english Requests threaded write stop.
|
||||||
//! \~russian Останавливает потоковую запись.
|
//! \~russian Запрашивает остановку потоковой записи.
|
||||||
void stopThreadedWrite();
|
void stopThreadedWrite();
|
||||||
|
|
||||||
//! \~english Terminate threaded write.
|
//! \~english Terminate threaded write.
|
||||||
@@ -294,217 +309,225 @@ public:
|
|||||||
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
//! \~russian Старайтесь не использовать! Этот метод может привести к повреждению памяти!
|
||||||
void terminateThreadedWrite();
|
void terminateThreadedWrite();
|
||||||
|
|
||||||
//! \~english Wait for threaded write finish no longer than "timeout".
|
//! \~english Waits until threaded write finishes or "timeout" expires.
|
||||||
//! \~russian Ожидает завершения потоковой записи в течении не более "timeout".
|
//! \~russian Ожидает завершения потоковой записи, но не дольше "timeout".
|
||||||
bool waitThreadedWriteFinished(PISystemTime timeout = {});
|
bool waitThreadedWriteFinished(PISystemTime timeout = {});
|
||||||
|
|
||||||
//! \~english Clear threaded write task queue
|
//! \~english Clears queued threaded-write tasks.
|
||||||
//! \~russian Очищает очередь потоковой записи
|
//! \~russian Очищает очередь заданий потоковой записи.
|
||||||
void clearThreadedWriteQueue();
|
void clearThreadedWriteQueue();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Start both threaded read and threaded write
|
//! \~english Starts both threaded read and threaded write.
|
||||||
//! \~russian Запускает потоковое чтение и запись
|
//! \~russian Запускает потоковое чтение и потоковую запись.
|
||||||
void start();
|
void start();
|
||||||
|
|
||||||
//! \~english Stop both threaded read and threaded write.
|
//! \~english Requests stop for both threaded read and threaded write.
|
||||||
//! \~russian Останавливает потоковое чтение и запись.
|
//! \~russian Запрашивает остановку потокового чтения и потоковой записи.
|
||||||
void stop();
|
void stop();
|
||||||
|
|
||||||
//! \~english Stop both threaded read and threaded write and wait for finish.
|
//! \~english Stops both background threads and waits for completion.
|
||||||
//! \~russian Останавливает потоковое чтение и запись и ожидает завершения.
|
//! \~russian Останавливает оба фоновых потока и ожидает их завершения.
|
||||||
void stopAndWait(PISystemTime timeout = {});
|
void stopAndWait(PISystemTime timeout = {});
|
||||||
|
|
||||||
//! \~english Interrupt blocking operation.
|
//! \~english Interrupts a blocking device operation.
|
||||||
//! \~russian Прерывает блокирующую операцию.
|
//! \~russian Прерывает блокирующую операцию устройства.
|
||||||
virtual void interrupt() {}
|
virtual void interrupt() {}
|
||||||
|
|
||||||
|
|
||||||
//! \~english Read from device maximum "max_size" bytes to "read_to"
|
//! \~english Reads at most "max_size" bytes into "read_to".
|
||||||
//! \~russian Читает из устройства не более "max_size" байт в "read_to"
|
//! \~russian Читает в "read_to" не более "max_size" байт.
|
||||||
ssize_t read(void * read_to, ssize_t max_size);
|
ssize_t read(void * read_to, ssize_t max_size);
|
||||||
|
|
||||||
//! \~english Read from device to memory block "mb"
|
//! \~english Reads data into memory block "mb".
|
||||||
//! \~russian Читает из устройства в блок памяти "mb"
|
//! \~russian Читает данные в блок памяти "mb".
|
||||||
ssize_t read(PIMemoryBlock mb);
|
ssize_t read(PIMemoryBlock mb);
|
||||||
|
|
||||||
//! \~english Read from device maximum "max_size" bytes and returns them as PIByteArray
|
//! \~english Reads at most "max_size" bytes and returns them as \a PIByteArray.
|
||||||
//! \~russian Читает из устройства не более "max_size" байт и возвращает данные как PIByteArray
|
//! \~russian Читает не более "max_size" байт и возвращает их как \a PIByteArray.
|
||||||
PIByteArray read(ssize_t max_size);
|
PIByteArray read(ssize_t max_size);
|
||||||
|
|
||||||
//! \~english Returns the number of bytes that are available for reading.
|
//! \~english Returns the number of bytes that are available for reading.
|
||||||
//! \~russian Возвращает количество байт доступных для чтения
|
//! \~russian Возвращает количество байт доступных для чтения.
|
||||||
//! \~\details
|
//! \~\details
|
||||||
//! \~english This function is commonly used with sequential devices
|
//! \~english
|
||||||
//! to determine the number of bytes to allocate in a buffer before reading.
|
//! This function is commonly used with sequential devices to determine the number of bytes to allocate in a buffer before reading. If
|
||||||
//! If function returns -1 it mean that number of bytes undefined.
|
//! function returns -1 it mean that number of bytes undefined.
|
||||||
//! \~russian Эта функция как правило используется чтобы знать какой
|
//! \~russian
|
||||||
//! размер буфера нужен в памяти для чтения.
|
//! Эта функция как правило используется чтобы знать какой размер буфера нужен в памяти для чтения. Если функция возвращает -1 это
|
||||||
//! Если функция возвращает -1 это значит что количество байт для чтения не известно.
|
//! значит что количество байт для чтения не известно.
|
||||||
virtual ssize_t bytesAvailable() const { return -1; }
|
virtual ssize_t bytesAvailable() const { return -1; }
|
||||||
|
|
||||||
//! \~english Write maximum "max_size" bytes of "data" to device
|
//! \~english Writes at most "max_size" bytes from "data".
|
||||||
//! \~russian Пишет в устройство не более "max_size" байт из "data"
|
//! \~russian Записывает из "data" не более "max_size" байт.
|
||||||
ssize_t write(const void * data, ssize_t max_size);
|
ssize_t write(const void * data, ssize_t max_size);
|
||||||
|
|
||||||
//! \~english Read from device for "timeout" and return readed data as PIByteArray.
|
//! \~english Reads data for up to "timeout" and returns collected bytes.
|
||||||
//! \~russian Читает из устройства в течении "timeout" и возвращает данные как PIByteArray.
|
//! \~russian Читает данные в течение "timeout" и возвращает накопленные байты.
|
||||||
PIByteArray readForTime(PISystemTime timeout);
|
PIByteArray readForTime(PISystemTime timeout);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Add task to threaded write queue and return task ID
|
//! \~english Queues "data" for threaded write and returns task ID.
|
||||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
//! \~russian Помещает "data" в очередь потоковой записи и возвращает ID задания.
|
||||||
ullong writeThreaded(const void * data, ssize_t max_size) { return writeThreaded(PIByteArray(data, uint(max_size))); }
|
ullong writeThreaded(const void * data, ssize_t max_size) { return writeThreaded(PIByteArray(data, uint(max_size))); }
|
||||||
|
|
||||||
//! \~english Add task to threaded write queue and return task ID
|
//! \~english Queues byte array "data" for threaded write and returns task ID.
|
||||||
//! \~russian Добавляет данные в очередь на потоковую запись и возвращает ID задания
|
//! \~russian Помещает массив байт "data" в очередь потоковой записи и возвращает ID задания.
|
||||||
ullong writeThreaded(const PIByteArray & data);
|
ullong writeThreaded(const PIByteArray & data);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Configure device from section "section" of file "config_file", if "parent_section" parent section also will be read
|
//! \~english Configures the device from section "section" of file "config_file".
|
||||||
|
//! \~russian Настраивает устройство из секции "section" файла "config_file".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! If "parent_section" is true, inherited parameters are also read from the parent section.
|
||||||
//! \~russian
|
//! \~russian
|
||||||
|
//! Если "parent_section" равно true, то дополнительные параметры также читаются из родительской секции.
|
||||||
bool configure(const PIString & config_file, const PIString & section, bool parent_section = false);
|
bool configure(const PIString & config_file, const PIString & section, bool parent_section = false);
|
||||||
|
|
||||||
|
|
||||||
//! \~english Returns full unambiguous string prefix. \ref PIIODevice_sec7
|
//! \~english Returns device prefix used in full-path notation. \ref PIIODevice_sec7
|
||||||
//! \~russian Возвращает префикс устройства. \ref PIIODevice_sec7
|
//! \~russian Возвращает префикс устройства, используемый в полной строке пути. \ref PIIODevice_sec7
|
||||||
virtual PIConstChars fullPathPrefix() const { return ""; }
|
virtual PIConstChars fullPathPrefix() const { return ""; }
|
||||||
|
|
||||||
static PIConstChars fullPathPrefixS() { return ""; }
|
static PIConstChars fullPathPrefixS() { return ""; }
|
||||||
|
|
||||||
//! \~english Returns full unambiguous string, describes this device, \a fullPathPrefix() + "://" + ...
|
//! \~english Returns full-path representation of this device, \a fullPathPrefix() + "://" + ...
|
||||||
//! \~russian Возвращает строку полного описания для этого устройства, \a fullPathPrefix() + "://" + ...
|
//! \~russian Возвращает полную строку описания этого устройства, \a fullPathPrefix() + "://" + ...
|
||||||
PIString constructFullPath() const;
|
PIString constructFullPath() const;
|
||||||
|
|
||||||
//! \~english Configure device with parameters of full unambiguous string
|
//! \~english Configures the device from full-path parameters.
|
||||||
//! \~russian Настраивает устройство из параметров строки полного описания
|
//! \~russian Настраивает устройство из параметров полной строки описания.
|
||||||
void configureFromFullPath(const PIString & full_path);
|
void configureFromFullPath(const PIString & full_path);
|
||||||
|
|
||||||
//! \~english Returns PIVariantTypes::IODevice, describes this device
|
//! \~english Builds \a PIVariantTypes::IODevice description for this device.
|
||||||
//! \~russian Возвращает PIVariantTypes::IODevice, описывающий это устройство
|
//! \~russian Создает описание \a PIVariantTypes::IODevice для этого устройства.
|
||||||
PIVariantTypes::IODevice constructVariant() const;
|
PIVariantTypes::IODevice constructVariant() const;
|
||||||
|
|
||||||
//! \~english Configure device from PIVariantTypes::IODevice
|
//! \~english Configures the device from \a PIVariantTypes::IODevice.
|
||||||
//! \~russian Настраивает устройство из PIVariantTypes::IODevice
|
//! \~russian Настраивает устройство из \a PIVariantTypes::IODevice.
|
||||||
void configureFromVariant(const PIVariantTypes::IODevice & d);
|
void configureFromVariant(const PIVariantTypes::IODevice & d);
|
||||||
|
|
||||||
//! \~english Try to create new device by prefix, configure it with \a configureFromFullPath() and returns it.
|
//! \~english Try to create new device by prefix, configure it with \a configureFromFullPath() and returns it.
|
||||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromFullPath() и возвращает его
|
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromFullPath() и возвращает его.
|
||||||
static PIIODevice * createFromFullPath(const PIString & full_path);
|
static PIIODevice * createFromFullPath(const PIString & full_path);
|
||||||
|
|
||||||
//! \~english Try to create new device by prefix, configure it with \a configureFromVariant() and returns it.
|
//! \~english Try to create new device by prefix, configure it with \a configureFromVariant() and returns it.
|
||||||
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromVariant() и возвращает его
|
//! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromVariant() и возвращает его.
|
||||||
static PIIODevice * createFromVariant(const PIVariantTypes::IODevice & d);
|
static PIIODevice * createFromVariant(const PIVariantTypes::IODevice & d);
|
||||||
|
|
||||||
|
//! \~english Returns normalized full-path representation for "full_path".
|
||||||
|
//! \~russian Возвращает нормализованную полную строку пути для "full_path".
|
||||||
static PIString normalizeFullPath(const PIString & full_path);
|
static PIString normalizeFullPath(const PIString & full_path);
|
||||||
|
|
||||||
|
//! \~english Splits full-path string into path, mode and options.
|
||||||
|
//! \~russian Разбирает полную строку пути на путь, режим и опции.
|
||||||
static void splitFullPath(PIString fpwm, PIString * full_path, DeviceMode * mode = 0, DeviceOptions * opts = 0);
|
static void splitFullPath(PIString fpwm, PIString * full_path, DeviceMode * mode = 0, DeviceOptions * opts = 0);
|
||||||
|
|
||||||
//! \~english Returns fullPath prefixes of all registered devices
|
//! \~english Returns fullPath prefixes of all registered devices
|
||||||
//! \~russian Возвращает префиксы всех зарегистрированных устройств
|
//! \~russian Возвращает префиксы всех зарегистрированных устройств
|
||||||
static PIStringList availablePrefixes();
|
static PIStringList availablePrefixes();
|
||||||
|
|
||||||
//! \~english Returns class names of all registered devices
|
//! \~english Returns class names of all registered devices.
|
||||||
//! \~russian Возвращает имена классов всех зарегистрированных устройств
|
//! \~russian Возвращает имена классов всех зарегистрированных устройств.
|
||||||
static PIStringList availableClasses();
|
static PIStringList availableClasses();
|
||||||
|
|
||||||
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)());
|
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)());
|
||||||
|
|
||||||
|
|
||||||
EVENT_HANDLER(bool, open);
|
//! \~english Writes memory block "mb" to the device.
|
||||||
EVENT_HANDLER1(bool, open, const PIString &, _path);
|
//! \~russian Записывает в устройство блок памяти "mb".
|
||||||
bool open(DeviceMode _mode);
|
|
||||||
EVENT_HANDLER2(bool, open, const PIString &, _path, DeviceMode, _mode);
|
|
||||||
EVENT_HANDLER(bool, close);
|
|
||||||
EVENT_HANDLER1(ssize_t, write, PIByteArray, data);
|
|
||||||
|
|
||||||
//! \~english Write memory block "mb" to device
|
|
||||||
//! \~russian Пишет в устройство блок памяти "mb"
|
|
||||||
ssize_t write(const PIMemoryBlock & mb) { return write(mb.data(), mb.size()); }
|
ssize_t write(const PIMemoryBlock & mb) { return write(mb.data(), mb.size()); }
|
||||||
|
|
||||||
EVENT_VHANDLER(void, flush) { ; }
|
|
||||||
|
|
||||||
EVENT(opened);
|
|
||||||
EVENT(closed);
|
|
||||||
EVENT2(threadedReadEvent, const uchar *, readed, ssize_t, size);
|
|
||||||
EVENT2(threadedWriteEvent, ullong, id, ssize_t, written_size);
|
|
||||||
|
|
||||||
//! \handlers
|
//! \handlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn bool open()
|
//! \fn bool open()
|
||||||
//! \~english Open device
|
//! \~english Opens the device with current path and mode.
|
||||||
//! \~russian Открывает устройство
|
//! \~russian Открывает устройство с текущими путём и режимом.
|
||||||
|
EVENT_HANDLER(bool, open);
|
||||||
|
|
||||||
//! \fn bool open(const PIString & path)
|
//! \fn bool open(const PIString & path)
|
||||||
//! \~english Open device with path "path"
|
//! \~english Opens the device with path "path".
|
||||||
//! \~russian Открывает устройство с путём "path"
|
//! \~russian Открывает устройство с путём "path".
|
||||||
|
EVENT_HANDLER1(bool, open, const PIString &, _path);
|
||||||
|
|
||||||
//! \fn bool open(const DeviceMode & mode)
|
//! \fn bool open(DeviceMode mode)
|
||||||
//! \~english Open device with mode "mode"
|
//! \~english Opens the device with mode "mode".
|
||||||
//! \~russian Открывает устройство с режимом открытия "mode"
|
//! \~russian Открывает устройство с режимом "mode".
|
||||||
|
bool open(DeviceMode _mode);
|
||||||
|
|
||||||
//! \fn bool open(const PIString & path, const DeviceMode & mode)
|
//! \fn bool open(const PIString & path, DeviceMode mode)
|
||||||
//! \~english Open device with path "path" and mode "mode"
|
//! \~english Opens the device with path "path" and mode "mode".
|
||||||
//! \~russian Открывает устройство с путём "path" и режимом открытия "mode"
|
//! \~russian Открывает устройство с путём "path" и режимом "mode".
|
||||||
|
EVENT_HANDLER2(bool, open, const PIString &, _path, DeviceMode, _mode);
|
||||||
|
|
||||||
//! \fn bool close()
|
//! \fn bool close()
|
||||||
//! \~english Close device
|
//! \~english Closes the device.
|
||||||
//! \~russian Закрывает устройство
|
//! \~russian Закрывает устройство.
|
||||||
|
EVENT_HANDLER(bool, close);
|
||||||
|
|
||||||
//! \fn ssize_t write(PIByteArray data)
|
//! \fn ssize_t write(PIByteArray data)
|
||||||
//! \~english Write "data" to device
|
//! \~english Writes "data" to the device.
|
||||||
//! \~russian Пишет "data" в устройство
|
//! \~russian Записывает "data" в устройство.
|
||||||
|
EVENT_HANDLER1(ssize_t, write, PIByteArray, data);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \vhandlers
|
//! \vhandlers
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void flush()
|
//! \fn void flush()
|
||||||
//! \~english Immediate write all buffers
|
//! \~english Immediately flushes device buffers.
|
||||||
//! \~russian Немедленно записать все буферизированные данные
|
//! \~russian Немедленно сбрасывает буферы устройства.
|
||||||
|
EVENT_VHANDLER(void, flush) { ; }
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \events
|
//! \events
|
||||||
//! \{
|
//! \{
|
||||||
|
|
||||||
//! \fn void opened()
|
//! \fn void opened()
|
||||||
//! \~english Raise if succesfull open
|
//! \~english Raised after successful opening.
|
||||||
//! \~russian Вызывается при успешном открытии
|
//! \~russian Вызывается после успешного открытия.
|
||||||
|
EVENT(opened);
|
||||||
|
|
||||||
//! \fn void closed()
|
//! \fn void closed()
|
||||||
//! \~english Raise if succesfull close
|
//! \~english Raised after successful closing.
|
||||||
//! \~russian Вызывается при успешном закрытии
|
//! \~russian Вызывается после успешного закрытия.
|
||||||
|
EVENT(closed);
|
||||||
|
|
||||||
//! \fn void threadedReadEvent(const uchar * readed, ssize_t size)
|
//! \fn void threadedReadEvent(const uchar * readed, ssize_t size)
|
||||||
//! \~english Raise if read thread succesfull read some data
|
//! \~english Raised after threaded read receives some data.
|
||||||
//! \~russian Вызывается при успешном потоковом чтении данных
|
//! \~russian Вызывается после того, как потоковое чтение получило данные.
|
||||||
|
EVENT2(threadedReadEvent, const uchar *, readed, ssize_t, size);
|
||||||
|
|
||||||
//! \fn void threadedWriteEvent(ullong id, ssize_t written_size)
|
//! \fn void threadedWriteEvent(ullong id, ssize_t written_size)
|
||||||
//! \~english Raise if write thread successfull write some data of task with ID "id"
|
//! \~english Raised after threaded write processes task with ID "id".
|
||||||
//! \~russian Вызывается при успешной потоковой записи данных с ID задания "id"
|
//! \~russian Вызывается после того, как потоковая запись обработала задание с ID "id".
|
||||||
|
EVENT2(threadedWriteEvent, ullong, id, ssize_t, written_size);
|
||||||
|
|
||||||
//! \}
|
//! \}
|
||||||
//! \ioparams
|
//! \ioparams
|
||||||
//! \{
|
//! \{
|
||||||
#ifdef DOXYGEN
|
#ifdef DOXYGEN
|
||||||
//! \~english setReopenEnabled, default "true"
|
//! \~english setReopenEnabled, default "true".
|
||||||
//! \~russian setReopenEnabled, по умолчанию "true"
|
//! \~russian setReopenEnabled, по умолчанию "true".
|
||||||
bool reopenEnabled;
|
bool reopenEnabled;
|
||||||
|
|
||||||
//! \~english setReopenTimeout, default 1_s
|
//! \~english setReopenTimeout, default 1_s.
|
||||||
//! \~russian setReopenTimeout, по умолчанию 1_s
|
//! \~russian setReopenTimeout, по умолчанию 1_s.
|
||||||
int reopenTimeout;
|
int reopenTimeout;
|
||||||
|
|
||||||
//! \~english setThreadedReadBufferSize in bytes, default 4096
|
//! \~english setThreadedReadBufferSize in bytes, default 4096.
|
||||||
//! \~russian setThreadedReadBufferSize в байтах, по умолчанию 4096
|
//! \~russian setThreadedReadBufferSize в байтах, по умолчанию 4096.
|
||||||
int threadedReadBufferSize;
|
int threadedReadBufferSize;
|
||||||
#endif
|
#endif
|
||||||
//! \}
|
//! \}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
//! \~english Reimplement to configure device from entries "e_main" and "e_parent", cast arguments to \a PIConfig::Entry*
|
//! \~english Reimplement to configure the device from "e_main" and optional "e_parent" entries cast to \a PIConfig::Entry*.
|
||||||
//! \~russian
|
//! \~russian Переопределите для настройки устройства из записей "e_main" и необязательной "e_parent", приведённых к \a
|
||||||
|
//! PIConfig::Entry*.
|
||||||
virtual bool configureDevice(const void * e_main, const void * e_parent = 0) { return true; }
|
virtual bool configureDevice(const void * e_main, const void * e_parent = 0) { return true; }
|
||||||
|
|
||||||
//! \~english Reimplement to open device, return value will be set to "opened_" variable.
|
//! \~english Reimplement to open device, return value will be set to "opened_" variable.
|
||||||
@@ -513,8 +536,8 @@ protected:
|
|||||||
//! переменную "opened_". Не используйте напрямую, только через \a open()!
|
//! переменную "opened_". Не используйте напрямую, только через \a open()!
|
||||||
virtual bool openDevice() = 0; // use path_, type_, opened_, init_ variables
|
virtual bool openDevice() = 0; // use path_, type_, opened_, init_ variables
|
||||||
|
|
||||||
//! \~english Reimplement to close device, inverse return value will be set to "opened_" variable
|
//! \~english Reimplement to close the device; inverse return value is stored into "opened_".
|
||||||
//! \~russian Переопределите для закрытия устройства, обратное возвращаемое значение будет установлено в переменную "opened_"
|
//! \~russian Переопределите для закрытия устройства; обратное возвращаемое значение сохраняется в "opened_".
|
||||||
virtual bool closeDevice() { return true; } // use path_, type_, opened_, init_ variables
|
virtual bool closeDevice() { return true; } // use path_, type_, opened_, init_ variables
|
||||||
|
|
||||||
//! \~english Reimplement this function to read from your device
|
//! \~english Reimplement this function to read from your device
|
||||||
@@ -531,44 +554,42 @@ protected:
|
|||||||
return -2;
|
return -2;
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Function executed when thread read some data, default implementation execute external callback "ret_func_"
|
//! \~english Called after threaded read receives data; default implementation calls the external callback set by \a
|
||||||
//! \~russian Метод вызывается после каждого успешного потокового чтения, по умолчанию вызывает callback "ret_func_"
|
//! setThreadedReadSlot().
|
||||||
|
//! \~russian Вызывается после успешного потокового чтения; по умолчанию вызывает внешний callback, заданный через \a
|
||||||
|
//! setThreadedReadSlot().
|
||||||
virtual bool threadedRead(const uchar * readed, ssize_t size);
|
virtual bool threadedRead(const uchar * readed, ssize_t size);
|
||||||
|
|
||||||
//! \~english Reimplement to construct full unambiguous string, describes this device.
|
//! \~english Reimplement to build device-specific part of full-path string. Default implementation returns \a path().
|
||||||
//! Default implementation returns \a path()
|
//! \~russian Переопределите для построения device-specific части полной строки пути. По умолчанию возвращает \a path().
|
||||||
//! \~russian Переопределите для создания строки полного описания устройства.
|
|
||||||
//! По умолчанию возвращает \a path()
|
|
||||||
virtual PIString constructFullPathDevice() const { return path(); }
|
virtual PIString constructFullPathDevice() const { return path(); }
|
||||||
|
|
||||||
//! \~english Reimplement to configure your device with parameters of full unambiguous string.
|
//! \~english Reimplement to configure the device from device-specific full-path parameters. Default implementation calls \a setPath().
|
||||||
//! Default implementation call \a setPath()
|
//! \~russian Переопределите для настройки устройства из device-specific параметров полной строки пути. По умолчанию вызывает \a
|
||||||
//! \~russian Переопределите для настройки устройства из строки полного описания.
|
//! setPath().
|
||||||
//! По умолчанию вызывает \a setPath()
|
|
||||||
virtual void configureFromFullPathDevice(const PIString & full_path) { setPath(full_path); }
|
virtual void configureFromFullPathDevice(const PIString & full_path) { setPath(full_path); }
|
||||||
|
|
||||||
//! \~english Reimplement to construct device properties.
|
//! \~english Reimplement to build device-specific variant properties. Default implementation returns \a PIPropertyStorage with "path".
|
||||||
//! Default implementation return PIPropertyStorage with \"path\" entry
|
//! \~russian Переопределите для построения device-specific свойств варианта. По умолчанию возвращает \a PIPropertyStorage со свойством
|
||||||
//! \~russian Переопределите для создания свойств устройства.
|
//! "path".
|
||||||
//! По умолчанию возвращает PIPropertyStorage со свойством \"path\"
|
|
||||||
virtual PIPropertyStorage constructVariantDevice() const;
|
virtual PIPropertyStorage constructVariantDevice() const;
|
||||||
|
|
||||||
//! \~english Reimplement to configure your device from PIPropertyStorage. Options and mode already applied.
|
//! \~english Reimplement to configure the device from \a PIPropertyStorage. Mode and options are already applied.
|
||||||
//! Default implementation apply \"path\" entry
|
//! Default implementation applies "path".
|
||||||
//! \~russian Переопределите для настройки устройства из PIPropertyStorage. Опции и режим уже применены.
|
//! \~russian Переопределите для настройки устройства из \a PIPropertyStorage. Режим и опции уже применены.
|
||||||
//! По умолчанию устанавливает свойство \"path\"
|
//! Реализация по умолчанию применяет "path".
|
||||||
virtual void configureFromVariantDevice(const PIPropertyStorage & d);
|
virtual void configureFromVariantDevice(const PIPropertyStorage & d);
|
||||||
|
|
||||||
//! \~english Reimplement to apply new device options
|
//! \~english Reimplement to react to changed device options.
|
||||||
//! \~russian Переопределите для применения новых опций устройства
|
//! \~russian Переопределите для реакции на изменение опций устройства.
|
||||||
virtual void optionsChanged() { ; }
|
virtual void optionsChanged() { ; }
|
||||||
|
|
||||||
//! \~english Reimplement to return correct \a DeviceInfoFlags. Default implementation returns 0
|
//! \~english Reimplement to report actual \a DeviceInfoFlags. Default implementation returns 0.
|
||||||
//! \~russian Переопределите для возврата правильных \a DeviceInfoFlags. По умолчанию возвращает 0
|
//! \~russian Переопределите для возврата актуальных \a DeviceInfoFlags. По умолчанию возвращает 0.
|
||||||
virtual DeviceInfoFlags deviceInfoFlags() const { return 0; }
|
virtual DeviceInfoFlags deviceInfoFlags() const { return 0; }
|
||||||
|
|
||||||
//! \~english Reimplement to apply new \a threadedReadBufferSize()
|
//! \~english Reimplement to react to new \a threadedReadBufferSize().
|
||||||
//! \~russian Переопределите для применения нового \a threadedReadBufferSize()
|
//! \~russian Переопределите для реакции на новое значение \a threadedReadBufferSize().
|
||||||
virtual void threadedReadBufferSizeChanged() { ; }
|
virtual void threadedReadBufferSizeChanged() { ; }
|
||||||
|
|
||||||
static PIIODevice * newDeviceByPrefix(const char * prefix);
|
static PIIODevice * newDeviceByPrefix(const char * prefix);
|
||||||
|
|||||||
@@ -1,3 +1,13 @@
|
|||||||
|
/*! \file piiodevicesmodule.h
|
||||||
|
* \ingroup IO
|
||||||
|
* \~\brief
|
||||||
|
* \~english Umbrella include for common IO device headers
|
||||||
|
* \~russian Общий include для основных заголовков устройств ввода/вывода
|
||||||
|
*
|
||||||
|
* \~\details
|
||||||
|
* \~english Includes the main public headers for files, buses, peers, and device-oriented IO helpers.
|
||||||
|
* \~russian Подключает основные публичные заголовки для файлов, шин, peer-компонентов и вспомогательных IO-устройств.
|
||||||
|
*/
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Module includes
|
Module includes
|
||||||
@@ -34,11 +44,12 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides base IO device, many realizations and utilites to work with %PIIODevice
|
//! This module contains the base %PIIODevice abstraction, concrete device implementations
|
||||||
|
//! and helper surfaces such as this convenience umbrella header.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают базовый класс устройства ввода/вывода, много реализаций и утилит
|
//! Модуль содержит базовую абстракцию %PIIODevice, конкретные реализации устройств
|
||||||
//! для работы с %PIIODevice
|
//! и вспомогательные поверхности, включая этот общий umbrella-заголовок.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piiostream.h
|
//! \~\file piiostream.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english PIBinaryStream functionality for PIIODevice
|
//! \~english Text and binary stream adapters for PIIODevice
|
||||||
* \~russian Функциональность PIBinaryStream для PIIODevice
|
//! \~russian Адаптеры текстовых и бинарных потоков для PIIODevice
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PIBinaryStream functionality for PIIODevice
|
PIBinaryStream functionality for PIIODevice
|
||||||
@@ -30,35 +29,46 @@
|
|||||||
#include "pitextstream.h"
|
#include "pitextstream.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english PIBinaryStream functionality for PIIODevice.
|
//! \~english %PIBinaryStream adapter over a \a PIIODevice.
|
||||||
//! \~russian Функциональность PIBinaryStream для PIIODevice.
|
//! \~russian Адаптер %PIBinaryStream поверх \a PIIODevice.
|
||||||
//! \~english See details \ref iostream
|
//! \~\details
|
||||||
//! \~russian Подробнее \ref iostream
|
//! \~english
|
||||||
|
//! Provides binary stream operations for PIIODevice-based devices.
|
||||||
|
//! See \ref iostream for the generic stream API.
|
||||||
|
//! \~russian
|
||||||
|
//! Предоставляет операции бинарного потока для устройств на основе PIIODevice.
|
||||||
|
//! Общий API потоков описан в \ref iostream.
|
||||||
class PIP_EXPORT PIIOBinaryStream: public PIBinaryStream<PIIOBinaryStream> {
|
class PIP_EXPORT PIIOBinaryStream: public PIBinaryStream<PIIOBinaryStream> {
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs %PIIOBinaryStream for "device" device
|
//! \~english Constructs a stream bound to "device".
|
||||||
//! \~russian Создает %PIIOBinaryStream для устройства "device"
|
//! \~russian Создает поток, привязанный к устройству "device".
|
||||||
PIIOBinaryStream(PIIODevice * device = nullptr): dev(device) {}
|
PIIOBinaryStream(PIIODevice * device = nullptr): dev(device) {}
|
||||||
|
|
||||||
//! \~english Assign "device" device
|
//! \~english Rebinds the stream to "device" and resets read-error state.
|
||||||
//! \~russian Назначает устройство "device"
|
//! \~russian Перепривязывает поток к устройству "device" и сбрасывает состояние ошибки чтения.
|
||||||
void setDevice(PIIODevice * device) {
|
void setDevice(PIIODevice * device) {
|
||||||
dev = device;
|
dev = device;
|
||||||
resetReadError();
|
resetReadError();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Appends raw bytes through the bound device.
|
||||||
|
//! \~russian Добавляет сырые байты через привязанное устройство.
|
||||||
bool binaryStreamAppendImp(const void * d, size_t s) {
|
bool binaryStreamAppendImp(const void * d, size_t s) {
|
||||||
if (!dev) return false;
|
if (!dev) return false;
|
||||||
return (dev->write(d, s) == (int)s);
|
return (dev->write(d, s) == (int)s);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Reads raw bytes from the bound device.
|
||||||
|
//! \~russian Читает сырые байты из привязанного устройства.
|
||||||
bool binaryStreamTakeImp(void * d, size_t s) {
|
bool binaryStreamTakeImp(void * d, size_t s) {
|
||||||
if (!dev) return false;
|
if (!dev) return false;
|
||||||
return (dev->read(d, s) == (int)s);
|
return (dev->read(d, s) == (int)s);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Returns the number of bytes currently available in the device.
|
||||||
|
//! \~russian Возвращает количество байт, доступных в устройстве в данный момент.
|
||||||
ssize_t binaryStreamSizeImp() const {
|
ssize_t binaryStreamSizeImp() const {
|
||||||
if (!dev) return 0;
|
if (!dev) return 0;
|
||||||
return dev->bytesAvailable();
|
return dev->bytesAvailable();
|
||||||
@@ -69,27 +79,36 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english PITextStream functionality for PIIODevice.
|
//! \~english %PITextStream adapter over a \a PIIODevice.
|
||||||
//! \~russian Функциональность PITextStream для PIIODevice.
|
//! \~russian Адаптер %PITextStream поверх \a PIIODevice.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! Provides text stream operations for PIIODevice-based devices.
|
||||||
|
//! \~russian
|
||||||
|
//! Предоставляет операции текстового потока для устройств на основе PIIODevice.
|
||||||
class PIP_EXPORT PIIOTextStream: public PITextStream<PIIOBinaryStream> {
|
class PIP_EXPORT PIIOTextStream: public PITextStream<PIIOBinaryStream> {
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs %PIIOTextStream for "device" device
|
//! \~english Constructs a text stream bound to "device".
|
||||||
//! \~russian Создает %PIIOTextStream для устройства "device"
|
//! \~russian Создает текстовый поток, привязанный к устройству "device".
|
||||||
PIIOTextStream(PIIODevice * device): PITextStream<PIIOBinaryStream>(&bin_stream), bin_stream(device) {}
|
PIIOTextStream(PIIODevice * device): PITextStream<PIIOBinaryStream>(&bin_stream), bin_stream(device) {}
|
||||||
|
|
||||||
//! \~english Contructs %PIIOTextStream for "string" string
|
//! \~english Constructs a text stream over "string" using "mode".
|
||||||
//! \~russian Создает %PIIOTextStream для строки "string"
|
//! \~russian Создает текстовый поток поверх строки "string" с режимом "mode".
|
||||||
PIIOTextStream(PIString * string, PIIODevice::DeviceMode mode): PITextStream<PIIOBinaryStream>(&bin_stream) {
|
PIIOTextStream(PIString * string, PIIODevice::DeviceMode mode): PITextStream<PIIOBinaryStream>(&bin_stream) {
|
||||||
io_string = new PIIOString(string, mode);
|
io_string = new PIIOString(string, mode);
|
||||||
bin_stream.setDevice(io_string);
|
bin_stream.setDevice(io_string);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Destroys the stream and owned temporary \a PIIOString, if any.
|
||||||
|
//! \~russian Уничтожает поток и временный \a PIIOString, которым он владеет, если он был создан.
|
||||||
~PIIOTextStream() {
|
~PIIOTextStream() {
|
||||||
if (io_string) delete io_string;
|
if (io_string) delete io_string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Rebinds the text stream to another device.
|
||||||
|
//! \~russian Перепривязывает текстовый поток к другому устройству.
|
||||||
void setDevice(PIIODevice * device) {
|
void setDevice(PIIODevice * device) {
|
||||||
bin_stream = PIIOBinaryStream(device);
|
bin_stream = PIIOBinaryStream(device);
|
||||||
setStream(&bin_stream);
|
setStream(&bin_stream);
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
/*! \file piiostring.h
|
//! \~\ingroup IO
|
||||||
* \ingroup IO
|
//! \~\{
|
||||||
* \~\brief
|
//! \~\file piiostring.h
|
||||||
* \~english PIIODevice wrapper around PIString
|
//! \~\brief
|
||||||
* \~russian Обертка PIIODevice вокруг PIString
|
//! \~english PIIODevice wrapper around PIString
|
||||||
*/
|
//! \~russian Обертка PIIODevice вокруг PIString
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
PIIODevice wrapper around PIString
|
PIIODevice wrapper around PIString
|
||||||
@@ -29,20 +30,23 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english PIIODevice wrapper around PIString.
|
//! \~english PIIODevice wrapper around PIString.
|
||||||
//! \~russian Обёртка PIIODevice вокруг PIString.
|
//! \~russian Обёртка PIIODevice вокруг PIString.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english PIIOString provides a PIIODevice interface for reading from and writing to PIString objects.
|
||||||
|
//! \~russian PIIOString предоставляет интерфейс PIIODevice для чтения и записи объектов PIString.
|
||||||
class PIP_EXPORT PIIOString: public PIIODevice {
|
class PIP_EXPORT PIIOString: public PIIODevice {
|
||||||
PIIODEVICE(PIIOString, "");
|
PIIODEVICE(PIIOString, "");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs %PIIOString with "string" content and "mode" open mode
|
//! \~english Constructs %PIIOString with "string" content and "mode" open mode.
|
||||||
//! \~russian Создает %PIIOString с содержимым "string" и режимом открытия "mode"
|
//! \~russian Создает %PIIOString с содержимым "string" и режимом открытия "mode".
|
||||||
explicit PIIOString(PIString * string = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadOnly);
|
explicit PIIOString(PIString * string = 0, PIIODevice::DeviceMode mode = PIIODevice::ReadOnly);
|
||||||
|
|
||||||
//! \~english Contructs %PIIOString with "string" content only for read
|
//! \~english Constructs %PIIOString with "string" content only for read.
|
||||||
//! \~russian Создает %PIIOString с содержимым "string" только для чтения
|
//! \~russian Создает %PIIOString с содержимым "string" только для чтения.
|
||||||
explicit PIIOString(const PIString & string);
|
explicit PIIOString(const PIString & string);
|
||||||
|
|
||||||
//! \~english Returns content
|
//! \~english Returns content
|
||||||
@@ -61,8 +65,8 @@ public:
|
|||||||
//! \~russian Открывает содержимое "string" только для чтения
|
//! \~russian Открывает содержимое "string" только для чтения
|
||||||
bool open(const PIString & string);
|
bool open(const PIString & string);
|
||||||
|
|
||||||
//! \~english Returns if position is at the end of content
|
//! \~english Returns if position is at the end of content.
|
||||||
//! \~russian Возвращает в конце содержимого ли позиция
|
//! \~russian Возвращает, находится ли позиция в конце содержимого.
|
||||||
bool isEnd() const;
|
bool isEnd() const;
|
||||||
|
|
||||||
|
|
||||||
@@ -79,12 +83,12 @@ public:
|
|||||||
void seekToEnd();
|
void seekToEnd();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Read one text line and return it
|
//! \~english Reads one text line and returns it.
|
||||||
//! \~russian Читает одну строку и возвращает её
|
//! \~russian Читает одну текстовую строку и возвращает её.
|
||||||
PIString readLine();
|
PIString readLine();
|
||||||
|
|
||||||
//! \~english Insert string "string" into content at current position
|
//! \~english Inserts string "string" into content at current position.
|
||||||
//! \~russian Вставляет строку "string" в содержимое буфера в текущую позицию
|
//! \~russian Вставляет строку "string" в содержимое буфера в текущую позицию.
|
||||||
int writeString(const PIString & string);
|
int writeString(const PIString & string);
|
||||||
|
|
||||||
ssize_t bytesAvailable() const override;
|
ssize_t bytesAvailable() const override;
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pipeer.h
|
//! \~\file pipeer.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Peering net node
|
//! \~english Peer-to-peer network node
|
||||||
* \~russian Элемент пиринговой сети
|
//! \~russian Узел одноранговой сети
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Peer - named I/O ethernet node, forming self-organized peering network
|
Peer - named I/O ethernet node, forming self-organized peering network
|
||||||
@@ -29,6 +28,16 @@
|
|||||||
#include "pidiagnostics.h"
|
#include "pidiagnostics.h"
|
||||||
#include "piethernet.h"
|
#include "piethernet.h"
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Named network peer built on top of %PIIODevice.
|
||||||
|
//! \~russian Именованный сетевой пир, построенный поверх %PIIODevice.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! The class discovers peers, routes packets by peer name and can expose a trusted-peer stream through inherited \a read() and \a write().
|
||||||
|
//! \~russian
|
||||||
|
//! Класс обнаруживает пиры, маршрутизирует пакеты по имени пира и может предоставлять поток trusted-peer через унаследованные \a read() и
|
||||||
|
//! \a write().
|
||||||
class PIP_EXPORT PIPeer: public PIIODevice {
|
class PIP_EXPORT PIPeer: public PIIODevice {
|
||||||
PIIODEVICE(PIPeer, "peer");
|
PIIODEVICE(PIPeer, "peer");
|
||||||
|
|
||||||
@@ -36,39 +45,96 @@ private:
|
|||||||
class PeerData;
|
class PeerData;
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs a peer node with local name "name".
|
||||||
|
//! \~russian Создает пиринговый узел с локальным именем "name".
|
||||||
explicit PIPeer(const PIString & name = PIString());
|
explicit PIPeer(const PIString & name = PIString());
|
||||||
|
|
||||||
|
//! \~english Destroys the peer node.
|
||||||
|
//! \~russian Уничтожает пиринговый узел.
|
||||||
virtual ~PIPeer();
|
virtual ~PIPeer();
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Public information about a discovered peer.
|
||||||
|
//! \~russian Общедоступная информация об обнаруженном пире.
|
||||||
class PIP_EXPORT PeerInfo {
|
class PIP_EXPORT PeerInfo {
|
||||||
friend class PIPeer;
|
friend class PIPeer;
|
||||||
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an empty peer description.
|
||||||
|
//! \~russian Создает пустое описание пира.
|
||||||
PeerInfo() {
|
PeerInfo() {
|
||||||
dist = sync = cnt = 0;
|
dist = sync = cnt = 0;
|
||||||
trace = -1;
|
trace = -1;
|
||||||
was_update = false;
|
was_update = false;
|
||||||
_data = 0;
|
_data = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Destroys the peer description.
|
||||||
|
//! \~russian Уничтожает описание пира.
|
||||||
~PeerInfo() {}
|
~PeerInfo() {}
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Network address of a peer endpoint.
|
||||||
|
//! \~russian Сетевой адрес конечной точки пира.
|
||||||
struct PIP_EXPORT PeerAddress {
|
struct PIP_EXPORT PeerAddress {
|
||||||
|
//! \~english Constructs a peer address with address and netmask.
|
||||||
|
//! \~russian Создает адрес пира с адресом и маской сети.
|
||||||
PeerAddress(const PINetworkAddress & a = PINetworkAddress(), const PINetworkAddress & m = PINetworkAddress("255.255.255.0"));
|
PeerAddress(const PINetworkAddress & a = PINetworkAddress(), const PINetworkAddress & m = PINetworkAddress("255.255.255.0"));
|
||||||
|
|
||||||
|
//! \~english Returns whether this address has a valid measured ping.
|
||||||
|
//! \~russian Возвращает, есть ли для этого адреса валидный измеренный ping.
|
||||||
bool isAvailable() const { return ping > 0; }
|
bool isAvailable() const { return ping > 0; }
|
||||||
|
|
||||||
|
//! \~english Peer address.
|
||||||
|
//! \~russian Адрес пира.
|
||||||
PINetworkAddress address;
|
PINetworkAddress address;
|
||||||
|
|
||||||
|
//! \~english Netmask for the address.
|
||||||
|
//! \~russian Маска сети для адреса.
|
||||||
PINetworkAddress netmask;
|
PINetworkAddress netmask;
|
||||||
|
|
||||||
|
//! \~english Last measured ping in milliseconds, or a negative value if unknown.
|
||||||
|
//! \~russian Последний измеренный ping в миллисекундах, либо отрицательное значение если он неизвестен.
|
||||||
double ping; // ms
|
double ping; // ms
|
||||||
|
|
||||||
|
//! \~english Returns whether a ping request is currently pending.
|
||||||
|
//! \~russian Показывает, ожидается ли сейчас ответ на ping-запрос.
|
||||||
bool wait_ping;
|
bool wait_ping;
|
||||||
|
|
||||||
|
//! \~english Timestamp of the last ping request or reply.
|
||||||
|
//! \~russian Временная метка последнего ping-запроса или ответа.
|
||||||
PISystemTime last_ping;
|
PISystemTime last_ping;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Peer name.
|
||||||
|
//! \~russian Имя пира.
|
||||||
PIString name;
|
PIString name;
|
||||||
|
|
||||||
|
//! \~english Known addresses of the peer.
|
||||||
|
//! \~russian Известные адреса пира.
|
||||||
PIVector<PeerAddress> addresses;
|
PIVector<PeerAddress> addresses;
|
||||||
|
|
||||||
|
//! \~english Distance in hops from the local peer (0 for direct neighbours).
|
||||||
|
//! \~russian Расстояние в хопах от локального пира (0 для прямых соседей).
|
||||||
int dist;
|
int dist;
|
||||||
|
|
||||||
|
//! \~english Names of direct neighbours for this peer.
|
||||||
|
//! \~russian Имена прямых соседей этого пира.
|
||||||
PIStringList neighbours;
|
PIStringList neighbours;
|
||||||
|
|
||||||
|
//! \~english Returns whether the peer is a direct neighbour.
|
||||||
|
//! \~russian Возвращает, является ли пир прямым соседом.
|
||||||
bool isNeighbour() const { return dist == 0; }
|
bool isNeighbour() const { return dist == 0; }
|
||||||
|
|
||||||
|
//! \~english Returns the best known ping in milliseconds.
|
||||||
|
//! \~russian Возвращает наилучший известный ping в миллисекундах.
|
||||||
int ping() const;
|
int ping() const;
|
||||||
|
|
||||||
|
//! \~english Returns the fastest known address of the peer.
|
||||||
|
//! \~russian Возвращает самый быстрый известный адрес пира.
|
||||||
PINetworkAddress fastestAddress() const;
|
PINetworkAddress fastestAddress() const;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -87,47 +153,148 @@ public:
|
|||||||
|
|
||||||
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
BINARY_STREAM_FRIEND(PIPeer::PeerInfo);
|
||||||
|
|
||||||
|
//! \~english Sends byte array "data" to peer "to".
|
||||||
|
//! \~russian Отправляет массив байт "data" пиру "to".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sends the specified byte array to the peer identified by name using the most efficient route.
|
||||||
|
//! \~russian Отправляет указанный байтовый массив пиру, идентифицируемому по имени, используя наиболее эффективный маршрут.
|
||||||
bool send(const PIString & to, const PIByteArray & data) { return send(to, data.data(), data.size_s()); }
|
bool send(const PIString & to, const PIByteArray & data) { return send(to, data.data(), data.size_s()); }
|
||||||
|
|
||||||
|
//! \~english Sends string "data" to peer "to".
|
||||||
|
//! \~russian Отправляет строку "data" пиру "to".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sends the specified string to the peer identified by name using the most efficient route.
|
||||||
|
//! \~russian Отправляет указанную строку пиру, идентифицируемому по имени, используя наиболее эффективный маршрут.
|
||||||
bool send(const PIString & to, const PIString & data) { return send(to, data.data(), data.size_s()); }
|
bool send(const PIString & to, const PIString & data) { return send(to, data.data(), data.size_s()); }
|
||||||
|
|
||||||
|
//! \~english Sends raw buffer to peer "to".
|
||||||
|
//! \~russian Отправляет сырой буфер пиру "to".
|
||||||
bool send(const PIString & to, const void * data, int size);
|
bool send(const PIString & to, const void * data, int size);
|
||||||
|
|
||||||
|
//! \~english Sends byte array "data" to peer described by "to".
|
||||||
|
//! \~russian Отправляет массив байт "data" пиру, описанному в "to".
|
||||||
bool send(const PeerInfo & to, const PIByteArray & data) { return send(to.name, data.data(), data.size_s()); }
|
bool send(const PeerInfo & to, const PIByteArray & data) { return send(to.name, data.data(), data.size_s()); }
|
||||||
|
|
||||||
|
//! \~english Sends string "data" to peer described by "to".
|
||||||
|
//! \~russian Отправляет строку "data" пиру, описанному в "to".
|
||||||
bool send(const PeerInfo & to, const PIString & data) { return send(to.name, data.data(), data.size_s()); }
|
bool send(const PeerInfo & to, const PIString & data) { return send(to.name, data.data(), data.size_s()); }
|
||||||
|
|
||||||
|
//! \~english Sends raw buffer to peer described by "to".
|
||||||
|
//! \~russian Отправляет сырой буфер пиру, описанному в "to".
|
||||||
bool send(const PeerInfo & to, const void * data, int size) { return send(to.name, data, size); }
|
bool send(const PeerInfo & to, const void * data, int size) { return send(to.name, data, size); }
|
||||||
|
|
||||||
|
//! \~english Sends byte array "data" to peer pointer "to".
|
||||||
|
//! \~russian Отправляет массив байт "data" пиру по указателю "to".
|
||||||
bool send(const PeerInfo * to, const PIByteArray & data);
|
bool send(const PeerInfo * to, const PIByteArray & data);
|
||||||
|
|
||||||
|
//! \~english Sends string "data" to peer pointer "to".
|
||||||
|
//! \~russian Отправляет строку "data" пиру по указателю "to".
|
||||||
bool send(const PeerInfo * to, const PIString & data);
|
bool send(const PeerInfo * to, const PIString & data);
|
||||||
|
|
||||||
|
//! \~english Sends raw buffer to peer pointer "to".
|
||||||
|
//! \~russian Отправляет сырой буфер пиру по указателю "to".
|
||||||
bool send(const PeerInfo * to, const void * data, int size);
|
bool send(const PeerInfo * to, const void * data, int size);
|
||||||
|
|
||||||
|
//! \~english Sends byte array "data" to all known peers.
|
||||||
|
//! \~russian Отправляет массив байт "data" всем известным пирам.
|
||||||
void sendToAll(const PIByteArray & data);
|
void sendToAll(const PIByteArray & data);
|
||||||
|
|
||||||
|
//! \~english Sends string "data" to all known peers.
|
||||||
|
//! \~russian Отправляет строку "data" всем известным пирам.
|
||||||
void sendToAll(const PIString & data);
|
void sendToAll(const PIString & data);
|
||||||
|
|
||||||
|
//! \~english Sends raw buffer to all known peers.
|
||||||
|
//! \~russian Отправляет сырой буфер всем известным пирам.
|
||||||
void sendToAll(const void * data, int size);
|
void sendToAll(const void * data, int size);
|
||||||
|
|
||||||
|
//! \~english Returns whether multicast reception is active.
|
||||||
|
//! \~russian Возвращает, активно ли получение multicast-пакетов.
|
||||||
bool isMulticastReceive() const { return !eths_mcast.isEmpty(); }
|
bool isMulticastReceive() const { return !eths_mcast.isEmpty(); }
|
||||||
|
|
||||||
|
//! \~english Returns whether broadcast reception is active.
|
||||||
|
//! \~russian Возвращает, активно ли получение broadcast-пакетов.
|
||||||
bool isBroadcastReceive() const { return !eths_bcast.isEmpty(); }
|
bool isBroadcastReceive() const { return !eths_bcast.isEmpty(); }
|
||||||
|
|
||||||
|
//! \~english Returns service-channel diagnostics.
|
||||||
|
//! \~russian Возвращает диагностику служебного канала.
|
||||||
PIDiagnostics & diagnosticService() { return diag_s; }
|
PIDiagnostics & diagnosticService() { return diag_s; }
|
||||||
|
|
||||||
|
//! \~english Returns payload-channel diagnostics.
|
||||||
|
//! \~russian Возвращает диагностику канала данных.
|
||||||
PIDiagnostics & diagnosticData() { return diag_d; }
|
PIDiagnostics & diagnosticData() { return diag_d; }
|
||||||
|
|
||||||
|
//! \~english Returns all currently known peers.
|
||||||
|
//! \~russian Возвращает всех известных на данный момент пиров.
|
||||||
const PIVector<PIPeer::PeerInfo> & allPeers() const { return peers; }
|
const PIVector<PIPeer::PeerInfo> & allPeers() const { return peers; }
|
||||||
|
|
||||||
|
//! \~english Returns whether a peer with name "name" is known.
|
||||||
|
//! \~russian Возвращает, известен ли пир с именем "name".
|
||||||
bool isPeerExists(const PIString & name) const { return getPeerByName(name) != 0; }
|
bool isPeerExists(const PIString & name) const { return getPeerByName(name) != 0; }
|
||||||
|
|
||||||
|
//! \~english Returns peer information by name, or null if absent.
|
||||||
|
//! \~russian Возвращает информацию о пире по имени, либо null если пир не найден.
|
||||||
const PeerInfo * getPeerByName(const PIString & name) const { return peers_map.value(name, 0); }
|
const PeerInfo * getPeerByName(const PIString & name) const { return peers_map.value(name, 0); }
|
||||||
|
|
||||||
|
//! \~english Returns information about the local peer.
|
||||||
|
//! \~russian Возвращает информацию о локальном пире.
|
||||||
const PeerInfo & selfInfo() const { return self_info; }
|
const PeerInfo & selfInfo() const { return self_info; }
|
||||||
|
|
||||||
|
//! \~english Returns routing map used to reach known peers.
|
||||||
|
//! \~russian Возвращает карту маршрутов, используемую для доступа к известным пирам.
|
||||||
const PIMap<PIString, PIVector<PeerInfo *>> & _peerMap() const { return addresses_map; }
|
const PIMap<PIString, PIVector<PeerInfo *>> & _peerMap() const { return addresses_map; }
|
||||||
|
|
||||||
|
//! \~english Rebuilds the peer network state and restarts discovery sockets.
|
||||||
|
//! \~russian Перестраивает состояние сети пиров и перезапускает сокеты обнаружения.
|
||||||
void reinit();
|
void reinit();
|
||||||
|
|
||||||
|
//! \~english Locks the peer list for manual external access.
|
||||||
|
//! \~russian Блокирует список пиров для внешнего ручного доступа.
|
||||||
void lock() { peers_mutex.lock(); }
|
void lock() { peers_mutex.lock(); }
|
||||||
|
|
||||||
|
//! \~english Unlocks the peer list after external access.
|
||||||
|
//! \~russian Снимает блокировку списка пиров после внешнего доступа.
|
||||||
void unlock() { peers_mutex.unlock(); }
|
void unlock() { peers_mutex.unlock(); }
|
||||||
|
|
||||||
|
//! \~english Changes local peer name and updates related diagnostics names.
|
||||||
|
//! \~russian Изменяет имя локального пира и обновляет связанные диагностические имена.
|
||||||
void changeName(const PIString & new_name);
|
void changeName(const PIString & new_name);
|
||||||
|
|
||||||
|
//! \~english Returns trusted peer name used by inherited \a read() and \a write().
|
||||||
|
//! \~russian Возвращает имя доверенного пира, используемое унаследованными \a read() и \a write().
|
||||||
const PIString & trustPeerName() const { return trust_peer; }
|
const PIString & trustPeerName() const { return trust_peer; }
|
||||||
|
|
||||||
|
//! \~english Sets trusted peer name for inherited \a read() and \a write().
|
||||||
|
//! \~russian Устанавливает имя доверенного пира для унаследованных \a read() и \a write().
|
||||||
void setTrustPeerName(const PIString & peer_name) { trust_peer = peer_name; }
|
void setTrustPeerName(const PIString & peer_name) { trust_peer = peer_name; }
|
||||||
|
|
||||||
|
//! \~english Sets TCP server address used for peer discovery fallback.
|
||||||
|
//! \~russian Устанавливает адрес TCP-сервера, используемого как резервный канал обнаружения пиров.
|
||||||
void setTcpServerIP(const PIString & ip);
|
void setTcpServerIP(const PIString & ip);
|
||||||
|
|
||||||
|
//! \~english Returns size of the next buffered payload from the trusted peer stream.
|
||||||
|
//! \~russian Возвращает размер следующей буферизованной полезной нагрузки из trusted-peer потока.
|
||||||
ssize_t bytesAvailable() const override;
|
ssize_t bytesAvailable() const override;
|
||||||
|
|
||||||
|
//! \events
|
||||||
|
//! \{
|
||||||
|
|
||||||
|
//! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data)
|
||||||
|
//! \~english Raised when payload data is delivered from peer "from".
|
||||||
|
//! \~russian Вызывается, когда полезные данные доставлены от пира "from".
|
||||||
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
|
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
|
||||||
|
|
||||||
|
//! \fn void peerConnectedEvent(const PIString & name)
|
||||||
|
//! \~english Raised when a new peer becomes available.
|
||||||
|
//! \~russian Вызывается, когда становится доступен новый пир.
|
||||||
EVENT1(peerConnectedEvent, const PIString &, name);
|
EVENT1(peerConnectedEvent, const PIString &, name);
|
||||||
|
|
||||||
|
//! \fn void peerDisconnectedEvent(const PIString & name)
|
||||||
|
//! \~english Raised when a known peer disappears from the network.
|
||||||
|
//! \~russian Вызывается, когда известный пир исчезает из сети.
|
||||||
EVENT1(peerDisconnectedEvent, const PIString &, name);
|
EVENT1(peerDisconnectedEvent, const PIString &, name);
|
||||||
|
|
||||||
|
//! \}
|
||||||
|
|
||||||
// bool lockedEth() const {return eth_mutex.isLocked();}
|
// bool lockedEth() const {return eth_mutex.isLocked();}
|
||||||
// bool lockedPeers() const {return peers_mutex.isLocked();}
|
// bool lockedPeers() const {return peers_mutex.isLocked();}
|
||||||
// bool lockedMBcasts() const {return mc_mutex.isLocked();}
|
// bool lockedMBcasts() const {return mc_mutex.isLocked();}
|
||||||
@@ -135,8 +302,16 @@ public:
|
|||||||
// bool lockedMCSends() const {return send_mc_mutex.isLocked();}
|
// bool lockedMCSends() const {return send_mc_mutex.isLocked();}
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
//! \~english Reimplement to handle incoming payload data.
|
||||||
|
//! \~russian Переопределите для обработки входящих полезных данных.
|
||||||
virtual void dataReceived(const PIString & from, const PIByteArray & data) { ; }
|
virtual void dataReceived(const PIString & from, const PIByteArray & data) { ; }
|
||||||
|
|
||||||
|
//! \~english Reimplement to react to peer appearance.
|
||||||
|
//! \~russian Переопределите для реакции на появление пира.
|
||||||
virtual void peerConnected(const PIString & name) { ; }
|
virtual void peerConnected(const PIString & name) { ; }
|
||||||
|
|
||||||
|
//! \~english Reimplement to react to peer disappearance.
|
||||||
|
//! \~russian Переопределите для реакции на исчезновение пира.
|
||||||
virtual void peerDisconnected(const PIString & name) { ; }
|
virtual void peerDisconnected(const PIString & name) { ; }
|
||||||
|
|
||||||
EVENT_HANDLER2(bool, dataRead, const uchar *, readed, ssize_t, size);
|
EVENT_HANDLER2(bool, dataRead, const uchar *, readed, ssize_t, size);
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
/*! \file piserial.h
|
//! \~\addtogroup IO
|
||||||
* \ingroup IO
|
//! \~\{
|
||||||
* \~\brief
|
//! \~\file piserial.h
|
||||||
* \~english Serial device
|
//! \~\brief
|
||||||
* \~russian Последовательный порт
|
//! \~english Serial device
|
||||||
*/
|
//! \~russian Последовательный порт
|
||||||
|
//! \~\}
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
COM
|
COM
|
||||||
@@ -30,7 +31,7 @@
|
|||||||
#include "pitimer.h"
|
#include "pitimer.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Serial device.
|
//! \~english Serial device.
|
||||||
//! \~russian Последовательный порт.
|
//! \~russian Последовательный порт.
|
||||||
@@ -84,7 +85,7 @@ public:
|
|||||||
S4000000 /*! 4000000 baud */ = 4000000
|
S4000000 /*! 4000000 baud */ = 4000000
|
||||||
};
|
};
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Information about serial device
|
//! \~english Information about serial device
|
||||||
//! \~russian Информация о последовательном устройстве
|
//! \~russian Информация о последовательном устройстве
|
||||||
@@ -110,7 +111,7 @@ public:
|
|||||||
PIString description;
|
PIString description;
|
||||||
|
|
||||||
//! \~english Device manufacturer
|
//! \~english Device manufacturer
|
||||||
//! \~russian Описание производителя
|
//! \~russian Производитель устройства
|
||||||
PIString manufacturer;
|
PIString manufacturer;
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -213,16 +214,18 @@ public:
|
|||||||
bool isDSR() const;
|
bool isDSR() const;
|
||||||
|
|
||||||
//! \~english Switch transmission line in break
|
//! \~english Switch transmission line in break
|
||||||
//! \~russian Переключает состояние передачи в break
|
//! \~russian Переключает состояние передачи в break.
|
||||||
bool setBreak(bool enabled);
|
bool setBreak(bool enabled);
|
||||||
|
|
||||||
|
//! \~english Set VTime parameter
|
||||||
|
//! \~russian Устанавливает параметр VTime
|
||||||
void setVTime(int t) {
|
void setVTime(int t) {
|
||||||
vtime = t;
|
vtime = t;
|
||||||
applySettings();
|
applySettings();
|
||||||
}
|
}
|
||||||
|
|
||||||
//! \~english Returns device name
|
//! \~english Returns device name
|
||||||
//! \~russian Возвращает имя устройства
|
//! \~russian Возвращает имя устройства.
|
||||||
PIString device() const { return path(); }
|
PIString device() const { return path(); }
|
||||||
|
|
||||||
//! \~english Returns output speed
|
//! \~english Returns output speed
|
||||||
@@ -236,7 +239,7 @@ public:
|
|||||||
int VTime() const { return vtime; }
|
int VTime() const { return vtime; }
|
||||||
|
|
||||||
//! \~english Discard all buffered input and output data
|
//! \~english Discard all buffered input and output data
|
||||||
//! \~russian Откидывает все буферизированные данные для передачи и приема
|
//! \~russian Откидывает все буферизированные данные для передачи и приема.
|
||||||
virtual void flush() override;
|
virtual void flush() override;
|
||||||
|
|
||||||
int read(void * read_to, int max_size) { return readDevice(read_to, max_size); }
|
int read(void * read_to, int max_size) { return readDevice(read_to, max_size); }
|
||||||
@@ -246,25 +249,25 @@ public:
|
|||||||
bool read(void * read_to, int max_size, double timeout_ms);
|
bool read(void * read_to, int max_size, double timeout_ms);
|
||||||
|
|
||||||
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
||||||
//! \~russian Читает из устройства в течении таймаута "timeout_ms" или до "size" байт
|
//! \~russian Читает из устройства в течение таймаута "timeout_ms" или до "size" байт.
|
||||||
PIString readString(int size = -1, double timeout_ms = 1000.);
|
PIString readString(int size = -1, double timeout_ms = 1000.);
|
||||||
|
|
||||||
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
//! \~english Read from device for "timeout_ms" timeout or for "size" bytes
|
||||||
//! \~russian Читает из устройства в течении таймаута "timeout_ms" или до "size" байт
|
//! \~russian Читает из устройства в течение таймаута "timeout_ms" или до "size" байт.
|
||||||
PIByteArray readData(int size = -1, double timeout_ms = 1000.);
|
PIByteArray readData(int size = -1, double timeout_ms = 1000.);
|
||||||
|
|
||||||
//! \~english Write to device data "data" with maximum size "size". Returns if sended bytes count = "size"
|
//! \~english Write to device data "data" with maximum size "size". Returns if sent bytes count = "size"
|
||||||
//! \~russian Пишет в порт не более "size" байт данных "data". Возвращает если количество записанных байт = "size"
|
//! \~russian Пишет в порт не более "size" байт данных "data". Возвращает если количество отправленных байт = "size"
|
||||||
bool send(const void * data, int size);
|
bool send(const void * data, int size);
|
||||||
|
|
||||||
//! \~english Write to device byte array "data". Returns if sended bytes count = size of "data"
|
//! \~english Write to device byte array "data". Returns if sent bytes count = size of "data"
|
||||||
//! \~russian Пишет в порт байтовый массив "data". Возвращает если количество записанных байт = размер "data"
|
//! \~russian Пишет в порт байтовый массив "data". Возвращает если количество отправленных байт = размер "data"
|
||||||
bool send(const PIByteArray & data) { return send(data.data(), data.size_s()); }
|
bool send(const PIByteArray & data) { return send(data.data(), data.size_s()); }
|
||||||
|
|
||||||
void interrupt() override;
|
void interrupt() override;
|
||||||
|
|
||||||
//! \~english Returns all available speeds for serial devices
|
//! \~english Returns all available speeds for serial devices
|
||||||
//! \~russian Возвращает все возможные скорости для устройств
|
//! \~russian Возвращает все возможные скорости для последовательных портов.
|
||||||
static PIVector<int> availableSpeeds();
|
static PIVector<int> availableSpeeds();
|
||||||
|
|
||||||
//! \~english Returns all available system devices path. If "test" each device will be tried to open
|
//! \~english Returns all available system devices path. If "test" each device will be tried to open
|
||||||
@@ -287,7 +290,7 @@ public:
|
|||||||
int speed;
|
int speed;
|
||||||
|
|
||||||
//! \~english dataBitsCount, default 8
|
//! \~english dataBitsCount, default 8
|
||||||
//! \~russian количесво бит данных, по умолчанию 8
|
//! \~russian количество бит данных, по умолчанию 8
|
||||||
int dataBitsCount;
|
int dataBitsCount;
|
||||||
|
|
||||||
//! \~english parityControl, default false
|
//! \~english parityControl, default false
|
||||||
@@ -319,7 +322,8 @@ protected:
|
|||||||
ssize_t writeDevice(const void * data, ssize_t max_size) override;
|
ssize_t writeDevice(const void * data, ssize_t max_size) override;
|
||||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential; }
|
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Sequential; }
|
||||||
|
|
||||||
//! Executes when any read function was successful. Default implementation does nothing
|
//! \~english Executes when any read function was successful. Default implementation does nothing
|
||||||
|
//! \~russian Выполняется при успешном вызове любой функции чтения. Реализация по умолчанию ничего не делает
|
||||||
virtual void received(const void * data, int size) { ; }
|
virtual void received(const void * data, int size) { ; }
|
||||||
|
|
||||||
void construct();
|
void construct();
|
||||||
|
|||||||
@@ -29,75 +29,245 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english Shared memory.
|
//! \~english Shared memory.
|
||||||
//! \~russian Разделяемая память.
|
//! \~russian Разделяемая память.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english
|
||||||
|
//! Shared memory is used as a single data storage accessible to various processes by name.
|
||||||
|
//! At the first opening of the shared memory object, \a size() bytes are allocated, by default 64 KiB.
|
||||||
|
//! All processes must use the same \a size() to avoid errors.
|
||||||
|
//!
|
||||||
|
//! The shared memory object has no read/write position,
|
||||||
|
//! each call to \a read() or \a write() accesses the beginning of memory.
|
||||||
|
//! For working with a specific memory area, overloaded methods with "offset" indication are used.
|
||||||
|
//!
|
||||||
|
//! \~russian
|
||||||
|
//! Разделяемая память используется как единое хранилище данных,
|
||||||
|
//! доступное различным процессам по имени. При первом открытии
|
||||||
|
//! объекта разделяемой памяти выделяется \a size() байт, по умолчанию
|
||||||
|
//! 64 Кб. Все процессы должны использовать один и тот же \a size()
|
||||||
|
//! во избежании ошибок.
|
||||||
|
//!
|
||||||
|
//! У объекта разделяемой памяти нету позиции чтения/записи,
|
||||||
|
//! каждый вызов \a read() или \a write() обращается
|
||||||
|
//! к началу памяти. Для работы с конкретным участком памяти
|
||||||
|
//! используются перегруженные методы с указанием "offset".
|
||||||
class PIP_EXPORT PISharedMemory: public PIIODevice {
|
class PIP_EXPORT PISharedMemory: public PIIODevice {
|
||||||
PIIODEVICE(PISharedMemory, "shm");
|
PIIODEVICE(PISharedMemory, "shm");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Constructs empty %PISharedMemory
|
//! \~english Constructs empty %PISharedMemory.
|
||||||
//! \~russian Создает пустой %PISharedMemory
|
//! \~russian Создает пустой %PISharedMemory.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Constructs an empty shared memory object with default size 64 KiB.
|
||||||
|
//! \~russian Создает пустой объект разделяемой памяти со стандартным размером 64 Кб.
|
||||||
explicit PISharedMemory();
|
explicit PISharedMemory();
|
||||||
|
|
||||||
//! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode"
|
//! \~english Constructs a shared memory object with name "shm_name", size "size" and open mode "mode".
|
||||||
//! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode"
|
//! \~russian Создает объект разделяемой памяти с именем "shm_name", размером "size" и режимом открытия "mode".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Constructs a shared memory object with the specified name, size, and open mode. If "shm_name" is not empty, the object is
|
||||||
|
//! automatically opened.
|
||||||
|
//! \~russian Создает объект разделяемой памяти с заданным именем, размером и режимом открытия. Если "shm_name" не пустой, объект
|
||||||
|
//! автоматически открывается.
|
||||||
explicit PISharedMemory(const PIString & shm_name, int size, DeviceMode mode = ReadWrite);
|
explicit PISharedMemory(const PIString & shm_name, int size, DeviceMode mode = ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destructor.
|
||||||
|
//! \~russian Деструктор.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Stops and closes the shared memory object.
|
||||||
|
//! \~russian Останавливает и закрывает объект разделяемой памяти.
|
||||||
virtual ~PISharedMemory();
|
virtual ~PISharedMemory();
|
||||||
|
|
||||||
|
|
||||||
//! \~english Read all shared memory content and return it as byte array
|
//! \~english Reads all shared memory content and returns it as byte array.
|
||||||
//! \~russian Читает всю разделяемую память и возвращает её как байтовый массив
|
//! \~russian Читает всю разделяемую память и возвращает её как байтовый массив.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Reads the entire shared memory and returns it as a PIByteArray. Returns empty array if size is less than or equal to zero.
|
||||||
|
//! \~russian Читает всю разделяемую память и возвращает её как PIByteArray. Возвращает пустой массив, если размер меньше или равен
|
||||||
|
//! нулю.
|
||||||
PIByteArray readAll();
|
PIByteArray readAll();
|
||||||
|
|
||||||
//! \~english Returns shared memory size
|
//! \~english Returns shared memory size.
|
||||||
//! \~russian Возвращает размер разделяемой памяти
|
//! \~russian Возвращает размер разделяемой памяти.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Returns the size of the shared memory in bytes. Returns -1 if the device is closed.
|
||||||
|
//! \~russian Возвращает размер разделяемой памяти в байтах. Возвращает -1, если устройство закрыто.
|
||||||
llong size() const;
|
llong size() const;
|
||||||
|
|
||||||
//! \~english Set shared memory size
|
//! \~english Sets shared memory size.
|
||||||
//! \~russian Устанавливает размер разделяемой памяти
|
//! \~russian Устанавливает размер разделяемой памяти.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Sets the size of the shared memory. If the device is open, it will be closed and reopened with the new size.
|
||||||
|
//! \~russian Устанавливает размер разделяемой памяти. Если устройство открыто, оно будет закрыто и открыто заново с новым размером.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english The size is rounded up to the nearest page size on some systems.
|
||||||
|
//! \~russian Размер округляется до ближайшей страницы на некоторых системах.
|
||||||
void setSize(llong s);
|
void setSize(llong s);
|
||||||
|
|
||||||
//! \~english Returns if shared memory object is empty (by size)
|
//! \~english Returns if shared memory object is empty (by size).
|
||||||
//! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру)
|
//! \~russian Возвращает пустой ли объект разделяемой памяти (по размеру).
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Returns true if the shared memory size is less than or equal to zero.
|
||||||
|
//! \~russian Возвращает true, если размер разделяемой памяти меньше или равен нулю.
|
||||||
bool isEmpty() const { return (size() <= 0); }
|
bool isEmpty() const { return (size() <= 0); }
|
||||||
|
|
||||||
//! \~english Read from shared memory to "read_to" no more than "max_size" and return readed bytes count
|
//! \~english Reads from shared memory to "read_to" no more than "max_size" and returns read bytes count.
|
||||||
//! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт
|
//! \~russian Читает из разделяемой памяти в "read_to" не более "max_size" и возвращает количество прочитанных байт.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Reads from the beginning of shared memory (offset 0) to the buffer "read_to" no more than "max_size" bytes.
|
||||||
|
//! \~russian Читает с начала разделяемой памяти (смещение 0) в буфер "read_to" не более "max_size" байт.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes read, or -1 on error.
|
||||||
|
//! \~russian Количество прочитанных байт, или -1 в случае ошибки.
|
||||||
|
//! \~\sa read(void *read_to, int max_size, int offset)
|
||||||
int read(void * read_to, int max_size);
|
int read(void * read_to, int max_size);
|
||||||
|
|
||||||
//! \~english Read from shared memory started from "offset" to "read_to" no more than "max_size" and return readed bytes count
|
//! \~english Reads from shared memory starting from "offset" to "read_to" no more than "max_size" and returns read bytes count.
|
||||||
//! \~russian Читает из разделяемой памяти с начала "offset" в "read_to" не более "max_size" и возвращает количество прочитанных байт
|
//! \~russian Читает из разделяемой памяти с начала "offset" в "read_to" не более "max_size" и возвращает количество прочитанных байт.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Reads from the shared memory starting at the specified "offset" to the buffer "read_to" no more than "max_size" bytes.
|
||||||
|
//! \~russian Читает из разделяемой памяти с указанного смещения "offset" в буфер "read_to" не более "max_size" байт.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes read, or -1 on error.
|
||||||
|
//! \~russian Количество прочитанных байт, или -1 в случае ошибки.
|
||||||
int read(void * read_to, int max_size, int offset);
|
int read(void * read_to, int max_size, int offset);
|
||||||
|
|
||||||
//! \~english Write to shared memory "data" with size "max_size" and return written bytes count
|
//! \~english Writes to shared memory "data" with size "max_size" and returns written bytes count.
|
||||||
//! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт
|
//! \~russian Пишет в разделяемую память "data" размером "max_size" и возвращает количество записанных байт.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes to the beginning of shared memory (offset 0) from the buffer "data" no more than "max_size" bytes.
|
||||||
|
//! \~russian Пишет в начало разделяемой памяти (смещение 0) из буфера "data" не более "max_size" байт.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes written, or -1 on error.
|
||||||
|
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||||
|
//! \~\sa write(const void *data, int max_size, int offset)
|
||||||
int write(const void * data, int max_size);
|
int write(const void * data, int max_size);
|
||||||
|
|
||||||
//! \~english Write to shared memory started from "offset" "data" with size "max_size" and return written bytes count
|
//! \~english Writes to shared memory starting from "offset" "data" with size "max_size" and returns written bytes count.
|
||||||
//! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных
|
//! \~russian Пишет в разделяемую память с начала "offset" "data" размером "max_size" и возвращает количество записанных.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes to the shared memory starting at the specified "offset" from the buffer "data" no more than "max_size" bytes.
|
||||||
|
//! \~russian Пишет в разделяемую память с указанного смещения "offset" из буфера "data" не более "max_size" байт.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes written, or -1 on error.
|
||||||
|
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||||
int write(const void * data, int max_size, int offset);
|
int write(const void * data, int max_size, int offset);
|
||||||
|
|
||||||
//! \~english Write "data" to shared memory
|
//! \~english Writes "data" to shared memory.
|
||||||
//! \~russian Пишет в разделяемую память "data"
|
//! \~russian Пишет в разделяемую память "data".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes the entire PIByteArray "data" to the beginning of shared memory (offset 0).
|
||||||
|
//! \~russian Пишет весь PIByteArray "data" в начало разделяемой памяти (смещение 0).
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes written, or -1 on error.
|
||||||
|
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||||
|
//! \~\sa write(const void *data, int max_size)
|
||||||
int write(const PIByteArray & data) { return write(data.data(), data.size_s()); }
|
int write(const PIByteArray & data) { return write(data.data(), data.size_s()); }
|
||||||
|
|
||||||
//! \~english Write "data" to shared memory
|
//! \~english Writes "data" to shared memory starting from "offset".
|
||||||
//! \~russian Пишет в разделяемую память "data"
|
//! \~russian Пишет в разделяемую память "data" с начала "offset".
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Writes the entire PIByteArray "data" to the shared memory starting at the specified "offset".
|
||||||
|
//! \~russian Пишет весь PIByteArray "data" в разделяемую память с указанного смещения "offset".
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes written, or -1 on error.
|
||||||
|
//! \~russian Количество записанных байт, или -1 в случае ошибки.
|
||||||
|
//! \~\sa write(const void *data, int max_size, int offset)
|
||||||
int write(const PIByteArray & data, int offset) { return write(data.data(), data.size_s(), offset); }
|
int write(const PIByteArray & data, int offset) { return write(data.data(), data.size_s(), offset); }
|
||||||
|
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
//! \~english Opens the shared memory device.
|
||||||
|
//! \~russian Открывает устройство разделяемой памяти.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Creates or opens the shared memory object depending on the system (POSIX or Windows).
|
||||||
|
//! \~russian Создает или открывает объект разделяемой памяти в зависимости от системы (POSIX или Windows).
|
||||||
|
//! \~\return
|
||||||
|
//! \~english True on success, false otherwise.
|
||||||
|
//! \~russian True в случае успеха, false в противном случае.
|
||||||
bool openDevice() override;
|
bool openDevice() override;
|
||||||
|
|
||||||
|
//! \~english Closes the shared memory device.
|
||||||
|
//! \~russian Закрывает устройство разделяемой памяти.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Closes the shared memory object and releases resources.
|
||||||
|
//! \~russian Закрывает объект разделяемой памяти и освобождает ресурсы.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english True on success, false otherwise.
|
||||||
|
//! \~russian True в случае успеха, false в противном случае.
|
||||||
bool closeDevice() override;
|
bool closeDevice() override;
|
||||||
|
|
||||||
|
//! \~english Constructs the full path device string.
|
||||||
|
//! \~russian Конструирует строку полного пути устройства.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Constructs a string in the format "path:size" representing the full path to the shared memory.
|
||||||
|
//! \~russian Конструирует строку формата "path:size", представляющую полный путь к разделяемой памяти.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The full path device string.
|
||||||
|
//! \~russian Строка полного пути устройства.
|
||||||
PIString constructFullPathDevice() const override;
|
PIString constructFullPathDevice() const override;
|
||||||
|
|
||||||
|
//! \~english Configures the device from the full path string.
|
||||||
|
//! \~russian Настраивает устройство из строки полного пути.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Parses the full path string in the format "path:size" and configures the device.
|
||||||
|
//! \~russian Парсит строку полного пути формата "path:size" и настраивает устройство.
|
||||||
|
//! \~\param full_path
|
||||||
|
//! \~english The full path string to parse.
|
||||||
|
//! \~russian Строка полного пути для парсинга.
|
||||||
void configureFromFullPathDevice(const PIString & full_path) override;
|
void configureFromFullPathDevice(const PIString & full_path) override;
|
||||||
|
|
||||||
|
//! \~english Constructs a variant device representation.
|
||||||
|
//! \~russian Конструирует представление устройства в виде variant.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Constructs a PIPropertyStorage with "path" and "size" properties representing the device state.
|
||||||
|
//! \~russian Конструирует PIPropertyStorage со свойствами "path" и "size", представляющими состояние устройства.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The property storage representing the device.
|
||||||
|
//! \~russian Хранилище свойств, представляющее устройство.
|
||||||
PIPropertyStorage constructVariantDevice() const override;
|
PIPropertyStorage constructVariantDevice() const override;
|
||||||
|
|
||||||
|
//! \~english Configures the device from a variant representation.
|
||||||
|
//! \~russian Настраивает устройство из представления variant.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Configures the device from a PIPropertyStorage containing "path" and "size" properties.
|
||||||
|
//! \~russian Настраивает устройство из PIPropertyStorage, содержащего свойства "path" и "size".
|
||||||
|
//! \~\param d
|
||||||
|
//! \~english The property storage to configure from.
|
||||||
|
//! \~russian Хранилище свойств для настройки.
|
||||||
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
void configureFromVariantDevice(const PIPropertyStorage & d) override;
|
||||||
|
|
||||||
|
//! \~english Reads from the device.
|
||||||
|
//! \~russian Читает из устройства.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Calls read() with offset 0.
|
||||||
|
//! \~russian Вызывает read() со смещением 0.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes read.
|
||||||
|
//! \~russian Количество прочитанных байт.
|
||||||
ssize_t readDevice(void * read_to, ssize_t max_size) override { return read(read_to, max_size, 0); }
|
ssize_t readDevice(void * read_to, ssize_t max_size) override { return read(read_to, max_size, 0); }
|
||||||
|
|
||||||
|
//! \~english Writes to the device.
|
||||||
|
//! \~russian Пишет в устройство.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Calls write() with offset 0.
|
||||||
|
//! \~russian Вызывает write() со смещением 0.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Number of bytes written.
|
||||||
|
//! \~russian Количество записанных байт.
|
||||||
ssize_t writeDevice(const void * data, ssize_t max_size) override { return write(data, max_size, 0); }
|
ssize_t writeDevice(const void * data, ssize_t max_size) override { return write(data, max_size, 0); }
|
||||||
|
|
||||||
|
//! \~english Returns device information flags.
|
||||||
|
//! \~russian Возвращает флаги информации об устройстве.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Returns the Reliable flag indicating that the device operates reliably.
|
||||||
|
//! \~russian Возвращает флаг Reliable, указывающий, что устройство работает надежно.
|
||||||
|
//! \~\return
|
||||||
|
//! \~english The device information flags.
|
||||||
|
//! \~russian Флаги информации об устройстве.
|
||||||
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
DeviceInfoFlags deviceInfoFlags() const override { return PIIODevice::Reliable; }
|
||||||
|
|
||||||
private:
|
private:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pispi.h
|
//! \~\file pispi.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english SPI device
|
//! \~english SPI device wrapper
|
||||||
* \~russian Устройство SPI
|
//! \~russian Обертка над SPI-устройством
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
SPI
|
SPI
|
||||||
@@ -29,37 +28,76 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup IO
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english SPI device with configurable speed, word size and clock mode.
|
||||||
|
//! \~russian SPI-устройство с настраиваемыми скоростью, размером слова и режимом тактирования.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Data is exchanged through \a write(), and received bytes are accumulated for subsequent \a read() calls.
|
||||||
|
//! \~russian Обмен выполняется через \a write(), а принятые байты накапливаются для последующих вызовов \a read().
|
||||||
class PIP_EXPORT PISPI: public PIIODevice {
|
class PIP_EXPORT PISPI: public PIIODevice {
|
||||||
PIIODEVICE(PISPI, "spi");
|
PIIODEVICE(PISPI, "spi");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs an SPI device for "path" with transfer speed "speed_hz".
|
||||||
|
//! \~russian Создает SPI-устройство для "path" со скоростью обмена "speed_hz".
|
||||||
explicit PISPI(const PIString & path = PIString(), uint speed_hz = 1000000, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
explicit PISPI(const PIString & path = PIString(), uint speed_hz = 1000000, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite);
|
||||||
|
|
||||||
|
//! \~english Destroys the SPI device.
|
||||||
|
//! \~russian Уничтожает SPI-устройство.
|
||||||
virtual ~PISPI();
|
virtual ~PISPI();
|
||||||
|
|
||||||
//! \brief Parameters of PISPI
|
//! \~english SPI mode flags.
|
||||||
|
//! \~russian Флаги режима SPI.
|
||||||
enum Parameters {
|
enum Parameters {
|
||||||
ClockInverse /*! SPI clk polarity control*/ = 0x1,
|
ClockInverse = 0x1 /*! \~english Invert clock polarity \~russian Инвертировать полярность тактового сигнала */,
|
||||||
ClockPhaseShift /*! SPI clk phase control */ = 0x2,
|
ClockPhaseShift = 0x2 /*! \~english Shift sampling phase \~russian Сдвинуть фазу выборки */,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Sets SPI clock speed in hertz.
|
||||||
|
//! \~russian Устанавливает частоту SPI в герцах.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english Configures the SPI clock frequency. The actual frequency may be rounded to the nearest supported value by the hardware.
|
||||||
|
//! \~russian Настраивает частоту тактового сигнала SPI. Фактическая частота может быть округлена до ближайшего поддерживаемого значения
|
||||||
|
//! оборудованием.
|
||||||
|
//! \~\sa speed()
|
||||||
void setSpeed(uint speed_hz);
|
void setSpeed(uint speed_hz);
|
||||||
|
|
||||||
|
//! \~english Returns SPI clock speed in hertz.
|
||||||
|
//! \~russian Возвращает частоту SPI в герцах.
|
||||||
|
//! \~\sa setSpeed()
|
||||||
uint speed() const { return spi_speed; }
|
uint speed() const { return spi_speed; }
|
||||||
|
|
||||||
|
//! \~english Sets bits per transferred word.
|
||||||
|
//! \~russian Устанавливает количество бит в передаваемом слове.
|
||||||
|
//! \~\sa bits()
|
||||||
void setBits(uchar bits = 8);
|
void setBits(uchar bits = 8);
|
||||||
|
|
||||||
|
//! \~english Returns bits per transferred word.
|
||||||
|
//! \~russian Возвращает количество бит в передаваемом слове.
|
||||||
uchar bits() const { return spi_bits; }
|
uchar bits() const { return spi_bits; }
|
||||||
|
|
||||||
//! Set parameters to "parameters_"
|
//! \~english Replaces all SPI mode flags with "parameters_".
|
||||||
|
//! \~russian Полностью заменяет набор флагов режима SPI на "parameters_".
|
||||||
void setParameters(PIFlags<PISPI::Parameters> parameters_) { spi_mode = (int)parameters_; }
|
void setParameters(PIFlags<PISPI::Parameters> parameters_) { spi_mode = (int)parameters_; }
|
||||||
|
|
||||||
//! Set parameter "parameter" to "on" state
|
//! \~english Enables or disables a single SPI mode flag.
|
||||||
|
//! \~russian Включает или выключает отдельный флаг режима SPI.
|
||||||
|
//! \~\sa isParameterSet()
|
||||||
void setParameter(PISPI::Parameters parameter, bool on = true);
|
void setParameter(PISPI::Parameters parameter, bool on = true);
|
||||||
|
|
||||||
//! Returns if parameter "parameter" is set
|
//! \~english Returns whether SPI mode flag "parameter" is enabled.
|
||||||
|
//! \~russian Возвращает, включен ли флаг режима SPI "parameter".
|
||||||
|
//! \~\sa setParameter()
|
||||||
bool isParameterSet(PISPI::Parameters parameter) const;
|
bool isParameterSet(PISPI::Parameters parameter) const;
|
||||||
|
|
||||||
//! Returns parameters
|
//! \~english Returns current SPI mode flags.
|
||||||
|
//! \~russian Возвращает текущие флаги режима SPI.
|
||||||
|
//! \~\sa setParameters()
|
||||||
PIFlags<PISPI::Parameters> parameters() const { return spi_mode; }
|
PIFlags<PISPI::Parameters> parameters() const { return spi_mode; }
|
||||||
|
|
||||||
|
//! \~english Returns how many received bytes are buffered for \a read().
|
||||||
|
//! \~russian Возвращает количество принятых байт, буферизованных для \a read().
|
||||||
ssize_t bytesAvailable() const override;
|
ssize_t bytesAvailable() const override;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -29,20 +29,24 @@
|
|||||||
#include "piiodevice.h"
|
#include "piiodevice.h"
|
||||||
|
|
||||||
|
|
||||||
//! \ingroup IO
|
//! \~\ingroup IO
|
||||||
//! \~\brief
|
//! \~\brief
|
||||||
//! \~english PIIODevice that pass write to read.
|
//! \~english %PIIODevice that returns written packets through \a read().
|
||||||
//! \~russian PIIODevice который транслирует запись на чтение.
|
//! \~russian %PIIODevice, который возвращает записанные пакеты через \a read().
|
||||||
class PIP_EXPORT PITransparentDevice: public PIIODevice {
|
class PIP_EXPORT PITransparentDevice: public PIIODevice {
|
||||||
PIIODEVICE(PITransparentDevice, "tr");
|
PIIODEVICE(PITransparentDevice, "tr");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
//! \~english Contructs empty %PITransparentDevice
|
//! \~english Constructs an empty %PITransparentDevice.
|
||||||
//! \~russian Создает пустой %PITransparentDevice
|
//! \~russian Создает пустой %PITransparentDevice.
|
||||||
explicit PITransparentDevice();
|
explicit PITransparentDevice();
|
||||||
|
|
||||||
|
//! \~english Destroys the transparent device.
|
||||||
|
//! \~russian Уничтожает прозрачное устройство.
|
||||||
virtual ~PITransparentDevice();
|
virtual ~PITransparentDevice();
|
||||||
|
|
||||||
|
//! \~english Returns size of the next queued packet.
|
||||||
|
//! \~russian Возвращает размер следующего пакета в очереди.
|
||||||
ssize_t bytesAvailable() const override;
|
ssize_t bytesAvailable() const override;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file piusb.h
|
//! \~\file piusb.h
|
||||||
* \ingroup USB
|
//! \~\ingroup USB
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english USB device
|
//! \~english USB input/output device declarations
|
||||||
* \~russian Устройство USB
|
//! \~russian Объявления USB-устройства ввода/вывода
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
USB, based on libusb
|
USB, based on libusb
|
||||||
@@ -40,10 +39,10 @@
|
|||||||
//! \~russian \par Общее
|
//! \~russian \par Общее
|
||||||
//!
|
//!
|
||||||
//! \~english
|
//! \~english
|
||||||
//! These files provides works with raw USB device
|
//! This module declares raw USB input/output devices built on libusb.
|
||||||
//!
|
//!
|
||||||
//! \~russian
|
//! \~russian
|
||||||
//! Эти файлы обеспечивают работу с сырым USB устройством
|
//! Модуль объявляет USB-устройства ввода/вывода для сырого обмена на базе libusb.
|
||||||
//!
|
//!
|
||||||
//! \~\authors
|
//! \~\authors
|
||||||
//! \~english
|
//! \~english
|
||||||
@@ -62,14 +61,32 @@
|
|||||||
|
|
||||||
struct usb_dev_handle;
|
struct usb_dev_handle;
|
||||||
|
|
||||||
|
//! \~\ingroup USB
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english USB implementation of \a PIIODevice.
|
||||||
|
//! \~russian USB-реализация \a PIIODevice.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english The PIUSB class provides functionality for working with USB devices through the libusb library.
|
||||||
|
//! \~russian Класс PIUSB предоставляет функциональность для работы с USB-устройствами через библиотеку libusb.
|
||||||
class PIP_USB_EXPORT PIUSB: public PIIODevice {
|
class PIP_USB_EXPORT PIUSB: public PIIODevice {
|
||||||
PIIODEVICE(PIUSB, "usb");
|
PIIODEVICE(PIUSB, "usb");
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs USB device wrapper for vendor ID "vid" and product ID "pid".
|
||||||
|
//! \~russian Создает обертку USB-устройства для vendor ID "vid" и product ID "pid".
|
||||||
explicit PIUSB(ushort vid = 0, ushort pid = 0);
|
explicit PIUSB(ushort vid = 0, ushort pid = 0);
|
||||||
|
|
||||||
|
//! \~english Destroys the USB device wrapper.
|
||||||
|
//! \~russian Уничтожает обертку USB-устройства.
|
||||||
virtual ~PIUSB();
|
virtual ~PIUSB();
|
||||||
|
|
||||||
|
//! \~\ingroup USB
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Parsed USB endpoint descriptor.
|
||||||
|
//! \~russian Разобранный дескриптор USB endpoint.
|
||||||
struct PIP_USB_EXPORT Endpoint {
|
struct PIP_USB_EXPORT Endpoint {
|
||||||
|
//! \~english Constructs endpoint descriptor and parses cached properties.
|
||||||
|
//! \~russian Создает дескриптор endpoint и разбирает кэшируемые свойства.
|
||||||
Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {
|
Endpoint(uchar a = 0, uchar at = 0, ushort mps = 0) {
|
||||||
address = a;
|
address = a;
|
||||||
attributes = at;
|
attributes = at;
|
||||||
@@ -77,106 +94,293 @@ public:
|
|||||||
parse();
|
parse();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Transfer direction encoded in endpoint address.
|
||||||
|
//! \~russian Направление передачи, закодированное в адресе endpoint.
|
||||||
enum Direction {
|
enum Direction {
|
||||||
Write = 0,
|
Write = 0 /** \~english Host-to-device endpoint \~russian Endpoint от хоста к устройству */,
|
||||||
Read = 1
|
Read = 1 /** \~english Device-to-host endpoint \~russian Endpoint от устройства к хосту */
|
||||||
};
|
|
||||||
enum TransferType {
|
|
||||||
Control = 0,
|
|
||||||
Isochronous = 1,
|
|
||||||
Bulk = 2,
|
|
||||||
Interrupt = 3
|
|
||||||
};
|
|
||||||
enum SynchronisationType {
|
|
||||||
NoSynchonisation = 0,
|
|
||||||
Asynchronous = 2,
|
|
||||||
Adaptive = 1,
|
|
||||||
Synchronous = 3
|
|
||||||
};
|
|
||||||
enum UsageType {
|
|
||||||
DataEndpoint = 0,
|
|
||||||
FeedbackEndpoint = 2,
|
|
||||||
ExplicitFeedbackDataEndpoint = 1
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english USB transfer type encoded in endpoint attributes.
|
||||||
|
//! \~russian Тип USB-передачи, закодированный в атрибутах endpoint.
|
||||||
|
enum TransferType {
|
||||||
|
Control = 0 /** \~english Control endpoint \~russian Control-endpoint */,
|
||||||
|
Isochronous = 1 /** \~english Isochronous endpoint \~russian Isochronous-endpoint */,
|
||||||
|
Bulk = 2 /** \~english Bulk endpoint \~russian Bulk-endpoint */,
|
||||||
|
Interrupt = 3 /** \~english Interrupt endpoint \~russian Interrupt-endpoint */
|
||||||
|
};
|
||||||
|
|
||||||
|
//! \~english Synchronisation mode for isochronous endpoints.
|
||||||
|
//! \~russian Режим синхронизации для isochronous-endpoint.
|
||||||
|
enum SynchronisationType {
|
||||||
|
NoSynchonisation = 0 /** \~english No synchronisation \~russian Без синхронизации */,
|
||||||
|
Asynchronous = 2 /** \~english Asynchronous synchronisation \~russian Асинхронная синхронизация */,
|
||||||
|
Adaptive = 1 /** \~english Adaptive synchronisation \~russian Адаптивная синхронизация */,
|
||||||
|
Synchronous = 3 /** \~english Synchronous synchronisation \~russian Синхронная синхронизация */
|
||||||
|
};
|
||||||
|
|
||||||
|
//! \~english Usage mode for isochronous endpoints.
|
||||||
|
//! \~russian Режим использования для isochronous-endpoint.
|
||||||
|
enum UsageType {
|
||||||
|
DataEndpoint = 0 /** \~english Data endpoint \~russian Endpoint данных */,
|
||||||
|
FeedbackEndpoint = 2 /** \~english Feedback endpoint \~russian Endpoint обратной связи */,
|
||||||
|
ExplicitFeedbackDataEndpoint =
|
||||||
|
1 /** \~english Explicit feedback data endpoint \~russian Endpoint данных с явной обратной связью */
|
||||||
|
};
|
||||||
|
|
||||||
|
//! \~english Parses direction and transfer information from \a address and \a attributes.
|
||||||
|
//! \~russian Разбирает направление и тип передачи из \a address и \a attributes.
|
||||||
void parse();
|
void parse();
|
||||||
|
|
||||||
|
//! \~english Returns true if the endpoint is not selected.
|
||||||
|
//! \~russian Возвращает true, если endpoint не выбран.
|
||||||
bool isNull() const { return address == 0; }
|
bool isNull() const { return address == 0; }
|
||||||
|
|
||||||
|
//! \~english Raw USB endpoint address.
|
||||||
|
//! \~russian Сырой адрес USB endpoint.
|
||||||
uchar address;
|
uchar address;
|
||||||
|
|
||||||
|
//! \~english Raw USB endpoint attributes.
|
||||||
|
//! \~russian Сырые атрибуты USB endpoint.
|
||||||
uchar attributes;
|
uchar attributes;
|
||||||
|
|
||||||
|
//! \~english Maximum packet size in bytes.
|
||||||
|
//! \~russian Максимальный размер пакета в байтах.
|
||||||
ushort max_packet_size;
|
ushort max_packet_size;
|
||||||
|
|
||||||
|
//! \~english Parsed transfer direction.
|
||||||
|
//! \~russian Разобранное направление передачи.
|
||||||
Direction direction;
|
Direction direction;
|
||||||
|
|
||||||
|
//! \~english Parsed transfer type.
|
||||||
|
//! \~russian Разобранный тип передачи.
|
||||||
TransferType transfer_type;
|
TransferType transfer_type;
|
||||||
|
|
||||||
|
//! \~english Parsed synchronisation type for isochronous transfers.
|
||||||
|
//! \~russian Разобранный тип синхронизации для isochronous-передач.
|
||||||
SynchronisationType synchronisation_type = NoSynchonisation;
|
SynchronisationType synchronisation_type = NoSynchonisation;
|
||||||
|
|
||||||
|
//! \~english Parsed usage type for isochronous transfers.
|
||||||
|
//! \~russian Разобранный режим использования для isochronous-передач.
|
||||||
UsageType usage_type = DataEndpoint;
|
UsageType usage_type = DataEndpoint;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\ingroup USB
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english USB interface description with its endpoints.
|
||||||
|
//! \~russian Описание USB-интерфейса и его endpoint.
|
||||||
struct PIP_USB_EXPORT Interface {
|
struct PIP_USB_EXPORT Interface {
|
||||||
|
//! \~english Index inside the configuration descriptor.
|
||||||
|
//! \~russian Индекс внутри дескриптора конфигурации.
|
||||||
uchar index = 0;
|
uchar index = 0;
|
||||||
|
|
||||||
|
//! \~english Value used to select this interface.
|
||||||
|
//! \~russian Значение, используемое для выбора этого интерфейса.
|
||||||
uchar value_to_select = 0;
|
uchar value_to_select = 0;
|
||||||
|
|
||||||
|
//! \~english USB interface class code.
|
||||||
|
//! \~russian Код класса USB-интерфейса.
|
||||||
ushort class_code = 0;
|
ushort class_code = 0;
|
||||||
|
|
||||||
|
//! \~english USB interface subclass code.
|
||||||
|
//! \~russian Код подкласса USB-интерфейса.
|
||||||
ushort subclass_code = 0;
|
ushort subclass_code = 0;
|
||||||
|
|
||||||
|
//! \~english USB interface protocol code.
|
||||||
|
//! \~russian Код протокола USB-интерфейса.
|
||||||
ushort protocol_code = 0;
|
ushort protocol_code = 0;
|
||||||
|
|
||||||
|
//! \~english Endpoints exposed by this interface.
|
||||||
|
//! \~russian Endpoint, доступные у этого интерфейса.
|
||||||
PIVector<PIUSB::Endpoint> endpoints;
|
PIVector<PIUSB::Endpoint> endpoints;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\ingroup USB
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english USB configuration description with available interfaces.
|
||||||
|
//! \~russian Описание USB-конфигурации с доступными интерфейсами.
|
||||||
struct PIP_USB_EXPORT Configuration {
|
struct PIP_USB_EXPORT Configuration {
|
||||||
|
//! \~english Index inside the device descriptor.
|
||||||
|
//! \~russian Индекс внутри дескриптора устройства.
|
||||||
uchar index = 0;
|
uchar index = 0;
|
||||||
|
|
||||||
|
//! \~english Value used to select this configuration.
|
||||||
|
//! \~russian Значение, используемое для выбора этой конфигурации.
|
||||||
uchar value_to_select = 0;
|
uchar value_to_select = 0;
|
||||||
|
|
||||||
|
//! \~english Raw USB configuration attributes.
|
||||||
|
//! \~russian Сырые атрибуты USB-конфигурации.
|
||||||
uchar attributes = 0;
|
uchar attributes = 0;
|
||||||
ushort max_power = 0; // mA
|
|
||||||
|
//! \~english Maximum bus power in mA.
|
||||||
|
//! \~russian Максимальное потребление по шине в мА.
|
||||||
|
ushort max_power = 0;
|
||||||
|
|
||||||
|
//! \~english True if the device is self-powered in this configuration.
|
||||||
|
//! \~russian True, если устройство в этой конфигурации имеет собственное питание.
|
||||||
bool self_powered = false;
|
bool self_powered = false;
|
||||||
|
|
||||||
|
//! \~english True if remote wakeup is supported.
|
||||||
|
//! \~russian True, если поддерживается remote wakeup.
|
||||||
bool remote_wakeup = false;
|
bool remote_wakeup = false;
|
||||||
|
|
||||||
|
//! \~english Interfaces available in this configuration.
|
||||||
|
//! \~russian Интерфейсы, доступные в этой конфигурации.
|
||||||
PIVector<PIUSB::Interface> interfaces;
|
PIVector<PIUSB::Interface> interfaces;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~\ingroup USB
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Top-level USB device descriptor collected during opening.
|
||||||
|
//! \~russian Верхнеуровневый USB-дескриптор, собранный при открытии.
|
||||||
struct PIP_USB_EXPORT Descriptor {
|
struct PIP_USB_EXPORT Descriptor {
|
||||||
|
//! \~english USB specification version in BCD form.
|
||||||
|
//! \~russian Версия спецификации USB в BCD-форме.
|
||||||
ushort usb_spec_number = 0;
|
ushort usb_spec_number = 0;
|
||||||
|
|
||||||
|
//! \~english Device class code.
|
||||||
|
//! \~russian Код класса устройства.
|
||||||
uchar device_class = 0;
|
uchar device_class = 0;
|
||||||
|
|
||||||
|
//! \~english Device subclass code.
|
||||||
|
//! \~russian Код подкласса устройства.
|
||||||
uchar device_subclass = 0;
|
uchar device_subclass = 0;
|
||||||
|
|
||||||
|
//! \~english Device protocol code.
|
||||||
|
//! \~russian Код протокола устройства.
|
||||||
uchar device_protocol = 0;
|
uchar device_protocol = 0;
|
||||||
|
|
||||||
|
//! \~english Maximum packet size for endpoint zero.
|
||||||
|
//! \~russian Максимальный размер пакета для endpoint zero.
|
||||||
uchar max_packet_size = 0;
|
uchar max_packet_size = 0;
|
||||||
|
|
||||||
|
//! \~english Vendor identifier.
|
||||||
|
//! \~russian Идентификатор производителя.
|
||||||
ushort id_vendor = 0;
|
ushort id_vendor = 0;
|
||||||
|
|
||||||
|
//! \~english Product identifier.
|
||||||
|
//! \~russian Идентификатор продукта.
|
||||||
ushort id_product = 0;
|
ushort id_product = 0;
|
||||||
|
|
||||||
|
//! \~english Device release number in BCD form.
|
||||||
|
//! \~russian Номер релиза устройства в BCD-форме.
|
||||||
ushort id_device_release = 0;
|
ushort id_device_release = 0;
|
||||||
|
|
||||||
|
//! \~english Index of manufacturer string descriptor.
|
||||||
|
//! \~russian Индекс строкового дескриптора производителя.
|
||||||
uchar index_manufacturer = 0;
|
uchar index_manufacturer = 0;
|
||||||
|
|
||||||
|
//! \~english Index of product string descriptor.
|
||||||
|
//! \~russian Индекс строкового дескриптора продукта.
|
||||||
uchar index_product = 0;
|
uchar index_product = 0;
|
||||||
|
|
||||||
|
//! \~english Index of serial number string descriptor.
|
||||||
|
//! \~russian Индекс строкового дескриптора серийного номера.
|
||||||
uchar index_serial = 0;
|
uchar index_serial = 0;
|
||||||
|
|
||||||
|
//! \~english Available device configurations.
|
||||||
|
//! \~russian Доступные конфигурации устройства.
|
||||||
PIVector<PIUSB::Configuration> configurations;
|
PIVector<PIUSB::Configuration> configurations;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Returns descriptor collected for the currently opened device.
|
||||||
|
//! \~russian Возвращает дескриптор, собранный для текущего открытого устройства.
|
||||||
const PIUSB::Descriptor & currentDescriptor() const { return desc_; }
|
const PIUSB::Descriptor & currentDescriptor() const { return desc_; }
|
||||||
|
|
||||||
|
//! \~english Returns the currently selected configuration description.
|
||||||
|
//! \~russian Возвращает описание текущей выбранной конфигурации.
|
||||||
const PIUSB::Configuration & currentConfiguration() const { return conf_; }
|
const PIUSB::Configuration & currentConfiguration() const { return conf_; }
|
||||||
|
|
||||||
|
//! \~english Returns the currently selected interface description.
|
||||||
|
//! \~russian Возвращает описание текущего выбранного интерфейса.
|
||||||
const PIUSB::Interface & currentInterface() const { return iface_; }
|
const PIUSB::Interface & currentInterface() const { return iface_; }
|
||||||
|
|
||||||
|
//! \~english Returns current vendor ID filter.
|
||||||
|
//! \~russian Возвращает текущий фильтр vendor ID.
|
||||||
ushort vendorID() const { return vid_; }
|
ushort vendorID() const { return vid_; }
|
||||||
|
|
||||||
|
//! \~english Returns current product ID filter.
|
||||||
|
//! \~russian Возвращает текущий фильтр product ID.
|
||||||
ushort productID() const { return pid_; }
|
ushort productID() const { return pid_; }
|
||||||
|
|
||||||
|
//! \~english Returns ordinal number among devices with matching vendor and product IDs.
|
||||||
|
//! \~russian Возвращает порядковый номер среди устройств с теми же vendor ID и product ID.
|
||||||
int deviceNumber() const { return property("deviceNumber").toInt(); }
|
int deviceNumber() const { return property("deviceNumber").toInt(); }
|
||||||
|
|
||||||
|
//! \~english Returns read timeout in milliseconds.
|
||||||
|
//! \~russian Возвращает таймаут чтения в миллисекундах.
|
||||||
int timeoutRead() const { return property("timeoutRead").toInt(); }
|
int timeoutRead() const { return property("timeoutRead").toInt(); }
|
||||||
|
|
||||||
|
//! \~english Returns write timeout in milliseconds.
|
||||||
|
//! \~russian Возвращает таймаут записи в миллисекундах.
|
||||||
int timeoutWrite() const { return property("timeoutWrite").toInt(); }
|
int timeoutWrite() const { return property("timeoutWrite").toInt(); }
|
||||||
|
|
||||||
|
//! \~english Returns endpoint used by \a read().
|
||||||
|
//! \~russian Возвращает endpoint, используемый методом \a read().
|
||||||
const PIUSB::Endpoint & endpointRead() const { return ep_read; }
|
const PIUSB::Endpoint & endpointRead() const { return ep_read; }
|
||||||
|
|
||||||
|
//! \~english Returns endpoint used by \a write().
|
||||||
|
//! \~russian Возвращает endpoint, используемый методом \a write().
|
||||||
const PIUSB::Endpoint & endpointWrite() const { return ep_write; }
|
const PIUSB::Endpoint & endpointWrite() const { return ep_write; }
|
||||||
|
|
||||||
|
//! \~english Returns endpoints of the currently selected interface.
|
||||||
|
//! \~russian Возвращает endpoint текущего выбранного интерфейса.
|
||||||
const PIVector<PIUSB::Endpoint> & endpoints() const { return eps; }
|
const PIVector<PIUSB::Endpoint> & endpoints() const { return eps; }
|
||||||
|
|
||||||
|
//! \~english Returns only readable endpoints from \a endpoints().
|
||||||
|
//! \~russian Возвращает только endpoint для чтения из \a endpoints().
|
||||||
PIVector<PIUSB::Endpoint> endpointsRead();
|
PIVector<PIUSB::Endpoint> endpointsRead();
|
||||||
|
|
||||||
|
//! \~english Returns only writable endpoints from \a endpoints().
|
||||||
|
//! \~russian Возвращает только endpoint для записи из \a endpoints().
|
||||||
PIVector<PIUSB::Endpoint> endpointsWrite();
|
PIVector<PIUSB::Endpoint> endpointsWrite();
|
||||||
|
|
||||||
|
//! \~english Returns endpoint with address "address", or null endpoint if it is absent.
|
||||||
|
//! \~russian Возвращает endpoint с адресом "address" или нулевой endpoint, если он отсутствует.
|
||||||
PIUSB::Endpoint getEndpointByAddress(uchar address);
|
PIUSB::Endpoint getEndpointByAddress(uchar address);
|
||||||
|
|
||||||
|
//! \~english Sets vendor ID filter and updates device path.
|
||||||
|
//! \~russian Устанавливает фильтр vendor ID и обновляет путь устройства.
|
||||||
void setVendorID(ushort vid);
|
void setVendorID(ushort vid);
|
||||||
|
|
||||||
|
//! \~english Sets product ID filter and updates device path.
|
||||||
|
//! \~russian Устанавливает фильтр product ID и обновляет путь устройства.
|
||||||
void setProductID(ushort pid);
|
void setProductID(ushort pid);
|
||||||
|
|
||||||
|
//! \~english Selects configuration by its public value and switches to its first interface.
|
||||||
|
//! \~russian Выбирает конфигурацию по её публичному значению и переключается на её первый интерфейс.
|
||||||
bool setConfiguration(uchar value);
|
bool setConfiguration(uchar value);
|
||||||
|
|
||||||
|
//! \~english Selects interface by its public value and refreshes active endpoints.
|
||||||
|
//! \~russian Выбирает интерфейс по его публичному значению и обновляет активные endpoint.
|
||||||
bool setInterface(uchar value);
|
bool setInterface(uchar value);
|
||||||
|
|
||||||
|
//! \~english Sets endpoint used by \a read().
|
||||||
|
//! \~russian Устанавливает endpoint, используемый методом \a read().
|
||||||
void setEndpointRead(const PIUSB::Endpoint & ep) { ep_read = ep; }
|
void setEndpointRead(const PIUSB::Endpoint & ep) { ep_read = ep; }
|
||||||
|
|
||||||
|
//! \~english Sets endpoint used by \a write().
|
||||||
|
//! \~russian Устанавливает endpoint, используемый методом \a write().
|
||||||
void setEndpointWrite(const PIUSB::Endpoint & ep) { ep_write = ep; }
|
void setEndpointWrite(const PIUSB::Endpoint & ep) { ep_write = ep; }
|
||||||
|
|
||||||
|
//! \~english Selects which matching device instance should be opened.
|
||||||
|
//! \~russian Выбирает, какой экземпляр среди совпадающих устройств должен быть открыт.
|
||||||
void setDeviceNumber(int dn) { setProperty("deviceNumber", dn); }
|
void setDeviceNumber(int dn) { setProperty("deviceNumber", dn); }
|
||||||
|
|
||||||
|
//! \~english Sets read timeout in milliseconds.
|
||||||
|
//! \~russian Устанавливает таймаут чтения в миллисекундах.
|
||||||
void setTimeoutRead(int t) { setProperty("timeoutRead", t); }
|
void setTimeoutRead(int t) { setProperty("timeoutRead", t); }
|
||||||
|
|
||||||
|
//! \~english Sets write timeout in milliseconds.
|
||||||
|
//! \~russian Устанавливает таймаут записи в миллисекундах.
|
||||||
void setTimeoutWrite(int t) { setProperty("timeoutWrite", t); }
|
void setTimeoutWrite(int t) { setProperty("timeoutWrite", t); }
|
||||||
|
|
||||||
|
//! \~english Reserved control-transfer write helper.
|
||||||
|
//! \~russian Зарезервированный helper для записи через control-transfer.
|
||||||
int controlWrite(const void * data, int max_size);
|
int controlWrite(const void * data, int max_size);
|
||||||
|
|
||||||
|
//! \~english Resets currently selected read and write endpoints.
|
||||||
|
//! \~russian Сбрасывает текущие выбранные endpoint чтения и записи.
|
||||||
virtual void flush() override;
|
virtual void flush() override;
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
@@ -200,6 +404,10 @@ protected:
|
|||||||
usb_dev_handle * hdev;
|
usb_dev_handle * hdev;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \relatesalso PICout
|
||||||
|
//! \~english Writes endpoint description to \a PICout.
|
||||||
|
//! \~russian Выводит описание endpoint в \a PICout.
|
||||||
PIP_USB_EXPORT PICout operator<<(PICout s, const PIUSB::Endpoint & v);
|
PIP_USB_EXPORT PICout operator<<(PICout s, const PIUSB::Endpoint & v);
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -1,9 +1,8 @@
|
|||||||
/*! \file pibasetransfer.h
|
//! \~\file pibasetransfer.h
|
||||||
* \ingroup IO
|
//! \~\ingroup IO-Utils
|
||||||
* \~\brief
|
//! \~\brief
|
||||||
* \~english Base class for reliable send and receive data in fixed packets with error correction, pause and resume
|
//! \~english Base class for reliable packet sessions with acknowledgements, pause and resume
|
||||||
* \~russian Базовый класс для надежного обмена данными с помощью фиксированных пакетов с коррекцией ошибок и паузой
|
//! \~russian Базовый класс для надежных пакетных сессий с подтверждениями, паузой и продолжением
|
||||||
*/
|
|
||||||
/*
|
/*
|
||||||
PIP - Platform Independent Primitives
|
PIP - Platform Independent Primitives
|
||||||
Base class for reliable send and receive data in fixed packets with error correction, pause and resume
|
Base class for reliable send and receive data in fixed packets with error correction, pause and resume
|
||||||
@@ -29,78 +28,276 @@
|
|||||||
#include "picrc.h"
|
#include "picrc.h"
|
||||||
#include "pidiagnostics.h"
|
#include "pidiagnostics.h"
|
||||||
|
|
||||||
|
|
||||||
|
//! \~\ingroup IO-Utils
|
||||||
|
//! \~\brief
|
||||||
|
//! \~english Base transport for reliable fixed-size packet exchange over an external channel.
|
||||||
|
//! \~russian Базовый транспорт для надежного обмена пакетами фиксированного размера через внешний канал.
|
||||||
|
//! \~\details
|
||||||
|
//! \~english This class provides a foundation for reliable data transfer with features like error correction, pause/resume functionality,
|
||||||
|
//! and packet-based communication.
|
||||||
|
//! \~russian Этот класс предоставляет основу для надежной передачи данных с возможностью коррекции ошибок, паузы/возобновления и пакетной
|
||||||
|
//! коммуникации.
|
||||||
class PIP_EXPORT PIBaseTransfer: public PIObject {
|
class PIP_EXPORT PIBaseTransfer: public PIObject {
|
||||||
PIOBJECT_SUBCLASS(PIBaseTransfer, PIObject);
|
PIOBJECT_SUBCLASS(PIBaseTransfer, PIObject);
|
||||||
|
|
||||||
public:
|
public:
|
||||||
|
//! \~english Constructs transfer with default packet size, timeout and diagnostics.
|
||||||
|
//! \~russian Создает передачу с размером пакета, таймаутом и диагностикой по умолчанию.
|
||||||
PIBaseTransfer();
|
PIBaseTransfer();
|
||||||
|
|
||||||
|
//! \~english Stops active transfer state and owned diagnostics.
|
||||||
|
//! \~russian Останавливает активное состояние передачи и встроенную диагностику.
|
||||||
~PIBaseTransfer();
|
~PIBaseTransfer();
|
||||||
|
|
||||||
#pragma pack(push, 1)
|
#pragma pack(push, 1)
|
||||||
|
//! \~english Common header placed before every protocol packet.
|
||||||
|
//! \~russian Общий заголовок, размещаемый перед каждым пакетом протокола.
|
||||||
struct PIP_EXPORT PacketHeader {
|
struct PIP_EXPORT PacketHeader {
|
||||||
|
//! \~english Packet signature used to recognize transfer packets.
|
||||||
|
//! \~russian Сигнатура пакета, используемая для распознавания пакетов передачи.
|
||||||
uint sig;
|
uint sig;
|
||||||
|
//! \~english Packet type from the transfer protocol.
|
||||||
|
//! \~russian Тип пакета из протокола передачи.
|
||||||
int type; // PacketType
|
int type; // PacketType
|
||||||
|
//! \~english Session identifier for current transfer exchange.
|
||||||
|
//! \~russian Идентификатор сессии текущего обмена.
|
||||||
int session_id;
|
int session_id;
|
||||||
|
//! \~english Sequential packet identifier inside the session.
|
||||||
|
//! \~russian Последовательный идентификатор пакета внутри сессии.
|
||||||
uint id;
|
uint id;
|
||||||
|
//! \~english CRC calculated for the packet payload.
|
||||||
|
//! \~russian CRC, вычисленная для полезной нагрузки пакета.
|
||||||
uint crc;
|
uint crc;
|
||||||
|
//! \~english Returns whether the packet signature matches \a packetSignature().
|
||||||
|
//! \~russian Возвращает, совпадает ли сигнатура пакета с \a packetSignature().
|
||||||
bool check_sig() { return (sig == signature); }
|
bool check_sig() { return (sig == signature); }
|
||||||
};
|
};
|
||||||
|
|
||||||
|
//! \~english Logical fragment description used to split data into packets.
|
||||||
|
//! \~russian Описание логического фрагмента, используемое для разбиения данных на пакеты.
|
||||||
struct PIP_EXPORT Part {
|
struct PIP_EXPORT Part {
|
||||||
|
//! \~english Constructs part metadata for item "id_", fragment size "size_" and offset "start_".
|
||||||
|
//! \~russian Создает метаданные части для элемента "id_", размера фрагмента "size_" и смещения "start_".
|
||||||
Part(uint id_ = 0, ullong size_ = 0, ullong start_ = 0): id(id_), size(size_), start(start_) {}
|
Part(uint id_ = 0, ullong size_ = 0, ullong start_ = 0): id(id_), size(size_), start(start_) {}
|
||||||
|
//! \~english Identifier of the logical item being transferred.
|
||||||
|
//! \~russian Идентификатор логического элемента, который передается.
|
||||||
uint id;
|
uint id;
|
||||||
|
//! \~english Size of this fragment in bytes.
|
||||||
|
//! \~russian Размер этого фрагмента в байтах.
|
||||||
ullong size;
|
ullong size;
|
||||||
|
//! \~english Byte offset of this fragment inside the logical item.
|
||||||
|
//! \~russian Смещение этого фрагмента в байтах внутри логического элемента.
|
||||||
ullong start;
|
ullong start;
|
||||||
};
|
};
|
||||||
#pragma pack(pop)
|
#pragma pack(pop)
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Requests cancellation of the current send session.
|
||||||
|
//! \~russian Запрашивает отмену текущей сессии отправки.
|
||||||
void stopSend();
|
void stopSend();
|
||||||
|
|
||||||
|
//! \~english Requests cancellation of the current receive session.
|
||||||
|
//! \~russian Запрашивает отмену текущей сессии приема.
|
||||||
void stopReceive();
|
void stopReceive();
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Returns whether a send session is active.
|
||||||
|
//! \~russian Возвращает, активна ли сессия отправки.
|
||||||
bool isSending() const { return is_sending; }
|
bool isSending() const { return is_sending; }
|
||||||
|
|
||||||
|
//! \~english Returns whether a receive session is active.
|
||||||
|
//! \~russian Возвращает, активна ли сессия приема.
|
||||||
bool isReceiving() const { return is_receiving; }
|
bool isReceiving() const { return is_receiving; }
|
||||||
|
|
||||||
|
//! \~english Returns whether the transfer is currently paused.
|
||||||
|
//! \~russian Возвращает, находится ли передача сейчас на паузе.
|
||||||
bool isPause() const { return is_pause; }
|
bool isPause() const { return is_pause; }
|
||||||
|
|
||||||
|
//! \~english Switches current session between paused and resumed states.
|
||||||
|
//! \~russian Переключает текущую сессию между состояниями паузы и продолжения.
|
||||||
void setPause(bool pause_);
|
void setPause(bool pause_);
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Sets maximum encoded packet size in bytes.
|
||||||
|
//! \~russian Устанавливает максимальный размер кодированного пакета в байтах.
|
||||||
void setPacketSize(int size) { packet_size = size; }
|
void setPacketSize(int size) { packet_size = size; }
|
||||||
|
|
||||||
|
//! \~english Returns maximum encoded packet size in bytes.
|
||||||
|
//! \~russian Возвращает максимальный размер кодированного пакета в байтах.
|
||||||
int packetSize() const { return packet_size; }
|
int packetSize() const { return packet_size; }
|
||||||
|
|
||||||
|
//! \~english Sets session timeout in seconds for start negotiation, acknowledgements and pause recovery.
|
||||||
|
//! \~russian Устанавливает таймаут сессии в секундах для согласования старта, подтверждений и восстановления после паузы.
|
||||||
void setTimeout(double sec);
|
void setTimeout(double sec);
|
||||||
|
|
||||||
|
//! \~english Returns session timeout in seconds.
|
||||||
|
//! \~russian Возвращает таймаут сессии в секундах.
|
||||||
double timeout() const { return timeout_; }
|
double timeout() const { return timeout_; }
|
||||||
|
|
||||||
|
//! \~english Enables or disables CRC validation for data packets.
|
||||||
|
//! \~russian Включает или выключает проверку CRC для пакетов данных.
|
||||||
void setCRCEnabled(bool en = true) { crc_enabled = en; }
|
void setCRCEnabled(bool en = true) { crc_enabled = en; }
|
||||||
|
|
||||||
|
//! \~english Returns whether CRC validation is enabled.
|
||||||
|
//! \~russian Возвращает, включена ли проверка CRC.
|
||||||
bool isCRCEnabled() const { return crc_enabled; }
|
bool isCRCEnabled() const { return crc_enabled; }
|
||||||
|
|
||||||
|
//! \~english Returns short textual state of the current session.
|
||||||
|
//! \~russian Возвращает краткое текстовое состояние текущей сессии.
|
||||||
PIString stateString() const { return state_string; }
|
PIString stateString() const { return state_string; }
|
||||||
|
|
||||||
|
//! \~english Returns a map of successfully received or transmitted packets for the current session.
|
||||||
|
//! \~russian Возвращает карту успешно принятых или переданных пакетов для текущей сессии.
|
||||||
PIString packetMap() const { return pm_string; }
|
PIString packetMap() const { return pm_string; }
|
||||||
|
|
||||||
|
//! \~english Returns total number of bytes planned for the current session.
|
||||||
|
//! \~russian Возвращает общее число байтов, запланированных для текущей сессии.
|
||||||
llong bytesAll() const { return bytes_all; }
|
llong bytesAll() const { return bytes_all; }
|
||||||
|
|
||||||
|
//! \~english Returns number of bytes already processed in the current session.
|
||||||
|
//! \~russian Возвращает число байтов, уже обработанных в текущей сессии.
|
||||||
llong bytesCur() const { return bytes_cur; }
|
llong bytesCur() const { return bytes_cur; }
|
||||||
|
|
||||||
|
//! \~english Get diagnostics object
|
||||||
|
//! \~russian Получить объект диагностики
|
||||||
|
//! \~\return
|
||||||
|
//! \~english Diagnostic object reference
|
||||||
|
//! \~russian Ссылка на объект диагностики
|
||||||
const PIDiagnostics & diagnostic() { return diag; }
|
const PIDiagnostics & diagnostic() { return diag; }
|
||||||
|
|
||||||
|
//! \~english Returns the packet signature constant used by the protocol.
|
||||||
|
//! \~russian Возвращает константу сигнатуры пакета, используемую протоколом.
|
||||||
static uint packetSignature() { return signature; }
|
static uint packetSignature() { return signature; }
|
||||||
|
|
||||||
|
//! \~\handlers
|
||||||
|
//! \~\{
|
||||||
|
|
||||||
|
//! \~\fn void received(PIByteArray data)
|
||||||
|
//! \~english Processes a single encoded packet received from an external transport.
|
||||||
|
//! \~russian Обрабатывает один закодированный пакет, полученный от внешнего транспорта.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english This handler must be called when data is received by an external transport.
|
||||||
|
//! \~russian Этот обработчик необходимо вызывать при получении данных внешним транспортом.
|
||||||
EVENT_HANDLER1(void, received, PIByteArray, data);
|
EVENT_HANDLER1(void, received, PIByteArray, data);
|
||||||
|
|
||||||
|
//! \~\fn void stop()
|
||||||
|
//! \~english Stops both sending and receiving sides of the current session.
|
||||||
|
//! \~russian Останавливает и отправку, и прием текущей сессии.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Equivalent to calling both `stopSend()` and `stopReceive()`.
|
||||||
|
//! \~russian Эквивалентно вызову `stopSend()` и `stopReceive()`.
|
||||||
EVENT_HANDLER(void, stop) {
|
EVENT_HANDLER(void, stop) {
|
||||||
stopSend();
|
stopSend();
|
||||||
stopReceive();
|
stopReceive();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~\fn void pause()
|
||||||
|
//! \~english Switches current session to paused state.
|
||||||
|
//! \~russian Переводит текущую сессию в состояние паузы.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggers the `paused()` signal.
|
||||||
|
//! \~russian Генерирует событие `paused()`.
|
||||||
EVENT_HANDLER(void, pause) { setPause(true); }
|
EVENT_HANDLER(void, pause) { setPause(true); }
|
||||||
|
|
||||||
|
//! \~\fn void resume()
|
||||||
|
//! \~english Resumes the current paused session.
|
||||||
|
//! \~russian Продолжает текущую приостановленную сессию.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggers the `resumed()` signal.
|
||||||
|
//! \~russian Генерирует событие `resumed()`.
|
||||||
EVENT_HANDLER(void, resume) { setPause(false); }
|
EVENT_HANDLER(void, resume) { setPause(false); }
|
||||||
|
|
||||||
|
//! \~\}
|
||||||
|
//! \~\events
|
||||||
|
//! \~\{
|
||||||
|
|
||||||
|
//! \~\fn void receiveStarted()
|
||||||
|
//! \~english Emitted when a receive session is accepted and initialized.
|
||||||
|
//! \~russian Генерируется, когда сессия приема принята и инициализирована.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggered by internal logic after receiving a valid `pt_Start` packet.
|
||||||
|
//! \~russian Генерируется внутренней логикой после получения корректного пакета типа `pt_Start`.
|
||||||
EVENT(receiveStarted);
|
EVENT(receiveStarted);
|
||||||
|
|
||||||
|
//! \~\fn void paused()
|
||||||
|
//! \~english Emitted when the transfer enters paused state.
|
||||||
|
//! \~russian Генерируется, когда передача переходит в состояние паузы.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggered when `pause` handler is invoked (e.g., via `setPause(true)` or incoming `pt_Pause`).
|
||||||
|
//! \~russian Генерируется при вызове обработчика `pause` (например, через `setPause(true)` или получении `pt_Pause`).
|
||||||
EVENT(paused);
|
EVENT(paused);
|
||||||
|
|
||||||
|
//! \~\fn void resumed()
|
||||||
|
//! \~english Emitted when the transfer leaves paused state.
|
||||||
|
//! \~russian Генерируется, когда передача выходит из состояния паузы.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggered when `resume` handler is invoked (e.g., via `setPause(false)` or incoming `pt_Start` during pause).
|
||||||
|
//! \~russian Генерируется при вызове обработчика `resume` (например, через `setPause(false)` или получении `pt_Start` во время
|
||||||
|
//! паузы).
|
||||||
EVENT(resumed);
|
EVENT(resumed);
|
||||||
|
|
||||||
|
//! \~\fn void receiveFinished(bool ok)
|
||||||
|
//! \~english Emitted when the receive session finishes with result "ok".
|
||||||
|
//! \~russian Генерируется, когда сессия приема завершается с результатом "ok".
|
||||||
|
//! \~\param ok
|
||||||
|
//! \~english `true` if all packets were received and verified, `false` on error or interruption.
|
||||||
|
//! \~russian `true`, если все пакеты получены и проверены, `false` — при ошибке или прерывании.
|
||||||
EVENT1(receiveFinished, bool, ok);
|
EVENT1(receiveFinished, bool, ok);
|
||||||
|
|
||||||
|
//! \~\fn void sendStarted()
|
||||||
|
//! \~english Emitted when a prepared send session starts.
|
||||||
|
//! \~russian Генерируется при запуске подготовленной сессии отправки.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english Triggered after `buildSession()` and before the first packet is sent.
|
||||||
|
//! \~russian Генерируется после `buildSession()` и до отправки первого пакета.
|
||||||
EVENT(sendStarted);
|
EVENT(sendStarted);
|
||||||
|
|
||||||
|
//! \~\fn void sendFinished(bool ok)
|
||||||
|
//! \~english Emitted when the send session finishes with result "ok".
|
||||||
|
//! \~russian Генерируется, когда сессия отправки завершается с результатом "ok".
|
||||||
|
//! \~\param ok
|
||||||
|
//! \~english `true` if all packets were sent and acknowledged, `false` on error or timeout.
|
||||||
|
//! \~russian `true`, если все пакеты отправлены и подтверждены, `false` — при ошибке или таймауте.
|
||||||
EVENT1(sendFinished, bool, ok);
|
EVENT1(sendFinished, bool, ok);
|
||||||
|
|
||||||
|
//! \~\fn void sendRequest(PIByteArray &data)
|
||||||
|
//! \~english Emitted for every encoded packet that must be written to the external transport.
|
||||||
|
//! \~russian Генерируется для каждого закодированного пакета, который нужно записать во внешний транспорт.
|
||||||
|
//! \~\param data
|
||||||
|
//! \~english Encoded packet including protocol header and payload.
|
||||||
|
//! \~russian Закодированный пакет, включая заголовок протокола и полезную нагрузку.
|
||||||
|
//! \~\note
|
||||||
|
//! \~english The external transport should send this data.
|
||||||
|
//! \~russian Внешний транспорт должен отправить эти данные.
|
||||||
EVENT1(sendRequest, PIByteArray &, data);
|
EVENT1(sendRequest, PIByteArray &, data);
|
||||||
|
|
||||||
|
//! \~\}
|
||||||
|
|
||||||
|
|
||||||
protected:
|
protected:
|
||||||
|
//! \~english Builds session packet layout for logical parts in "parts".
|
||||||
|
//! \~russian Формирует раскладку пакетов сессии для логических частей из "parts".
|
||||||
void buildSession(PIVector<Part> parts);
|
void buildSession(PIVector<Part> parts);
|
||||||
|
|
||||||
|
//! \~english Returns payload bytes for one requested logical fragment.
|
||||||
|
//! \~russian Возвращает байты полезной нагрузки для одного запрошенного логического фрагмента.
|
||||||
virtual PIByteArray buildPacket(Part fi) = 0;
|
virtual PIByteArray buildPacket(Part fi) = 0;
|
||||||
|
|
||||||
|
//! \~english Consumes one received logical fragment and optional custom packet header.
|
||||||
|
//! \~russian Обрабатывает один принятый логический фрагмент и необязательный пользовательский заголовок пакета.
|
||||||
virtual void receivePart(Part fi, PIByteArray ba, PIByteArray pheader) = 0;
|
virtual void receivePart(Part fi, PIByteArray ba, PIByteArray pheader) = 0;
|
||||||
|
|
||||||
|
//! \~english Called after a new receive session is accepted and initialized.
|
||||||
|
//! \~russian Вызывается после принятия и инициализации новой сессии приема.
|
||||||
virtual void beginReceive() { ; }
|
virtual void beginReceive() { ; }
|
||||||
|
|
||||||
|
//! \~english Custom header
|
||||||
|
//! \~russian Пользовательский заголовок
|
||||||
virtual PIByteArray customHeader() { return PIByteArray(); }
|
virtual PIByteArray customHeader() { return PIByteArray(); }
|
||||||
|
|
||||||
|
//! \~english Runs the prepared send session until success, failure or cancellation.
|
||||||
|
//! \~russian Выполняет подготовленную сессию отправки до успеха, ошибки или отмены.
|
||||||
bool send_process();
|
bool send_process();
|
||||||
|
|
||||||
uint packet_header_size, part_header_size;
|
uint packet_header_size, part_header_size;
|
||||||
@@ -156,33 +353,48 @@ private:
|
|||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
//! \~english Binary stream write operator for PacketHeader
|
||||||
|
//! \~russian Оператор записи в бинарный поток для PacketHeader
|
||||||
BINARY_STREAM_WRITE(PIBaseTransfer::PacketHeader) {
|
BINARY_STREAM_WRITE(PIBaseTransfer::PacketHeader) {
|
||||||
s << v.sig << v.type << v.session_id << v.id << v.crc;
|
s << v.sig << v.type << v.session_id << v.id << v.crc;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
//! \~english Binary stream read operator for PacketHeader
|
||||||
|
//! \~russian Оператор чтения из бинарного потока для PacketHeader
|
||||||
BINARY_STREAM_READ(PIBaseTransfer::PacketHeader) {
|
BINARY_STREAM_READ(PIBaseTransfer::PacketHeader) {
|
||||||
s >> v.sig >> v.type >> v.session_id >> v.id >> v.crc;
|
s >> v.sig >> v.type >> v.session_id >> v.id >> v.crc;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Binary stream write operator for Part
|
||||||
|
//! \~russian Оператор записи в бинарный поток для Part
|
||||||
BINARY_STREAM_WRITE(PIBaseTransfer::Part) {
|
BINARY_STREAM_WRITE(PIBaseTransfer::Part) {
|
||||||
s << v.id << v.size << v.start;
|
s << v.id << v.size << v.start;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
//! \~english Binary stream read operator for Part
|
||||||
|
//! \~russian Оператор чтения из бинарного потока для Part
|
||||||
BINARY_STREAM_READ(PIBaseTransfer::Part) {
|
BINARY_STREAM_READ(PIBaseTransfer::Part) {
|
||||||
s >> v.id >> v.size >> v.start;
|
s >> v.id >> v.size >> v.start;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~english Binary stream write operator for StartRequest
|
||||||
|
//! \~russian Оператор записи в бинарный поток для StartRequest
|
||||||
BINARY_STREAM_WRITE(PIBaseTransfer::StartRequest) {
|
BINARY_STREAM_WRITE(PIBaseTransfer::StartRequest) {
|
||||||
s << v.packets << v.size;
|
s << v.packets << v.size;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
//! \~english Binary stream read operator for StartRequest
|
||||||
|
//! \~russian Оператор чтения из бинарного потока для StartRequest
|
||||||
BINARY_STREAM_READ(PIBaseTransfer::StartRequest) {
|
BINARY_STREAM_READ(PIBaseTransfer::StartRequest) {
|
||||||
s >> v.packets >> v.size;
|
s >> v.packets >> v.size;
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
//! \~\relatesalso PICout
|
||||||
|
//! \~english Writes Part to \a PICout.
|
||||||
|
//! \~russian Выводит Part в \a PICout.
|
||||||
inline PICout operator<<(PICout s, const PIBaseTransfer::Part & v) {
|
inline PICout operator<<(PICout s, const PIBaseTransfer::Part & v) {
|
||||||
s.saveAndSetControls(0);
|
s.saveAndSetControls(0);
|
||||||
s << "Part(\"" << v.id << "\", " << PIString::readableSize(v.start) << " b | " << PIString::readableSize(v.size) << " b)";
|
s << "Part(\"" << v.id << "\", " << PIString::readableSize(v.start) << " b | " << PIString::readableSize(v.size) << " b)";
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user