39 Commits

Author SHA1 Message Date
f52fd45936 version 2026-03-26 09:33:23 +03:00
88d4a8e74d PIByteArray gcc one annoying warning off 2026-03-26 09:32:30 +03:00
6ddc7263e8 Merge pull request 'add new PIThreadPoolWorker - rework of PIThreadPoolExecutor' (#202) from PIThreadPoolWorker into master
Reviewed-on: #202
Reviewed-by: Бычков Андрей <andrey@signalmodelling.ru>
2026-03-26 09:12:23 +03:00
a16f629dc5 PIThreadPoolWorker ready to use 2026-03-25 10:59:32 +03:00
5868e0ec9d work with PIThreadPoolWorker 2026-03-24 19:56:43 +03:00
3102b985d5 add new PIThreadPoolWorker - rework of PIThreadPoolExecutor 2026-03-24 14:09:41 +03:00
93547beb38 Merge pull request 'disable gmock build and remove obsolete tests' (#201) from disable_gmock into master
Reviewed-on: #201
2026-03-21 17:00:45 +03:00
5794eac20a Merge pull request 'move std function' (#200) from pitimer_slot into master
Reviewed-on: #200
2026-03-21 17:00:36 +03:00
edb7189013 disable gmock build and remove obsolete tests 2026-03-21 13:31:29 +03:00
dc16a0c903 CMakeLists.txt 2026-03-20 17:26:58 +03:00
96c22e1184 move std function 2026-03-20 16:31:30 +03:00
4537e40832 Merge branch 'master' into pitimer_slot 2026-03-20 15:35:34 +03:00
6efe77a395 add move 2026-03-20 13:46:31 +03:00
6cfc4524f0 PITimer slot optimize 2026-03-20 13:19:55 +03:00
fe3b30bd49 version 5.6.1
patch deploy_tool: procDpkg now prioritize "non-cross" and "non-dev" packages, then only "non-cross"
add PIP_MANUAL_TEST CMake option
2026-03-20 13:00:24 +03:00
a1be5be5a1 increase timeout and remove sleep 2026-03-18 15:01:17 +03:00
99c99c39c2 separate cmake opts for tests 2026-03-18 13:39:01 +03:00
ba63e72bfa Merge pull request 'disable exeptions in cmake' (#199) from disable_exeptions into master
Reviewed-on: #199
2026-03-18 11:48:54 +03:00
79fa549201 fix matrix test 2026-03-18 11:46:08 +03:00
35140ee002 Merge pull request 'some fixes' (#198) from some_fixes into master
Reviewed-on: #198
2026-03-18 11:08:48 +03:00
f0c8bfef0a Merge pull request 'simplify piprotectedvariable' (#197) from protected_var_refact into master
Reviewed-on: #197
2026-03-18 10:58:58 +03:00
ba57aa0144 disable exceptions on win 2026-03-18 09:40:32 +03:00
ccbf86f781 disable exeptions in cmake 2026-03-18 09:30:28 +03:00
ac415ebbb6 revert can_unlock flag 2026-03-18 08:54:06 +03:00
c02b627d47 some fixes
PIEthernet::listen
PIClientServer::Server::~Server
PISystemTime const sleep
ClientServer tests fast and stable
2026-03-17 20:14:22 +03:00
9dc1af921c more simplify Pointer 2026-03-17 19:18:44 +03:00
e761625eab using recursive mutex 2026-03-17 19:14:14 +03:00
449978bda0 revert main and more tests 2026-03-17 19:07:01 +03:00
fe01c353e6 simplify tests 2026-03-17 18:56:20 +03:00
9f57f0107e remove picout 2026-03-17 18:34:48 +03:00
ac877f1024 fixes 2026-03-17 18:13:23 +03:00
8ccc05ee78 simplify piprotectedvariable 2026-03-17 17:33:27 +03:00
2798d7de9c fix gitignore 2026-03-17 09:33:10 +03:00
767bb2b382 doc 2026-03-12 19:55:06 +03:00
3e5714a5e1 doc 2026-03-12 19:27:21 +03:00
6e4a64e64a doc 2026-03-12 19:21:03 +03:00
40cdc90131 fix 2026-03-12 19:13:12 +03:00
d758cea974 doc fix 2026-03-12 19:11:28 +03:00
ed13838237 merged AI doc, some new pages 2026-03-12 14:46:57 +03:00
213 changed files with 6972 additions and 4979 deletions

2
.gitignore vendored
View File

@@ -1,5 +1,5 @@
/src_main/piversion.h /src_main/piversion.h
/.svn /.*
/doc/rtf /doc/rtf
_unsused _unsused
CMakeLists.txt.user* CMakeLists.txt.user*

View File

@@ -97,8 +97,10 @@ public:
{ {
int code = lua_pcall (L, nargs, nresults, msgh); int code = lua_pcall (L, nargs, nresults, msgh);
if (code != LUABRIDGE_LUA_OK) if (code != LUABRIDGE_LUA_OK) {
Throw (LuaException (L, code)); // Throw (LuaException (L, code));
assert(true);
}
} }
//---------------------------------------------------------------------------- //----------------------------------------------------------------------------
@@ -128,7 +130,8 @@ protected:
private: private:
static int throwAtPanic (lua_State* L) static int throwAtPanic (lua_State* L)
{ {
throw LuaException (L, -1); // throw LuaException (L, -1);
return -1;
} }
}; };

View File

@@ -101,7 +101,8 @@ protected:
{ {
if (m_stackSize == 0) if (m_stackSize == 0)
{ {
throw std::logic_error ("Unable to continue registration"); std::cerr << ("Unable to continue registration");
assert(true);
} }
} }
}; };
@@ -1054,7 +1055,8 @@ public:
{ {
if (m_stackSize == 1) if (m_stackSize == 1)
{ {
throw std::logic_error ("endNamespace () called on global namespace"); std::cerr << ("endNamespace () called on global namespace");
assert(true);
} }
assert (m_stackSize > 1); assert (m_stackSize > 1);
@@ -1150,7 +1152,8 @@ public:
{ {
if (m_stackSize == 1) if (m_stackSize == 1)
{ {
throw std::logic_error ("addProperty () called on global namespace"); std::cerr << ("addProperty () called on global namespace");
assert(true);
} }
assert (lua_istable (L, -1)); // Stack: namespace table (ns) assert (lua_istable (L, -1)); // Stack: namespace table (ns)

View File

@@ -33,6 +33,7 @@
#include <cassert> #include <cassert>
#include <stdexcept> #include <stdexcept>
#include <iostream>
namespace luabridge { namespace luabridge {
@@ -320,7 +321,8 @@ public:
lua_rawgetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ()); lua_rawgetp (L, LUA_REGISTRYINDEX, ClassInfo <T>::getClassKey ());
if (!lua_istable (L, -1)) if (!lua_istable (L, -1))
{ {
throw std::logic_error ("The class is not registered in LuaBridge"); std::cerr << ("The class is not registered in LuaBridge");
assert(true);
} }
lua_setmetatable (L, -2); lua_setmetatable (L, -2);
return ud; return ud;
@@ -375,7 +377,8 @@ private:
lua_rawgetp (L, LUA_REGISTRYINDEX, key); lua_rawgetp (L, LUA_REGISTRYINDEX, key);
if (!lua_istable (L, -1)) if (!lua_istable (L, -1))
{ {
throw std::logic_error ("The class is not registered in LuaBridge"); std::cerr << ("The class is not registered in LuaBridge");
assert(true);
} }
lua_setmetatable (L, -2); lua_setmetatable (L, -2);
} }

View File

@@ -5,9 +5,9 @@ if (POLICY CMP0177)
endif() endif()
project(PIP) project(PIP)
set(PIP_MAJOR 5) set(PIP_MAJOR 5)
set(PIP_MINOR 6) set(PIP_MINOR 7)
set(PIP_REVISION 0) set(PIP_REVISION 0)
set(PIP_SUFFIX ) set(PIP_SUFFIX _alpha)
set(PIP_COMPANY SHS) set(PIP_COMPANY SHS)
set(PIP_DOMAIN org.SHS) set(PIP_DOMAIN org.SHS)
@@ -67,11 +67,13 @@ set(PIP_DLL_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE STRING "")
option(ICU "ICU support for convert codepages" ${_ICU_DEFAULT}) option(ICU "ICU support for convert codepages" ${_ICU_DEFAULT})
option(STD_IOSTREAM "Building with std iostream operators support" OFF) option(STD_IOSTREAM "Building with std iostream operators support" OFF)
option(INTROSPECTION "Build with introspection" OFF) option(INTROSPECTION "Build with introspection" OFF)
option(TESTS "Build tests and perform their before install step" OFF) option(TESTS "Build tests" OFF)
option(TESTS_RUN "Run tests before install step" OFF)
option(COVERAGE "Build project with coverage info" OFF) option(COVERAGE "Build project with coverage info" OFF)
option(PIP_FFTW_F "Support fftw module for float" ON) option(PIP_FFTW_F "Support fftw module for float" ON)
option(PIP_FFTW_L "Support fftw module for long double" ON) option(PIP_FFTW_L "Support fftw module for long double" ON)
option(PIP_FFTW_Q "Support fftw module for quad double" OFF) option(PIP_FFTW_Q "Support fftw module for quad double" OFF)
option(PIP_MANUAL_TEST "Build dev test (main.cpp)" OFF)
set(PIP_UTILS 1) set(PIP_UTILS 1)
set(CMAKE_CXX_STANDARD_REQUIRED TRUE) set(CMAKE_CXX_STANDARD_REQUIRED TRUE)
set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD 11)
@@ -360,10 +362,13 @@ endif()
if(WIN32) if(WIN32)
add_definitions(-DPSAPI_VERSION=1) add_definitions(-DPSAPI_VERSION=1)
if(${C_COMPILER} STREQUAL "cl.exe") if(${C_COMPILER} STREQUAL "cl.exe")
set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0") set(CMAKE_CXX_FLAGS "/O2 /Ob2 /Ot /W0 /EH-")
endif() endif()
else() else()
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fPIC")
if (NOT DEFINED ANDROID_PLATFORM)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fno-exceptions")
endif()
if(DEFINED ENV{QNX_HOST} OR PIP_FREERTOS) if(DEFINED ENV{QNX_HOST} OR PIP_FREERTOS)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth-32") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -ftemplate-depth-32")
endif() endif()
@@ -592,12 +597,14 @@ if (NOT CROSSTOOLS)
#target_link_libraries(pip_plugin pip) #target_link_libraries(pip_plugin pip)
if (NOT DEFINED ANDROID_PLATFORM) if (NOT DEFINED ANDROID_PLATFORM)
if(microhttpd_FOUND AND curl_FOUND) if (PIP_MANUAL_TEST)
add_executable(pip_test "main.cpp") if(microhttpd_FOUND AND curl_FOUND)
target_link_libraries(pip_test pip pip_io_utils pip_client_server pip_http_server pip_http_client) add_executable(pip_test "main.cpp")
if(sodium_FOUND) target_link_libraries(pip_test pip pip_io_utils pip_client_server pip_http_server pip_http_client)
add_executable(pip_cloud_test "main_picloud_test.cpp") if(sodium_FOUND)
target_link_libraries(pip_cloud_test pip_cloud) add_executable(pip_cloud_test "main_picloud_test.cpp")
target_link_libraries(pip_cloud_test pip_cloud)
endif()
endif() endif()
endif() endif()
endif() endif()
@@ -823,6 +830,9 @@ if (PIP_TESTS_LIST)
foreach(_test ${PIP_TESTS_LIST}) foreach(_test ${PIP_TESTS_LIST})
message(" * ${_test}") message(" * ${_test}")
endforeach() endforeach()
if (TESTS_RUN)
message("TESTS_RUN ON -> Run tests before install step")
endif()
else() else()
message(" Tests: skip (tests off)") message(" Tests: skip (tests off)")
endif() endif()

View File

@@ -3,67 +3,712 @@
\~english \~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. # State Machine
# Concepts ## State Machine Description
* **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. State machine is a behavioral design pattern that allows an object to change its behavior when its internal state changes.
* **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. Implementation in PIP is based on the **SCXML** (State Chart XML) standard.
* **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. ### SCXML Concepts
# Minimal example - **State** — a node in the state tree, can be atomic or compound
- **Transition** — a connection between states that triggers on an event
- **Event** — a trigger that causes a transition
- **Guard** — a condition that must be true for a transition to execute
- **Action** — an operation executed during a transition
- **Parallel** — a state where all substates are activated simultaneously
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. ### PIP State Machine Features
- **Cannot create state, event, transition on stack** — all objects are created via `new` and managed via pointers
- **State machine is the root state** — `PIStateMachine` inherits from `PIStateBase`
- **All transitions and states are automatically deleted** — when the parent object is destroyed
### State Types
- **Atomic state** — a state without nested substates
- **Compound state** — a state containing nested substates
- **Final state** — a terminating state indicating the end of machine execution
- **Parallel state** — a state where all substates are activated simultaneously
### Transition Types
- **Normal transition** — triggers on receiving a specific event
- **Timeout transition** — triggers automatically after a specified time interval
- **Guarded transition** — triggers only when a specific condition is met
## State Machine API
### Main Classes
#### PIStateMachine
Main state machine class.
**Key methods:**
- `bool start()` — starts state machine execution
- `bool isRunning()` — checks if state machine is running
- `void setOnFinish(std::function<void()> f)` — sets finish callback
- `bool postEvent(int event_id, Args... args)` — posts event to state machine
#### PIStateBase
Base class for all states.
**Key methods:**
- `virtual void onEnter()` — called when state is entered
- `virtual void onExit()` — called when state is exited
- `void addState(PIStateBase *s)` — adds child state
- `PITransitionBase *addTransition(PIStateBase *target, int event_id)` — adds transition
- `PITransitionTimeout *addTimeoutTransition(PIStateBase *target, PISystemTime timeout)` — adds timeout transition
- `void setParallel(bool yes)` — sets parallel mode
#### PIStateLambda
State with lambda callbacks.
\code{.cpp} \code{.cpp}
enum Mode { Start, Manual, Auto, Finish, End }; PIStateLambda(std::function<void()> on_enter, std::function<void()> on_exit = nullptr, const PIString &n = {})
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 \endcode
Full example: doc/examples/pistatemachine.cpp. API details: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h. #### PIStateFinal
Final state of state machine.
\code{.cpp}
PIStateFinal(std::function<void()> on_finish = nullptr, const PIString &n = {})
\endcode
#### PITransitionBase
Base class for transitions.
**Key methods:**
- `PITransitionBase *addGuard(std::function<R(Args...)> f)` — adds guard function
- `PITransitionBase *addAction(std::function<void()> a)` — adds action
- `void trigger()` — triggers transition
#### PITransitionTimeout
Transition that triggers after a specified timeout.
## Usage Examples
### Simple State Machine
\code{.cpp}
#include "pistatemachine.h"
#include "pisystemtime.h"
// Create state machine
PIStateMachine *machine = new PIStateMachine("Main");
// Create states
PIStateLambda *idle = new PIStateLambda(
[]() { piCout << "Entering Idle state\n"; },
[]() { piCout << "Exiting Idle state\n"; },
"Idle"
);
PIStateLambda *running = new PIStateLambda(
[]() { piCout << "Entering Running state\n"; },
[]() { piCout << "Exiting Running state\n"; },
"Running"
);
PIStateFinal *finish = new PIStateFinal(
[]() { piCout << "Machine finished\n"; },
"Finish"
);
// Add states
machine->addState(idle);
machine->addState(running);
machine->addState(finish);
// Set initial state
idle->setInitialState(idle);
running->setInitialState(running);
machine->setInitialState(idle);
// Add transitions
idle->addTransition(running, 1);
running->addTransition(finish, 2);
// Set finish callback
machine->setOnFinish([]() { piCout << "Machine execution completed\n"; });
// Start machine
machine->start();
// Post events
machine->postEvent(1); // Transition to Running
machine->postEvent(2); // Transition to Finish
\endcode
### Guarded Transitions
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Guards");
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
PIStateLambda *stateC = new PIStateLambda([]() { piCout << "State C\n"; }, nullptr, "C");
machine->addState(stateA);
machine->addState(stateB);
machine->addState(stateC);
stateA->setInitialState(stateA);
machine->setInitialState(stateA);
// Transition with guard function
auto *t1 = stateA->addTransition(stateB, 1);
t1->addGuard([](int value) -> bool {
return value > 10;
});
// Transition with another guard function
auto *t2 = stateB->addTransition(stateC, 2);
t2->addGuard([](const PIString &msg) -> bool {
return msg == "allowed";
});
machine->start();
// First call will not execute (value <= 10)
machine->postEvent(1, 5);
// Second call will execute (value > 10)
machine->postEvent(1, 15);
// First call will not execute (msg != "allowed")
machine->postEvent(2, "test");
// Second call will execute (msg == "allowed")
machine->postEvent(2, "allowed");
\endcode
### Timeout Transitions
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Timeout");
PIStateLambda *working = new PIStateLambda(
[]() { piCout << "Working...\n"; },
[]() { piCout << "Stop working\n"; },
"Working"
);
PIStateLambda *timeoutState = new PIStateLambda([]() { piCout << "Timeout occurred\n"; }, nullptr, "Timeout");
PIStateFinal *finish = new PIStateFinal([]() { piCout << "Done\n"; }, "Finish");
machine->addState(working);
machine->addState(timeoutState);
machine->addState(finish);
working->setInitialState(working);
machine->setInitialState(working);
// Add timeout transition (after 5 seconds)
working->addTimeoutTransition(timeoutState, PISystemTime::fromSeconds(5));
// Add transition from timeoutState to finish
timeoutState->addTransition(finish, 1);
machine->start();
\endcode
### Compound States
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Compound States");
// Root state (machine)
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root state\n"; }, nullptr, "Root");
// Compound state with substates
PIStateLambda *parent = new PIStateLambda([]() { piCout << "Parent state\n"; }, nullptr, "Parent");
PIStateLambda *child1 = new PIStateLambda([]() { piCout << "Child 1\n"; }, nullptr, "Child1");
PIStateLambda *child2 = new PIStateLambda([]() { piCout << "Child 2\n"; }, nullptr, "Child2");
parent->setInitialState(child1);
parent->addState(child1);
parent->addState(child2);
root->addState(parent);
machine->addState(root);
machine->setInitialState(root);
// Add transitions
root->addTransition(parent, 1);
parent->addTransition(root, 2);
machine->start();
// Transition to parent
machine->postEvent(1);
// Transition back
machine->postEvent(2);
\endcode
### Parallel States
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Parallel States");
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root\n"; }, nullptr, "Root");
PIStateLambda *parallel = new PIStateLambda([]() { piCout << "Parallel\n"; }, nullptr, "Parallel");
PIStateLambda *sub1 = new PIStateLambda([]() { piCout << "Substate 1\n"; }, nullptr, "Sub1");
PIStateLambda *sub2 = new PIStateLambda([]() { piCout << "Substate 2\n"; }, nullptr, "Sub2");
// Enable parallel mode
parallel->setParallel(true);
parallel->addState(sub1);
parallel->addState(sub2);
parallel->setInitialState(sub1);
root->addState(parallel);
machine->addState(root);
machine->setInitialState(root);
machine->start();
// When entering parallel, both substates are activated simultaneously
\endcode
### Transitions with Actions
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Actions");
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
machine->addState(stateA);
machine->addState(stateB);
machine->setInitialState(stateA);
// Add transition with action
auto *t = stateA->addTransition(stateB, 1);
t->addAction([]() { piCout << "Action during transition\n"; });
machine->start();
machine->postEvent(1);
\endcode
## Thread Safety
State machine is thread-safe. The `postEvent` method uses a queue to handle nested calls, allowing safe event posting from
different threads.
## Usage Rules
### Cannot Create on Stack
\code{.cpp}
// ❌ WRONG
PIStateLambda state([]() {}, nullptr, "State");
// ✅ CORRECT
PIStateLambda *state = new PIStateLambda([]() {}, nullptr, "State");
\endcode
### Proper Object Hierarchy
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Main");
// States are created via new and added to machine or another state
PIStateLambda *state1 = new PIStateLambda([]() {}, nullptr, "State1");
PIStateLambda *state2 = new PIStateLambda([]() {}, nullptr, "State2");
machine->addState(state1);
machine->addState(state2);
// Transitions are added to states via addTransition
state1->addTransition(state2, 1);
// Machine is started
machine->start();
\endcode
### Memory Cleanup
All objects (states, transitions) are automatically deleted when the parent object is destroyed:
- When `PIStateMachine` is destroyed, all states and transitions are deleted
- When `PIStateBase` is destroyed, all child states and transitions are deleted
## Debugging
For debugging, you can use the `print()` method to output the state tree:
\code{.cpp}
machine->print();
\endcode
Also, you can use `activeAtomics()` to get a list of active states.
## Related Modules
- \ref DateTime module for `PISystemTime` used in timeout transitions
\~russian \~russian
Модуль машины состояний (\a PIStateMachine) предоставляет иерархические состояния, переходы по событиям и по таймауту и ориентирован на идеи [SCXML](https://www.w3.org/TR/scxml/). # Машина состояний
# Концепции ## Описание машины состояний
* **Состояние** — именованный узел с опциональным обработчиком входа. Состояния добавляются через \a PIStateMachine::addState() (или аналог в шаблонном подклассе): enum/id, имя, при необходимости обработчик. Машина состояний — это поведенческий паттерн проектирования, который позволяет объекту изменять свое поведение при изменении
* **Переход (правило)** — из одного состояния в другое по событию (и при выполнении условий). \a addRule() регистрирует переход; можно задать условия и действия. внутреннего состояния. Реализация в PIP основана на стандарте **SCXML** (State Chart XML).
* **Событие** — целочисленный id, посылаемый через \a postEvent(); машина доставляет его активным состояниям и выполняет первый подходящий переход.
* **Условия** — именованные флаги, требуемые для перехода (например \a addCondition() на \a Rule). Установка через \a performCondition(), сброс — \a resetConditions().
* **Таймаут** — переход по истечении времени; используется вместе с \a PITimer или встроенной поддержкой таймаутов в классах переходов.
Машина — подкласс \a PIObject; к ней можно подключать таймеры и другие объекты для посылки событий. Перед запуском задают \a setInitialState() и вызывают \a start(). \a switchToState() — прямая смена состояния, \a performCondition() — выполнение именованного условия. ### Основные концепции SCXML
# Минимальный пример - **State (Состояние)** — узел в дереве состояний, может быть атомарным или составным
- **Transition (Переход)** — связь между состояниями, срабатывает при событии
- **Event (Событие)** — триггер, вызывающий переход
- **Guard (Сторожевая функция)** — условие, которое должно быть истинным для выполнения перехода
- **Action (Действие)** — операция, выполняемая при переходе
- **Parallel (Параллельное состояние)** — состояние, в котором все подсостояния активируются одновременно
Определяют enum состояний, подкласс \a PIStateMachine<YourEnum>, в конструкторе добавляют состояния и правила, задают начальное состояние и запускают. События посылают из обработчика клавиш, таймера и т.д. Код минимального примера приведён выше в англоязычной секции. ### Особенности реализации PIP
Полный пример: doc/examples/pistatemachine.cpp. Детали API: \a PIStateMachine, \a PIStateBase, \a pistatemachine_state.h, \a pistatemachine_transition.h. - **Нельзя создавать state, event, transition в стеке** — все объекты создаются через `new` и управляются через указатели
- **Машина состояний — это корневой state** — `PIStateMachine` наследуется от `PIStateBase`
- **Все переходы и состояния удаляются автоматически** — при уничтожении родительского объекта
### Основные типы состояний
- **Атомарное состояние** — состояние без вложенных подсостояний
- **Составное состояние** — состояние, содержащее вложенные подсостояния
- **Финальное состояние** — завершающее состояние, указывающее на окончание работы машины
- **Параллельное состояние** — состояние, в котором все подсостояния активируются одновременно
### Виды переходов
- **Обычный переход** — срабатывает при получении определенного события
- **Переход по таймауту** — срабатывает автоматически через заданный промежуток времени
- **Переход с guard** — срабатывает только при выполнении определенного условия
## PIP State Machine API
### Основные классы
#### PIStateMachine
Основной класс машины состояний.
**Ключевые методы:**
- `bool start()` — запускает выполнение машины состояний
- `bool isRunning()` — проверяет, запущена ли машина
- `void setOnFinish(std::function<void()> f)` — устанавливает коллбэк завершения
- `bool postEvent(int event_id, Args... args)` — отправляет событие в машину состояний
#### PIStateBase
Базовый класс для всех состояний.
**Ключевые методы:**
- `virtual void onEnter()` — вызывается при входе в состояние
- `virtual void onExit()` — вызывается при выходе из состояния
- `void addState(PIStateBase *s)` — добавляет дочернее состояние
- `PITransitionBase *addTransition(PIStateBase *target, int event_id)` — добавляет переход
- `PITransitionTimeout *addTimeoutTransition(PIStateBase *target, PISystemTime timeout)` — добавляет переход по таймауту
- `void setParallel(bool yes)` — устанавливает параллельный режим
#### PIStateLambda
Состояние с lambda-коллбэками.
\code{.cpp}
PIStateLambda(std::function<void()> on_enter, std::function<void()> on_exit = nullptr, const PIString &n = {})
\endcode
#### PIStateFinal
Финальное состояние машины состояний.
\code{.cpp}
PIStateFinal(std::function<void()> on_finish = nullptr, const PIString &n = {})
\endcode
#### PITransitionBase
Базовый класс для переходов.
**Ключевые методы:**
- `PITransitionBase *addGuard(std::function<R(Args...)> f)` — добавляет сторожевую функцию
- `PITransitionBase *addAction(std::function<void()> a)` — добавляет действие
- `void trigger()` — запускает переход
#### PITransitionTimeout
Переход, срабатывающий через заданный промежуток времени.
## Примеры использования
### Простая машина состояний
\code{.cpp}
#include "pistatemachine.h"
#include "pisystemtime.h"
// Создаем машину состояний
PIStateMachine *machine = new PIStateMachine("Main");
// Создаем состояния
PIStateLambda *idle = new PIStateLambda(
[]() { piCout << "Entering Idle state\n"; },
[]() { piCout << "Exiting Idle state\n"; },
"Idle"
);
PIStateLambda *running = new PIStateLambda(
[]() { piCout << "Entering Running state\n"; },
[]() { piCout << "Exiting Running state\n"; },
"Running"
);
PIStateFinal *finish = new PIStateFinal(
[]() { piCout << "Machine finished\n"; },
"Finish"
);
// Добавляем состояния
machine->addState(idle);
machine->addState(running);
machine->addState(finish);
// Устанавливаем начальное состояние
idle->setInitialState(idle);
running->setInitialState(running);
machine->setInitialState(idle);
// Добавляем переходы
idle->addTransition(running, 1);
running->addTransition(finish, 2);
// Устанавливаем коллбэк завершения
machine->setOnFinish([]() { piCout << "Machine execution completed\n"; });
// Запускаем машину
machine->start();
// Отправляем события
machine->postEvent(1); // Перейти в Running
machine->postEvent(2); // Перейти в Finish
\endcode
### Машина состояний с guard-функциями
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Guards");
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
PIStateLambda *stateC = new PIStateLambda([]() { piCout << "State C\n"; }, nullptr, "C");
machine->addState(stateA);
machine->addState(stateB);
machine->addState(stateC);
stateA->setInitialState(stateA);
machine->setInitialState(stateA);
// Переход с guard-функцией
auto *t1 = stateA->addTransition(stateB, 1);
t1->addGuard([](int value) -> bool {
return value > 10;
});
// Переход с другой guard-функцией
auto *t2 = stateB->addTransition(stateC, 2);
t2->addGuard([](const PIString &msg) -> bool {
return msg == "allowed";
});
machine->start();
// Первый вызов не выполнится (value <= 10)
machine->postEvent(1, 5);
// Второй вызов выполнится (value > 10)
machine->postEvent(1, 15);
// Первый вызов не выполнится (msg != "allowed")
machine->postEvent(2, "test");
// Второй вызов выполнится (msg == "allowed")
machine->postEvent(2, "allowed");
\endcode
### Машина состояний с таймаутами
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Timeout");
PIStateLambda *working = new PIStateLambda(
[]() { piCout << "Working...\n"; },
[]() { piCout << "Stop working\n"; },
"Working"
);
PIStateLambda *timeoutState = new PIStateLambda([]() { piCout << "Timeout occurred\n"; }, nullptr, "Timeout");
PIStateFinal *finish = new PIStateFinal([]() { piCout << "Done\n"; }, "Finish");
machine->addState(working);
machine->addState(timeoutState);
machine->addState(finish);
working->setInitialState(working);
machine->setInitialState(working);
// Добавляем переход по таймауту (через 5 секунд)
working->addTimeoutTransition(timeoutState, PISystemTime::fromSeconds(5));
// Добавляем переход из timeoutState в finish
timeoutState->addTransition(finish, 1);
machine->start();
\endcode
### Составные состояния
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Compound States");
// Корневое состояние (машина)
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root state\n"; }, nullptr, "Root");
// Составное состояние с подсостояниями
PIStateLambda *parent = new PIStateLambda([]() { piCout << "Parent state\n"; }, nullptr, "Parent");
PIStateLambda *child1 = new PIStateLambda([]() { piCout << "Child 1\n"; }, nullptr, "Child1");
PIStateLambda *child2 = new PIStateLambda([]() { piCout << "Child 2\n"; }, nullptr, "Child2");
parent->setInitialState(child1);
parent->addState(child1);
parent->addState(child2);
root->addState(parent);
machine->addState(root);
machine->setInitialState(root);
// Добавляем переходы
root->addTransition(parent, 1);
parent->addTransition(root, 2);
machine->start();
// Переход в parent
machine->postEvent(1);
// Переход обратно
machine->postEvent(2);
\endcode
### Параллельные состояния
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Parallel States");
PIStateLambda *root = new PIStateLambda([]() { piCout << "Root\n"; }, nullptr, "Root");
PIStateLambda *parallel = new PIStateLambda([]() { piCout << "Parallel\n"; }, nullptr, "Parallel");
PIStateLambda *sub1 = new PIStateLambda([]() { piCout << "Substate 1\n"; }, nullptr, "Sub1");
PIStateLambda *sub2 = new PIStateLambda([]() { piCout << "Substate 2\n"; }, nullptr, "Sub2");
// Включаем параллельный режим
parallel->setParallel(true);
parallel->addState(sub1);
parallel->addState(sub2);
parallel->setInitialState(sub1);
root->addState(parallel);
machine->addState(root);
machine->setInitialState(root);
machine->start();
// При входе в parallel оба подсостояния активируются одновременно
\endcode
### Машина состояний с действиями
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("With Actions");
PIStateLambda *stateA = new PIStateLambda([]() { piCout << "State A\n"; }, nullptr, "A");
PIStateLambda *stateB = new PIStateLambda([]() { piCout << "State B\n"; }, nullptr, "B");
machine->addState(stateA);
machine->addState(stateB);
machine->setInitialState(stateA);
// Добавляем переход с действием
auto *t = stateA->addTransition(stateB, 1);
t->addAction([]() { piCout << "Action during transition\n"; });
machine->start();
machine->postEvent(1);
\endcode
## Потокобезопасность
Машина состояний PIP потокобезопасна. Метод `postEvent` использует очередь для обработки вложенных вызовов, что позволяет
безопасно отправлять события из разных потоков.
## Правила использования
### Нельзя создавать в стеке
\code{.cpp}
// ❌ НЕЛЬЗЯ
PIStateLambda state([]() {}, nullptr, "State");
// ✅ ПРАВИЛЬНО
PIStateLambda *state = new PIStateLambda([]() {}, nullptr, "State");
\endcode
### Правильная иерархия объектов
\code{.cpp}
PIStateMachine *machine = new PIStateMachine("Main");
// Состояния создаются через new и добавляются в машину или другое состояние
PIStateLambda *state1 = new PIStateLambda([]() {}, nullptr, "State1");
PIStateLambda *state2 = new PIStateLambda([]() {}, nullptr, "State2");
machine->addState(state1);
machine->addState(state2);
// Переходы добавляются к состояниям через addTransition
state1->addTransition(state2, 1);
// Машина запускается
machine->start();
\endcode
### Очистка памяти
Все объекты (состояния, переходы) автоматически удаляются при уничтожении родительского объекта:
- При уничтожении `PIStateMachine` удаляются все состояния и переходы
- При уничтожении `PIStateBase` удаляются все дочерние состояния и переходы
## Отладка
Для отладки можно использовать метод `print()` для вывода дерева состояний:
\code{.cpp}
machine->print();
\endcode
Также можно использовать `activeAtomics()` для получения списка активных состояний.
## Связанные модули
- \ref DateTime модуль для `PISystemTime`, используемого в переходах по таймауту

View File

@@ -72,11 +72,7 @@ PIClientServer::Server::~Server() {
clean_thread->waitForFinish(); clean_thread->waitForFinish();
piDeleteSafety(clean_thread); piDeleteSafety(clean_thread);
stopServer(); stopServer();
for (auto c: clients) { closeAll();
c->aboutDelete();
c->destroy();
delete c;
}
piDeleteSafety(tcp_server); piDeleteSafety(tcp_server);
} }

View File

@@ -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() {}

View File

@@ -247,7 +247,7 @@ PIHTTPClient * PIHTTPClient::onFinish(std::function<void()> f) {
PIHTTPClient * PIHTTPClient::onFinish(std::function<void(const PIHTTP::MessageConst &)> f) { PIHTTPClient * PIHTTPClient::onFinish(std::function<void(const PIHTTP::MessageConst &)> f) {
on_finish = f; on_finish = std::move(f);
return this; return this;
} }
@@ -258,7 +258,7 @@ PIHTTPClient * PIHTTPClient::onError(std::function<void()> f) {
PIHTTPClient * PIHTTPClient::onError(std::function<void(const PIHTTP::MessageConst &)> f) { PIHTTPClient * PIHTTPClient::onError(std::function<void(const PIHTTP::MessageConst &)> f) {
on_error = f; on_error = std::move(f);
return this; return this;
} }
@@ -269,7 +269,7 @@ PIHTTPClient * PIHTTPClient::onAbort(std::function<void()> f) {
PIHTTPClient * PIHTTPClient::onAbort(std::function<void(const PIHTTP::MessageConst &)> f) { PIHTTPClient * PIHTTPClient::onAbort(std::function<void(const PIHTTP::MessageConst &)> f) {
on_abort = f; on_abort = std::move(f);
return this; return this;
} }

View File

@@ -45,7 +45,7 @@ bool PIHTTPServer::registerPath(const PIString & path, PIHTTP::Method method, Re
Endpoint ep; Endpoint ep;
if (!ep.create(path)) return false; if (!ep.create(path)) return false;
ep.method = method; ep.method = method;
ep.function = functor; ep.function = std::move(functor);
endpoints[ep.priority] << ep; endpoints[ep.priority] << ep;
return true; return true;
} }

View File

@@ -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.

View File

@@ -1,12 +1,11 @@
/*! \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
Ivan Pelipenko peri4ko@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
@@ -30,10 +29,13 @@
#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)

View File

@@ -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,16 +29,19 @@
class PISharedMemory; class PISharedMemory;
//! \ingroup Application //! \~\ingroup Application
//! \~\brief //! \~\brief
//! \~english Single-instance application control. //! \~english Single-instance application control.
//! \~russian Контроль одного экземпляра приложения. //! \~russian Контроль одного экземпляра приложения.
//! \~\details //! \~\details
//! \~english Instances created with the same application name share a channel: //! \~english The PISingleApplication class provides single-instance application control. It allows detecting if the current application
//! the first instance listens for messages, later instances can send data to it. //! instance is the first one launched and enables inter-process communication between multiple instances. Multiple instances with the same
//! \~russian Экземпляры, созданные с одинаковым именем приложения, используют //! "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);
@@ -57,16 +59,14 @@ public:
//! \~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 Sends message "m" to the first launched instance. //! \~english Sends message "m" to the first launched application instance
//! \~russian Отправляет сообщение "m" первому запущенному экземпляру. //! \~russian Посылает сообщение "m" первому запущенному экземпляру приложения
EVENT_HANDLER1(void, sendMessage, const PIByteArray &, m);
//! \} //! \}
//! \events //! \events
@@ -74,8 +74,9 @@ public:
//! \fn void messageReceived(PIByteArray m) //! \fn void messageReceived(PIByteArray m)
//! \brief //! \brief
//! \~english Raised in the first launched instance when another instance sends a message. //! \~english Emitted by the first launched application when receiving a message from another instance
//! \~russian Вызывается в первом запущенном экземпляре при получении сообщения от другого экземпляра. //! \~russian Вызывается первым запущенным приложением при получении сообщения от другого экземпляра
EVENT1(messageReceived, PIByteArray, m);
//! \} //! \}

View File

@@ -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,10 +29,15 @@
#include "pithread.h" #include "pithread.h"
//! \ingroup Application //! \~\ingroup Application
//! \~\brief //! \~\brief
//! \~english Process and thread resource 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;
@@ -48,7 +52,7 @@ public:
~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 Статистика процесса (фиксированные поля).
@@ -118,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 Статистика потока (фиксированные поля).
@@ -153,7 +157,7 @@ public:
}; };
#pragma pack(pop) #pragma pack(pop)
//! \ingroup Application //! \~\ingroup Application
//! \~\brief //! \~\brief
//! \~english Process statistics. //! \~english Process statistics.
//! \~russian Статистика процесса. //! \~russian Статистика процесса.
@@ -191,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 Статистика потока.
@@ -246,10 +250,16 @@ public:
//! \~russian Возвращает используемый объем RAM в байтах на поддерживаемых платформах. //! \~russian Возвращает используемый объем RAM в байтах на поддерживаемых платформах.
static ullong usedRAM(); static ullong usedRAM();
//! \~\events
//! \~\{
//! \~\fn void measured()
//! \~english Raised after a new statistics snapshot is measured. //! \~english Raised after a new statistics snapshot is measured.
//! \~russian Вызывается после измерения нового снимка статистики. //! \~russian Вызывается после измерения нового снимка статисти
EVENT(measured); EVENT(measured);
//! \~\}
private: private:
void run() override; void run() override;
void gatherThread(llong id); void gatherThread(llong id);
@@ -265,20 +275,11 @@ private:
PRIVATE_DECLARATION(PIP_EXPORT) PRIVATE_DECLARATION(PIP_EXPORT)
#endif #endif
//! \ingroup Application
//! \~\brief
//! \~english Registry of active system monitors.
//! \~russian Реестр активных системных мониторов.
class PIP_EXPORT Pool { class PIP_EXPORT Pool {
friend class PISystemMonitor; friend class PISystemMonitor;
public: public:
//! \~english Returns singleton pool of active monitors indexed by PID.
//! \~russian Возвращает синглтон-пул активных мониторов, индексированных по PID.
static Pool * instance(); static Pool * instance();
//! \~english Returns monitor registered for "pID", or null if it is absent.
//! \~russian Возвращает монитор, зарегистрированный для "pID", или null если его нет.
PISystemMonitor * getByPID(int pID); PISystemMonitor * getByPID(int pID);
private: private:

View File

@@ -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
@@ -43,19 +42,23 @@
//! \~russian Алиас к \a PITranslator::trNoOp(). //! \~russian Алиас к \a PITranslator::trNoOp().
# define piTrNoOp # define piTrNoOp
#else
# define piTr PITranslator::tr
# define piTrNoOp PITranslator::trNoOp
#endif #endif
#define piTr PITranslator::tr //! \~\ingroup Application
#define piTrNoOp PITranslator::trNoOp
//! \ingroup Application
//! \~\brief //! \~\brief
//! \~english Translation support //! \~english Translation support
//! \~russian Поддержка перевода //! \~russian Поддержка перевода
//! \~\details //! \~\details
//! \~english %PITranslator stores loaded translations in a process-wide singleton. //! \~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. //! If translation or context is missing, the source string is returned unchanged.
//! \~russian %PITranslator хранит загруженные переводы в синглтоне процесса. //! \~russian Предоставляет поддержку перевода с контекстно-зависимыми обертками строк и методами загрузки.
//! %PITranslator хранит загруженные переводы в синглтоне процесса.
//! Если перевод или контекст не найдены, исходная строка возвращается без изменений. //! Если перевод или контекст не найдены, исходная строка возвращается без изменений.
class PIP_EXPORT PITranslator { class PIP_EXPORT PITranslator {
public: public:
@@ -105,10 +108,12 @@ private:
}; };
//! \ingroup Application //! \~\ingroup Application
//! \~\brief //! \~\brief
//! \~english Helper returned by \a operator""_tr for optional-context translation. //! \~english Context-aware string wrapper that automatically translates strings using PITranslator::tr().
//! \~russian Вспомогательный тип, возвращаемый \a operator""_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. //! \~english Stores source string for later translation.
@@ -128,10 +133,12 @@ private:
}; };
//! \ingroup Application //! \~\ingroup Application
//! \~\brief //! \~\brief
//! \~english Helper returned by \a operator""_trNoOp that keeps source text unchanged. //! \~english Context-aware string wrapper that preserves original strings without translation (no-op).
//! \~russian Вспомогательный тип, возвращаемый \a operator""_trNoOp, который сохраняет исходный текст без изменений. //! 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. //! \~english Stores source string without translating it.
@@ -154,6 +161,7 @@ private:
//! \~\brief //! \~\brief
//! \~english User-defined literal that defers translation through \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));
} }
@@ -161,6 +169,7 @@ inline PIStringContextTr operator""_tr(const char * v, size_t sz) {
//! \~\brief //! \~\brief
//! \~english User-defined literal that keeps source text unchanged via \a PITranslator::trNoOp(). //! \~english User-defined literal that keeps source text unchanged via \a PITranslator::trNoOp().
//! \~russian Пользовательский литерал, сохраняющий исходный текст без изменений через \a PITranslator::trNoOp(). //! \~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));
} }

View File

@@ -1,9 +1,8 @@
/*! \file piclientserver_client.h //! \~\file piclientserver_client.h
* \ingroup ClientServer //! \~\ingroup ClientServer
* \~\brief //! \brief
* \~english Client-side and server-side client connection classes //! \~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,10 +32,15 @@ namespace PIClientServer {
// ServerClient // ServerClient
//! \ingroup ClientServer //! \~\ingroup ClientServer
//! \~\brief //! \~\brief
//! \~english Server-side representation of one accepted client connection. //! \~english Server-side representation of one accepted client connection.
//! \~russian Серверное представление одного принятого клиентского соединения. //! \~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);
@@ -58,10 +62,15 @@ private:
// Client // Client
//! \ingroup ClientServer //! \~\ingroup ClientServer
//! \~\brief //! \~\brief
//! \~english Active client connection that initiates a connection to a server. //! \~english Active client connection that initiates a connection to a server.
//! \~russian Активное клиентское соединение, которое само подключается к серверу. //! \~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);

View File

@@ -1,9 +1,11 @@
/*! \file piclientserver_client_base.h //! \~\file piclientserver_client_base.h
* \ingroup ClientServer //! \~\ingroup ClientServer
* \~\brief //! \brief
* \~english Base declarations for client connections in the %ClientServer module //! \~english Base class for client-server communication
* \~russian Базовые объявления клиентских соединений в модуле %ClientServer //! \~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,16 +37,12 @@ namespace PIClientServer {
class Server; class Server;
//! \ingroup ClientServer //! \~\ingroup ClientServer
//! \~\brief //! \~\brief
//! \~english Marker interface for client-side entities in the module. //! \~english Base class for client and server-side client communication. Provides TCP connection management, diagnostics, and packet
//! \~russian Маркерный интерфейс для клиентских сущностей модуля. //! streaming capabilities.
class ClientInterface {}; //! \~russian Базовый класс для клиентской и серверной коммуникации. Обеспечивает управление TCP-соединением, диагностику и потоковую
//! передачу пакетов.
//! \ingroup ClientServer
//! \~\brief
//! \~english Base class for one packet-based client connection.
//! \~russian Базовый класс для одного пакетного клиентского соединения.
// 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;
@@ -54,10 +52,12 @@ public:
//! \~english Constructs a disconnected client connection object. //! \~english Constructs a disconnected client connection object.
//! \~russian Создает объект клиентского соединения в отключенном состоянии. //! \~russian Создает объект клиентского соединения в отключенном состоянии.
ClientBase(); ClientBase();
//! \~english Destroys the client connection and releases owned resources. //! \~english Destroys the client connection and releases owned resources.
//! \~russian Уничтожает клиентское соединение и освобождает связанные ресурсы. //! \~russian Уничтожает клиентское соединение и освобождает связанные ресурсы.
virtual ~ClientBase(); virtual ~ClientBase();
//! \~english Returns the underlying TCP transport object. //! \~english Returns the underlying TCP transport object.
//! \~russian Возвращает базовый объект TCP-транспорта. //! \~russian Возвращает базовый объект TCP-транспорта.
const PIEthernet * getTCP() const { return tcp; } const PIEthernet * getTCP() const { return tcp; }
@@ -89,16 +89,18 @@ public:
PIDiagnostics::State diagnostics() const; PIDiagnostics::State diagnostics() const;
//! \~english Returns how many payload bytes of the current packet are already received. //! \~english Returns how many payload bytes of the current packet are already received (all bytes count passed in \a receivePacketStart()).
//! \~russian Возвращает, сколько байтов полезной нагрузки текущего пакета уже получено. //! \~russian Возвращает, сколько байтов полезной нагрузки текущего пакета уже получено (общее количество передается в \a receivePacketStart()).
int receivePacketProgress() const; int receivePacketProgress() const;
//! \~english Returns the current packet framing configuration. //! \~english Returns the current packet framing configuration.
//! \~russian Возвращает текущую конфигурацию пакетирования. //! \~russian Возвращает текущую конфигурацию пакетирования.
const PIStreamPackerConfig & configuration() const { return stream.configuration(); } const PIStreamPackerConfig & configuration() const { return stream.configuration(); }
//! \~english Returns the current packet framing configuration for modification. //! \~english Returns the current packet framing configuration for modification.
//! \~russian Возвращает текущую конфигурацию пакетирования для изменения. //! \~russian Возвращает текущую конфигурацию пакетирования для изменения.
PIStreamPackerConfig & configuration() { return stream.configuration(); } PIStreamPackerConfig & configuration() { return stream.configuration(); }
//! \~english Replaces the packet framing configuration. //! \~english Replaces the packet framing configuration.
//! \~russian Заменяет конфигурацию пакетирования. //! \~russian Заменяет конфигурацию пакетирования.
void setConfiguration(const PIStreamPackerConfig & config) { stream.setConfiguration(config); } void setConfiguration(const PIStreamPackerConfig & config) { stream.setConfiguration(config); }

View File

@@ -1,9 +1,8 @@
/*! \file piclientserver_server.h //! \~\file piclientserver_server.h
* \ingroup ClientServer //! \~\ingroup ClientServer
* \~\brief //! \brief
* \~english TCP server and client factory for the %ClientServer module //! \~english TCP Server
* \~russian TCP-сервер и фабрика клиентов для модуля %ClientServer //! \~russian TCP Сервер
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Ivan Pelipenko peri4ko@yandex.ru Ivan Pelipenko peri4ko@yandex.ru
@@ -38,10 +37,12 @@ namespace PIClientServer {
class ServerClient; class ServerClient;
//! \ingroup ClientServer //! \~\ingroup ClientServer
//! \~\brief //! \~\brief
//! \~english TCP server that accepts connections and manages %ServerClient objects. //! \~english TCP server implementation for client-server communication. Accepts incoming connections and manages multiple clients with
//! \~russian TCP-сервер, принимающий соединения и управляющий объектами %ServerClient. //! 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);
@@ -50,6 +51,7 @@ public:
//! \~english Constructs a stopped server with default limits. //! \~english Constructs a stopped server with default limits.
//! \~russian Создает остановленный сервер с ограничениями по умолчанию. //! \~russian Создает остановленный сервер с ограничениями по умолчанию.
Server(); Server();
//! \~english Stops the server and releases transport resources. //! \~english Stops the server and releases transport resources.
//! \~russian Останавливает сервер и освобождает транспортные ресурсы. //! \~russian Останавливает сервер и освобождает транспортные ресурсы.
virtual ~Server(); virtual ~Server();
@@ -60,6 +62,9 @@ public:
//! \~english Starts listening on all interfaces at port "port". //! \~english Starts listening on all interfaces at port "port".
//! \~russian Начинает прослушивание на всех интерфейсах на порту "port". //! \~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}); }
@@ -69,6 +74,9 @@ public:
//! \~english Closes all currently connected clients. //! \~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();
@@ -78,6 +86,9 @@ public:
//! \~english Sets the maximum number of simultaneous 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 Returns the number of currently connected clients. //! \~english Returns the number of currently connected clients.
@@ -92,7 +103,7 @@ public:
//! \~english Sets the factory used to create accepted client objects. //! \~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 = std::move(f); }
private: private:
void newClient(ServerClient * c); void newClient(ServerClient * c);

View File

@@ -1,17 +1,12 @@
/*! \file piclientservermodule.h //! \~\file piclientservermodule.h
* \ingroup ClientServer //! \~\ingroup ClientServer
* \~\brief //! \~\brief
* \~english Umbrella header and module group for TCP client-server helpers //! \~english Umbrella header and module group for TCP client-server helpers
* \~russian Общий заголовок и группа модуля для TCP-клиент-серверных компонентов //! \~russian Общий заголовок и группа модуля для TCP-клиент-серверных компонентов
*
* \~\details
* \~english Includes the public TCP client and server helper headers.
* \~russian Подключает публичные заголовки вспомогательных TCP-клиента и сервера.
*/
/* /*
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, Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by it under the terms of the GNU Lesser General Public License as published by

View File

@@ -1,9 +1,8 @@
/*! \file picloudbase.h //! \~\file picloudbase.h
* \ingroup Cloud //! \~\ingroup Cloud
* \~\brief //! \brief
* \~english Shared transport state for PICloud endpoints //! \~english Base class for PICloudClient and PICloudServer.
* \~russian Общая транспортная часть для конечных точек PICloud //! \~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,10 +29,10 @@
#include "piethernet.h" #include "piethernet.h"
#include "pistreampacker.h" #include "pistreampacker.h"
//! \ingroup Cloud //! \~\ingroup Cloud
//! \~\brief //! \brief
//! \~english Shared transport helper for %PICloudClient and %PICloudServer. //! \~english Base class for cloud client and server.
//! \~russian Общий транспортный помощник для %PICloudClient и %PICloudServer. //! \~russian Базовый класс для облачного клиента и сервера.
class PIP_CLOUD_EXPORT PICloudBase { class PIP_CLOUD_EXPORT PICloudBase {
public: public:
//! \~english Constructs the shared PICloud transport state. //! \~english Constructs the shared PICloud transport state.

View File

@@ -1,9 +1,8 @@
/*! \file picloudclient.h //! \~\file picloudclient.h
* \ingroup Cloud //! \~\ingroup Cloud
* \~\brief //! \~\brief
* \~english Client-side PICloud device for one named server //! \~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,7 +28,7 @@
#include "picloudbase.h" #include "picloudbase.h"
#include "piconditionvar.h" #include "piconditionvar.h"
//! \ingroup Cloud //! \~\ingroup Cloud
//! \~\brief //! \~\brief
//! \~english %PIIODevice implementation for a logical PICloud client. //! \~english %PIIODevice implementation for a logical PICloud client.
//! \~russian Реализация %PIIODevice для логического клиента PICloud. //! \~russian Реализация %PIIODevice для логического клиента PICloud.
@@ -42,28 +41,32 @@ public:
//! \~english Constructs a client for transport endpoint "path" and mode "mode". //! \~english Constructs a client for transport endpoint "path" and mode "mode".
//! \~russian Создает клиент для транспортной точки "path" и режима "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. //! \~english Destroys the client and closes the underlying transport.
//! \~russian Уничтожает клиент и закрывает нижележащий транспорт. //! \~russian Уничтожает клиент и закрывает нижележащий транспорт.
virtual ~PICloudClient(); virtual ~PICloudClient();
//! \~english Sets the logical server name used during the PICloud handshake. //! \~english Sets the logical server name used during the PICloud handshake.
//! \~russian Устанавливает логическое имя сервера, используемое при рукопожатии PICloud. //! \~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. //! \~english Enables or disables automatic reconnect of the underlying TCP link.
//! \~russian Включает или выключает автоматическое переподключение нижележащего TCP-соединения. //! \~russian Включает или выключает автоматическое переподключение нижележащего TCP-соединения.
void setKeepConnection(bool on); void setKeepConnection(bool on);
//! \~english Returns whether the logical PICloud session is established. //! \~english Returns whether the logical PICloud session is established.
//! \~russian Возвращает, установлена ли логическая сессия PICloud. //! \~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(). //! \~english Returns the number of payload bytes buffered for \a read().
//! \~russian Возвращает количество байтов полезной нагрузки, буферизованных для \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. //! \~english Interrupts pending connection and read waits.
//! \~russian Прерывает ожидающие операции подключения и чтения. //! \~russian Прерывает ожидающие операции подключения и чтения.
void interrupt() override; void interrupt() override;
EVENT(connected);
EVENT(disconnected);
//! \events //! \events
//! \{ //! \{
@@ -71,10 +74,12 @@ public:
//! \fn void connected() //! \fn void connected()
//! \~english Raised after the logical PICloud session becomes ready. //! \~english Raised after the logical PICloud session becomes ready.
//! \~russian Вызывается после того, как логическая сессия PICloud готова к работе. //! \~russian Вызывается после того, как логическая сессия PICloud готова к работе.
EVENT(connected);
//! \fn void disconnected() //! \fn void disconnected()
//! \~english Raised when the logical PICloud session is closed. //! \~english Raised when the logical PICloud session is closed.
//! \~russian Вызывается при закрытии логической сессии PICloud. //! \~russian Вызывается при закрытии логической сессии PICloud.
EVENT(disconnected);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file picloudserver.h //! \~\file picloudserver.h
* \ingroup Cloud //! \~\ingroup Cloud
* \~\brief //! \~\brief
* \~english Server-side PICloud device for one named endpoint //! \~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,7 +28,7 @@
#include "picloudbase.h" #include "picloudbase.h"
#include "piconditionvar.h" #include "piconditionvar.h"
//! \ingroup Cloud //! \~\ingroup Cloud
//! \~\brief //! \~\brief
//! \~english %PIIODevice implementation for a logical PICloud server. //! \~english %PIIODevice implementation for a logical PICloud server.
//! \~russian Реализация %PIIODevice для логического сервера PICloud. //! \~russian Реализация %PIIODevice для логического сервера PICloud.
@@ -42,11 +41,13 @@ public:
//! \~english Constructs a logical server for transport endpoint "path" and mode "mode". //! \~english Constructs a logical server for transport endpoint "path" and mode "mode".
//! \~russian Создает логический сервер для транспортной точки "path" и режима "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. //! \~english Destroys the server and closes all logical clients.
//! \~russian Уничтожает сервер и закрывает всех логических клиентов. //! \~russian Уничтожает сервер и закрывает всех логических клиентов.
virtual ~PICloudServer(); virtual ~PICloudServer();
//! \ingroup Cloud
//! \~\ingroup Cloud
//! \~\brief //! \~\brief
//! \~english Per-client %PIIODevice exposed by %PICloudServer. //! \~english Per-client %PIIODevice exposed by %PICloudServer.
//! \~russian Клиентское %PIIODevice, предоставляемое %PICloudServer. //! \~russian Клиентское %PIIODevice, предоставляемое %PICloudServer.
@@ -61,6 +62,7 @@ public:
//! \~english Constructs a wrapper for logical client "id" owned by server "srv". //! \~english Constructs a wrapper for logical client "id" owned by server "srv".
//! \~russian Создает обертку для логического клиента "id", принадлежащего серверу "srv". //! \~russian Создает обертку для логического клиента "id", принадлежащего серверу "srv".
Client(PICloudServer * srv = nullptr, uint id = 0); Client(PICloudServer * srv = nullptr, uint id = 0);
//! \~english Destroys the client wrapper. //! \~english Destroys the client wrapper.
//! \~russian Уничтожает клиентскую обертку. //! \~russian Уничтожает клиентскую обертку.
virtual ~Client(); virtual ~Client();
@@ -92,7 +94,6 @@ public:
//! \~russian Возвращает снимок текущих подключенных логических клиентов. //! \~russian Возвращает снимок текущих подключенных логических клиентов.
PIVector<PICloudServer::Client *> clients() const; PIVector<PICloudServer::Client *> clients() const;
EVENT1(newConnection, PICloudServer::Client *, client);
//! \events //! \events
//! \{ //! \{
@@ -100,6 +101,7 @@ public:
//! \fn void newConnection(PICloudServer::Client * client) //! \fn void newConnection(PICloudServer::Client * client)
//! \~english Raised when a new logical client appears for this server name. //! \~english Raised when a new logical client appears for this server name.
//! \~russian Вызывается, когда для этого имени сервера появляется новый логический клиент. //! \~russian Вызывается, когда для этого имени сервера появляется новый логический клиент.
EVENT1(newConnection, PICloudServer::Client *, client);
//! \} //! \}

View File

@@ -1,9 +1,9 @@
/*! \file picloudtcp.h //! \~\file picloudtcp.h
* \ingroup Cloud //! \~\ingroup Cloud
* \~\brief //! \~\brief
* \~english Low-level TCP framing helpers for PICloud //! \~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
@@ -33,13 +33,13 @@
class PIStreamPacker; class PIStreamPacker;
//! \ingroup Cloud //! \~\ingroup Cloud
//! \~english Namespace for low-level PICloud transport helpers. //! \~english Namespace for low-level PICloud transport helpers.
//! \~russian Пространство имен для низкоуровневых транспортных помощников PICloud. //! \~russian Пространство имен для низкоуровневых транспортных помощников PICloud.
namespace PICloud { namespace PICloud {
//! \ingroup Cloud //! \~\ingroup Cloud
//! \~\brief //! \~\brief
//! \~english Builds and parses PICloud frames on top of %PIStreamPacker. //! \~english Builds and parses PICloud frames on top of %PIStreamPacker.
//! \~russian Формирует и разбирает кадры PICloud поверх %PIStreamPacker. //! \~russian Формирует и разбирает кадры PICloud поверх %PIStreamPacker.
@@ -48,77 +48,94 @@ public:
//! \~english Supported PICloud frame versions. //! \~english Supported PICloud frame versions.
//! \~russian Поддерживаемые версии кадров PICloud. //! \~russian Поддерживаемые версии кадров PICloud.
enum Version { enum Version {
Version_1 = 1, /** \~english First protocol version \~russian Первая версия протокола */ Version_1 = 1 /** \~english First protocol version \~russian Первая версия протокола */,
Version_2 = 2 /** \~english Current protocol version \~russian Текущая версия протокола */ Version_2 = 2 /** \~english Current protocol version \~russian Текущая версия протокола */
}; };
//! \~english Logical destination role of a PICloud frame. //! \~english Logical destination role of a PICloud frame.
//! \~russian Логическая роль получателя кадра PICloud. //! \~russian Логическая роль получателя кадра PICloud.
enum Role { enum Role {
InvalidRole = 0, /** \~english Invalid or unknown role \~russian Некорректная или неизвестная роль */ InvalidRole = 0 /** \~english Invalid or unknown role \~russian Некорректная или неизвестная роль */,
Server = 1, /** \~english Frame for a logical server \~russian Кадр для логического сервера */ Server = 1 /** \~english Frame for a logical server \~russian Кадр для логического сервера */,
Client = 2, /** \~english Frame for a logical client \~russian Кадр для логического клиента */ Client = 2 /** \~english Frame for a logical client \~russian Кадр для логического клиента */
}; };
//! \~english Kind of PICloud frame payload. //! \~english Kind of PICloud frame payload.
//! \~russian Вид полезной нагрузки кадра PICloud. //! \~russian Вид полезной нагрузки кадра PICloud.
enum Type { enum Type {
InvalidType = 0, /** \~english Invalid or unknown frame \~russian Некорректный или неизвестный кадр */ InvalidType = 0 /** \~english Invalid or unknown frame \~russian Некорректный или неизвестный кадр */,
Connect = 1, /** \~english Connect or registration frame \~russian Кадр подключения или регистрации */ Connect = 1 /** \~english Connect or registration frame \~russian Кадр подключения или регистрации */,
Disconnect = 2, /** \~english Disconnect notification frame \~russian Кадр уведомления об отключении */ Disconnect = 2 /** \~english Disconnect notification frame \~russian Кадр уведомления об отключении */,
Data = 3, /** \~english Payload data frame \~russian Кадр с полезными данными */ Data = 3 /** \~english Payload data frame \~russian Кадр с полезными данными */,
Ping = 4 /** \~english Keepalive frame \~russian Кадр поддержания соединения */ Ping = 4 /** \~english Keepalive frame \~russian Кадр поддержания соединения */
}; };
//! \~english Constructs a PICloud frame helper bound to packer "s". //! \~english Constructs a PICloud frame helper bound to packer "s".
//! \~russian Создает помощник кадров PICloud, связанный с упаковщиком "s". //! \~russian Создает помощник кадров PICloud, связанный с упаковщиком "s".
TCP(PIStreamPacker * s); TCP(PIStreamPacker * s);
//! \~english Sets the logical role written into outgoing frames. //! \~english Sets the logical role written into outgoing frames.
//! \~russian Устанавливает логическую роль, записываемую в исходящие кадры. //! \~russian Устанавливает логическую роль, записываемую в исходящие кадры.
void setRole(Role r); void setRole(Role r);
//! \~english Returns the logical role of this helper. //! \~english Returns the logical role of this helper.
//! \~russian Возвращает логическую роль этого помощника. //! \~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. //! \~english Sets the logical server name used by connect and keepalive frames.
//! \~russian Устанавливает логическое имя сервера, используемое кадрами подключения и поддержания соединения. //! \~russian Устанавливает логическое имя сервера, используемое кадрами подключения и поддержания соединения.
void setServerName(const PIString & server_name_); void setServerName(const PIString & server_name_);
//! \~english Returns the configured logical server name. //! \~english Returns the configured logical server name.
//! \~russian Возвращает настроенное логическое имя сервера. //! \~russian Возвращает настроенное логическое имя сервера.
PIString serverName() const; PIString serverName() const;
//! \~english Sends the initial connect frame for the current server name. //! \~english Sends the initial connect frame for the current server name.
//! \~russian Отправляет начальный кадр подключения для текущего имени сервера. //! \~russian Отправляет начальный кадр подключения для текущего имени сервера.
void sendStart(); void sendStart();
//! \~english Sends a connect frame for logical client "client_id". //! \~english Sends a connect frame for logical client "client_id".
//! \~russian Отправляет кадр подключения для логического клиента "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". //! \~english Sends a disconnect frame for logical client "client_id".
//! \~russian Отправляет кадр отключения для логического клиента "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. //! \~english Sends a payload frame for the current logical role.
//! \~russian Отправляет кадр с полезными данными для текущей логической роли. //! \~russian Отправляет кадр с полезными данными для текущей логической роли.
int sendData(const PIByteArray & data); int sendData(const PIByteArray & data);
//! \~english Sends a payload frame tagged with logical client "client_id". //! \~english Sends a payload frame tagged with logical client "client_id".
//! \~russian Отправляет кадр с полезными данными, помеченный логическим клиентом "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. //! \~english Sends a keepalive frame.
//! \~russian Отправляет кадр поддержания соединения. //! \~russian Отправляет кадр поддержания соединения.
void sendPing(); void sendPing();
//! \~english Parses frame header and returns its type and destination role. //! \~english Parses frame header and returns its type and destination role.
//! \~russian Разбирает заголовок кадра и возвращает его тип и роль получателя. //! \~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. //! \~english Returns whether current role uses direct payload parsing.
//! \~russian Возвращает, использует ли текущая роль прямой разбор полезной нагрузки. //! \~russian Возвращает, использует ли текущая роль прямой разбор полезной нагрузки.
bool canParseData(PIByteArray & ba); bool canParseData(PIByteArray & ba);
//! \~english Extracts logical client identifier and payload from a server-side data frame. //! \~english Extracts logical client identifier and payload from a server-side data frame.
//! \~russian Извлекает идентификатор логического клиента и полезную нагрузку из серверного кадра данных. //! \~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. //! \~english Validates and returns raw connect payload used for server identity exchange.
//! \~russian Проверяет и возвращает сырой payload подключения, используемый при обмене идентичностью сервера. //! \~russian Проверяет и возвращает сырой payload подключения, используемый при обмене идентичностью сервера.
PIByteArray parseConnect_d(PIByteArray & ba); PIByteArray parseConnect_d(PIByteArray & ba);
//! \~english Extracts logical client identifier from a connect frame. //! \~english Extracts logical client identifier from a connect frame.
//! \~russian Извлекает идентификатор логического клиента из кадра подключения. //! \~russian Извлекает идентификатор логического клиента из кадра подключения.
uint parseConnect(PIByteArray & ba); uint parseConnect(PIByteArray & ba);
//! \~english Extracts logical client identifier from a disconnect frame. //! \~english Extracts logical client identifier from a disconnect frame.
//! \~russian Извлекает идентификатор логического клиента из кадра отключения. //! \~russian Извлекает идентификатор логического клиента из кадра отключения.
uint parseDisconnect(PIByteArray & ba); uint parseDisconnect(PIByteArray & ba);

View File

@@ -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
@@ -34,8 +36,13 @@
class PIVariant; class PIVariant;
//! \~english Namespace contains runtime code model structures and registries. 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 {
@@ -43,13 +50,13 @@ namespace PICodeInfo {
//! \~russian Модификаторы типа. //! \~russian Модификаторы типа.
enum TypeFlag { enum TypeFlag {
NoFlag /** \~english No modifiers. \~russian Модификаторы отсутствуют. */, NoFlag /** \~english No modifiers. \~russian Модификаторы отсутствуют. */,
Const /** \~english \c const modifier. \~russian Модификатор \c const. */ = 0x01, Const = 0x01 /** \~english \c const modifier. \~russian Модификатор \c const. */,
Static /** \~english \c static modifier. \~russian Модификатор \c static. */ = 0x02, Static = 0x02 /** \~english \c static modifier. \~russian Модификатор \c static. */,
Mutable /** \~english \c mutable modifier. \~russian Модификатор \c mutable. */ = 0x04, Mutable = 0x04 /** \~english \c mutable modifier. \~russian Модификатор \c mutable. */,
Volatile /** \~english \c volatile modifier. \~russian Модификатор \c volatile. */ = 0x08, Volatile = 0x08 /** \~english \c volatile modifier. \~russian Модификатор \c volatile. */,
Inline /** \~english \c inline modifier. \~russian Модификатор \c inline. */ = 0x10, Inline = 0x10 /** \~english \c inline modifier. \~russian Модификатор \c inline. */,
Virtual /** \~english \c virtual modifier. \~russian Модификатор \c virtual. */ = 0x20, Virtual = 0x20 /** \~english \c virtual modifier. \~russian Модификатор \c virtual. */,
Extern /** \~english \c extern modifier. \~russian Модификатор \c extern. */ = 0x40 Extern = 0x40 /** \~english \c extern modifier. \~russian Модификатор \c extern. */
}; };
//! \~english Bitmask of type modifiers. //! \~english Bitmask of type modifiers.
@@ -320,79 +327,70 @@ private:
NO_COPY_CLASS(__Storage__) NO_COPY_CLASS(__Storage__)
}; };
class PIP_EXPORT class PIP_EXPORT __StorageAccess__ {
__StorageAccess__{public: public:
static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes(){return *(__Storage__::instance()->classesInfo); static const PIMap<PIConstChars, PICodeInfo::ClassInfo *> & classes() {
} // namespace PICodeInfo return *(__Storage__::instance()->classesInfo);
} // namespace PICodeInfo
static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() { static const PIMap<PIConstChars, PICodeInfo::EnumInfo *> & enums() { return *(__Storage__::instance()->enumsInfo); }
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);
} }
static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFunctions() { static const PIMap<PIConstChars, PICodeInfo::AccessTypeFunction> & accessTypeFunctions() {
return *(__Storage__::instance()->accessTypeFunctions); return *(__Storage__::instance()->accessTypeFunctions);
} }
static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() { static const PIMap<PIConstChars, PICodeInfo::AccessOffsetFunction> & accessOffsetFunctions() {
return *(__Storage__::instance()->accessOffsetFunctions); return *(__Storage__::instance()->accessOffsetFunctions);
} }
} };
;
//! \relatesalso PICodeInfo //! \relatesalso PICodeInfo
//! \~\brief //! \~english Macro for the global code model registries.
//! \~english Shortcut facade for the global code model registries. //! \~russian Макрос для доступа к глобальным реестрам модели кода.
//! \~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:
return __Storage__::instance() -> classesInfo; const PIMap<PIConstChars, PICodeInfo::ClassInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::classes()") {
} return __Storage__::instance()->classesInfo;
} }
; };
//! \~english Deprecated compatibility object for \a PICODEINFO::classes().
//! \~russian Устаревший объект совместимости для \a PICODEINFO::classes().
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:
return __Storage__::instance() -> enumsInfo; const PIMap<PIConstChars, PICodeInfo::EnumInfo *> * operator->() const DEPRECATEDM("use PICODEINFO::enums()") {
} return __Storage__::instance()->enumsInfo;
} }
; };
//! \~english Deprecated compatibility object for \a PICODEINFO::enums().
//! \~russian Устаревший объект совместимости для \a PICODEINFO::enums().
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;
} }
} };
;
//! \~english Deprecated compatibility object for \a PICODEINFO::accessValueFunctions().
//! \~russian Устаревший объект совместимости для \a PICODEINFO::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;
} }
} };
;
//! \~english Deprecated compatibility object for \a PICODEINFO::accessTypeFunctions().
//! \~russian Устаревший объект совместимости для \a PICODEINFO::accessTypeFunctions().
static AccessTypeFunctionInterface accessTypeFunctions; static AccessTypeFunctionInterface accessTypeFunctions;

View File

@@ -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,10 +36,14 @@ inline bool _isCChar(const PIString & c) {
return _isCChar(c[0]); return _isCChar(c[0]);
} }
//! \ingroup Code //! \~\ingroup Code
//! \~\brief //! \~\brief
//! \~english Parser of C/C++ declarations used by the code model tools. //! \~english Parser of C/C++ declarations used by the code model tools.
//! \~russian Разборщик объявлений C/C++, используемый инструментами модели кода. //! \~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. //! \~english Constructs a parser with built-in PIP macro presets.
@@ -50,11 +53,14 @@ public:
//! \~english Visibility of a parsed declaration inside the current scope. //! \~english Visibility of a parsed declaration inside the current scope.
//! \~russian Видимость разобранного объявления в текущей области. //! \~russian Видимость разобранного объявления в текущей области.
enum Visibility { enum Visibility {
Global /** \~english Global or namespace-level declaration. \~russian Глобальное объявление или объявление уровня пространства имен. */, Global /** \~english Global or namespace-level declaration. \~russian Глобальное объявление или объявление уровня пространства имен.
*/
,
Public /** \~english Public class member. \~russian Открытый член класса. */, Public /** \~english Public class member. \~russian Открытый член класса. */,
Protected /** \~english Protected class member. \~russian Защищенный член класса. */, Protected /** \~english Protected class member. \~russian Защищенный член класса. */,
Private /** \~english Private class member. \~russian Закрытый член класса. */ Private /** \~english Private class member. \~russian Закрытый член класса. */
}; };
//! \~english Parsed declaration attributes. //! \~english Parsed declaration attributes.
//! \~russian Атрибуты разобранного объявления. //! \~russian Атрибуты разобранного объявления.
enum Attribute { enum Attribute {
@@ -71,12 +77,15 @@ public:
//! \~english Bitmask of parsed declaration attributes. //! \~english Bitmask of parsed declaration attributes.
//! \~russian Битовая маска атрибутов разобранного объявления. //! \~russian Битовая маска атрибутов разобранного объявления.
typedef PIFlags<Attribute> Attributes; typedef PIFlags<Attribute> Attributes;
//! \~english Preprocessor define name and value. //! \~english Preprocessor define name and value.
//! \~russian Имя и значение макроса \c define. //! \~russian Имя и значение макроса \c define.
typedef PIPair<PIString, PIString> Define; typedef PIPair<PIString, PIString> Define;
//! \~english Typedef alias and target type. //! \~english Typedef alias and target type.
//! \~russian Псевдоним typedef и целевой тип. //! \~russian Псевдоним typedef и целевой тип.
typedef PIPair<PIString, PIString> Typedef; typedef PIPair<PIString, PIString> Typedef;
//! \~english Parsed metadata map. //! \~english Parsed metadata map.
//! \~russian Карта разобранных метаданных. //! \~russian Карта разобранных метаданных.
typedef PIMap<PIString, PIString> MetaMap; typedef PIMap<PIString, PIString> MetaMap;
@@ -89,15 +98,19 @@ public:
value = v; value = v;
args = a; args = a;
} }
//! \~english Expands the macro body with arguments from \a args_. //! \~english Expands the macro body with arguments from \a args_.
//! \~russian Разворачивает тело макроса с аргументами из \a args_. //! \~russian Разворачивает тело макроса с аргументами из \a args_.
PIString expand(PIString args_, bool * ok = 0) const; PIString expand(PIString args_, bool * ok = 0) const;
//! \~english Macro name. //! \~english Macro name.
//! \~russian Имя макроса. //! \~russian Имя макроса.
PIString name; PIString name;
//! \~english Macro replacement text. //! \~english Macro replacement text.
//! \~russian Текст замены макроса. //! \~russian Текст замены макроса.
PIString value; PIString value;
//! \~english Ordered list of macro argument names. //! \~english Ordered list of macro argument names.
//! \~russian Упорядоченный список имен аргументов макроса. //! \~russian Упорядоченный список имен аргументов макроса.
PIStringList args; PIStringList args;
@@ -113,39 +126,51 @@ public:
is_type_ptr = false; is_type_ptr = false;
attributes = NoAttributes; attributes = NoAttributes;
} }
//! \~english Returns whether the member is declared as a bitfield. //! \~english Returns whether the member is declared as a bitfield.
//! \~russian Возвращает, объявлен ли член как битовое поле. //! \~russian Возвращает, объявлен ли член как битовое поле.
bool isBitfield() const { return bits > 0; } bool isBitfield() const { return bits > 0; }
//! \~english Parsed metadata attached to the member. //! \~english Parsed metadata attached to the member.
//! \~russian Разобранные метаданные, привязанные к члену. //! \~russian Разобранные метаданные, привязанные к члену.
MetaMap meta; MetaMap meta;
//! \~english Member type or return type. //! \~english Member type or return type.
//! \~russian Тип члена или возвращаемый тип. //! \~russian Тип члена или возвращаемый тип.
PIString type; PIString type;
//! \~english Member name. //! \~english Member name.
//! \~russian Имя члена. //! \~russian Имя члена.
PIString name; PIString name;
//! \~english Full textual argument declarations. //! \~english Full textual argument declarations.
//! \~russian Полные текстовые объявления аргументов. //! \~russian Полные текстовые объявления аргументов.
PIStringList arguments_full; PIStringList arguments_full;
//! \~english Argument types only. //! \~english Argument types only.
//! \~russian Только типы аргументов. //! \~russian Только типы аргументов.
PIStringList arguments_type; PIStringList arguments_type;
//! \~english Parsed array dimensions. //! \~english Parsed array dimensions.
//! \~russian Разобранные размеры массива. //! \~russian Разобранные размеры массива.
PIStringList dims; PIStringList dims;
//! \~english Member visibility. //! \~english Member visibility.
//! \~russian Видимость члена. //! \~russian Видимость члена.
Visibility visibility; Visibility visibility;
//! \~english Member attributes. //! \~english Member attributes.
//! \~russian Атрибуты члена. //! \~russian Атрибуты члена.
Attributes attributes; Attributes attributes;
//! \~english Indicates that the parsed type is a pointer. //! \~english Indicates that the parsed type is a pointer.
//! \~russian Показывает, что разобранный тип является указателем. //! \~russian Показывает, что разобранный тип является указателем.
bool is_type_ptr; bool is_type_ptr;
//! \~english Parsed size in bytes when available. //! \~english Parsed size in bytes when available.
//! \~russian Разобранный размер в байтах, если он известен. //! \~russian Разобранный размер в байтах, если он известен.
int size; int size;
//! \~english Bit count for bitfields, or \c -1 otherwise. //! \~english Bit count for bitfields, or \c -1 otherwise.
//! \~russian Количество бит для битового поля или \c -1 в остальных случаях. //! \~russian Количество бит для битового поля или \c -1 в остальных случаях.
int bits; int bits;
@@ -160,39 +185,51 @@ public:
size = 0; size = 0;
parent_scope = 0; parent_scope = 0;
} }
//! \~english Parsed metadata attached to the entity. //! \~english Parsed metadata attached to the entity.
//! \~russian Разобранные метаданные, привязанные к сущности. //! \~russian Разобранные метаданные, привязанные к сущности.
MetaMap meta; MetaMap meta;
//! \~english Entity kind, for example \c class, \c struct or \c namespace. //! \~english Entity kind, for example \c class, \c struct or \c namespace.
//! \~russian Вид сущности, например \c class, \c struct или \c namespace. //! \~russian Вид сущности, например \c class, \c struct или \c namespace.
PIString type; PIString type;
//! \~english Entity name. //! \~english Entity name.
//! \~russian Имя сущности. //! \~russian Имя сущности.
PIString name; PIString name;
//! \~english Source file where the entity was parsed. //! \~english Source file where the entity was parsed.
//! \~russian Исходный файл, в котором была разобрана сущность. //! \~russian Исходный файл, в котором была разобрана сущность.
PIString file; PIString file;
//! \~english Entity visibility inside its parent scope. //! \~english Entity visibility inside its parent scope.
//! \~russian Видимость сущности внутри родительской области. //! \~russian Видимость сущности внутри родительской области.
Visibility visibility; Visibility visibility;
//! \~english Parsed size in bytes when available. //! \~english Parsed size in bytes when available.
//! \~russian Разобранный размер в байтах, если он известен. //! \~russian Разобранный размер в байтах, если он известен.
int size; int size;
//! \~english Indicates that the entity was declared without a name. //! \~english Indicates that the entity was declared without a name.
//! \~russian Показывает, что сущность объявлена без имени. //! \~russian Показывает, что сущность объявлена без имени.
bool is_anonymous; bool is_anonymous;
//! \~english Immediate containing entity, or \c nullptr for the root scope. //! \~english Immediate containing entity, or \c nullptr for the root scope.
//! \~russian Непосредственная содержащая сущность или \c nullptr для корневой области. //! \~russian Непосредственная содержащая сущность или \c nullptr для корневой области.
Entity * parent_scope; Entity * parent_scope;
//! \~english Direct base entities. //! \~english Direct base entities.
//! \~russian Непосредственные базовые сущности. //! \~russian Непосредственные базовые сущности.
PIVector<Entity *> parents; PIVector<Entity *> parents;
//! \~english Parsed member functions. //! \~english Parsed member functions.
//! \~russian Разобранные функции-члены. //! \~russian Разобранные функции-члены.
PIVector<Member> functions; PIVector<Member> functions;
//! \~english Parsed data members. //! \~english Parsed data members.
//! \~russian Разобранные поля данных. //! \~russian Разобранные поля данных.
PIVector<Member> members; PIVector<Member> members;
//! \~english Typedefs declared inside the entity. //! \~english Typedefs declared inside the entity.
//! \~russian Typedef-объявления внутри сущности. //! \~russian Typedef-объявления внутри сущности.
PIVector<Typedef> typedefs; PIVector<Typedef> typedefs;
@@ -206,12 +243,15 @@ public:
value = v; value = v;
meta = m; meta = m;
} }
//! \~english Parsed metadata attached to the enumerator. //! \~english Parsed metadata attached to the enumerator.
//! \~russian Разобранные метаданные, привязанные к элементу перечисления. //! \~russian Разобранные метаданные, привязанные к элементу перечисления.
MetaMap meta; MetaMap meta;
//! \~english Enumerator name. //! \~english Enumerator name.
//! \~russian Имя элемента перечисления. //! \~russian Имя элемента перечисления.
PIString name; PIString name;
//! \~english Enumerator value. //! \~english Enumerator value.
//! \~russian Значение элемента перечисления. //! \~russian Значение элемента перечисления.
int value; int value;
@@ -221,12 +261,15 @@ public:
//! \~russian Разобранное перечисление. //! \~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. //! \~english Parsed metadata attached to the enum.
//! \~russian Разобранные метаданные, привязанные к перечислению. //! \~russian Разобранные метаданные, привязанные к перечислению.
MetaMap meta; MetaMap meta;
//! \~english Enum name. //! \~english Enum name.
//! \~russian Имя перечисления. //! \~russian Имя перечисления.
PIString name; PIString name;
//! \~english Parsed enumerators. //! \~english Parsed enumerators.
//! \~russian Разобранные элементы перечисления. //! \~russian Разобранные элементы перечисления.
PIVector<EnumeratorInfo> members; PIVector<EnumeratorInfo> members;
@@ -235,54 +278,70 @@ public:
//! \~english Parses one source file and optionally follows its includes. //! \~english Parses one source file and optionally follows its includes.
//! \~russian Разбирает один исходный файл и при необходимости следует по его include-зависимостям. //! \~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. //! \~english Parses several source files into one parser state.
//! \~russian Разбирает несколько исходных файлов в одном состоянии разборщика. //! \~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. //! \~english Parses source text provided directly in memory.
//! \~russian Разбирает исходный текст, переданный напрямую из памяти. //! \~russian Разбирает исходный текст, переданный напрямую из памяти.
void parseFileContent(PIString fc); void parseFileContent(PIString fc);
//! \~english Adds a directory to the include search list. //! \~english Adds a directory to the include search list.
//! \~russian Добавляет каталог в список поиска include-файлов. //! \~russian Добавляет каталог в список поиска include-файлов.
void includeDirectory(const PIString & dir) { includes << dir; } void includeDirectory(const PIString & dir) { includes << dir; }
//! \~english Adds a custom preprocessor definition before parsing. //! \~english Adds a custom preprocessor definition before parsing.
//! \~russian Добавляет пользовательское препроцессорное определение перед разбором. //! \~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. //! \~english Returns whether an enum with \a name was parsed.
//! \~russian Возвращает, было ли разобрано перечисление с именем \a name. //! \~russian Возвращает, было ли разобрано перечисление с именем \a name.
bool isEnum(const PIString & name); bool isEnum(const PIString & name);
//! \~english Finds a parsed entity by its full name. //! \~english Finds a parsed entity by its full name.
//! \~russian Ищет разобранную сущность по ее полному имени. //! \~russian Ищет разобранную сущность по ее полному имени.
Entity * findEntityByName(const PIString & en); Entity * findEntityByName(const PIString & en);
//! \~english Returns the set of files already processed by the parser. //! \~english Returns the set of files already processed by the parser.
//! \~russian Возвращает набор файлов, уже обработанных разборщиком. //! \~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. //! \~english Returns the file detected as the main translation unit.
//! \~russian Возвращает файл, определенный как основной единицей трансляции. //! \~russian Возвращает файл, определенный как основной единицей трансляции.
PIString mainFile() const { return main_file; } PIString mainFile() const { return main_file; }
//! \~english Returns the synthetic global scope entity. //! \~english Returns the synthetic global scope entity.
//! \~russian Возвращает синтетическую сущность глобальной области. //! \~russian Возвращает синтетическую сущность глобальной области.
const PICodeParser::Entity * global() const { return &root_; } const PICodeParser::Entity * global() const { return &root_; }
//! \~english Returns the maximum number of macro substitution passes. //! \~english Returns the maximum number of macro substitution passes.
//! \~russian Возвращает максимальное число проходов подстановки макросов. //! \~russian Возвращает максимальное число проходов подстановки макросов.
int macrosSubstitutionMaxIterations() const { return macros_iter; } int macrosSubstitutionMaxIterations() const { return macros_iter; }
//! \~english Sets the maximum number of macro substitution passes. //! \~english Sets the maximum number of macro substitution passes.
//! \~russian Задает максимальное число проходов подстановки макросов. //! \~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. //! \~english Parsed \c define directives, including built-in and custom ones.
//! \~russian Разобранные директивы \c define, включая встроенные и пользовательские. //! \~russian Разобранные директивы \c define, включая встроенные и пользовательские.
PIVector<Define> defines, custom_defines; PIVector<Define> defines, custom_defines;
//! \~english Parsed function-like macros. //! \~english Parsed function-like macros.
//! \~russian Разобранные функциональные макросы. //! \~russian Разобранные функциональные макросы.
PIVector<Macro> macros; PIVector<Macro> macros;
//! \~english Parsed enums from the processed files. //! \~english Parsed enums from the processed files.
//! \~russian Разобранные перечисления из обработанных файлов. //! \~russian Разобранные перечисления из обработанных файлов.
PIVector<Enum> enums; PIVector<Enum> enums;
//! \~english Parsed top-level typedef declarations. //! \~english Parsed top-level typedef declarations.
//! \~russian Разобранные typedef-объявления верхнего уровня. //! \~russian Разобранные typedef-объявления верхнего уровня.
PIVector<Typedef> typedefs; PIVector<Typedef> typedefs;
//! \~english Parsed entities discovered in the processed files. //! \~english Parsed entities discovered in the processed files.
//! \~russian Разобранные сущности, найденные в обработанных файлах. //! \~russian Разобранные сущности, найденные в обработанных файлах.
PIVector<Entity *> entities; PIVector<Entity *> entities;

View File

@@ -1,13 +1,12 @@
/*! \file piconsolemodule.h //! \~\file piconsolemodule.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \~\brief
* \~english Umbrella include for common console screen headers //! \~english Console module headers
* \~russian Зонтичный заголовок для общих экранных заголовков консольного модуля //! \~russian Заголовочные файлы модуля консоли
* //! \~\details
* \~\details //! \~english This file includes all Console module headers providing keyboard input, screen management, and tile-based UI.
* \~english Includes the public keyboard listener and console screen headers. //! \~russian Этот файл включает все заголовочные файлы модуля консоли, обеспечивающие ввод с клавиатуры, управление экраном и UI на основе
* \~russian Подключает публичные заголовки слушателя клавиатуры и консольного экрана. //! тайлов.
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Module includes Module includes

View File

@@ -1,9 +1,8 @@
/*! \file pikbdlistener.h //! \~\file pikbdlistener.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \~\brief
* \~english Console keyboard and mouse 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
@@ -41,7 +40,7 @@
} }
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Console input listener for keyboard and mouse events. //! \~english Console input listener for keyboard and mouse events.
//! \~russian Слушатель консольного ввода для событий клавиатуры и мыши. //! \~russian Слушатель консольного ввода для событий клавиатуры и мыши.
@@ -54,49 +53,48 @@ public:
//! \~english Keyboard keys reported as non-character codes. //! \~english Keyboard keys reported as non-character codes.
//! \~russian Клавиши, передаваемые как несимвольные коды. //! \~russian Клавиши, передаваемые как несимвольные коды.
enum SpecialKey { enum SpecialKey {
Tab /** \~english Tab key \~russian Клавиша Tab */ = 0x09, Tab = 0x09 /** \~english Tab key \~russian Клавиша Tab */,
Return /** \~english Enter key \~russian Клавиша Enter */ = 0x0a, Return = 0x0a /** \~english Enter key \~russian Клавиша Enter */,
Esc /** \~english Escape key \~russian Клавиша Escape */ = 0x1b, Esc = 0x1b /** \~english Escape key \~russian Клавиша Escape */,
Space /** \~english Space key \~russian Клавиша пробела */ = 0x20, Space = 0x20 /** \~english Space key \~russian Клавиша пробела */,
Backspace /** \~english Backspace key \~russian Клавиша Backspace */ = 0x7f, Backspace = 0x7f /** \~english Backspace key \~russian Клавиша Backspace */,
UpArrow /** \~english Up arrow key \~russian Стрелка вверх */ = -1, UpArrow = -1 /** \~english Up arrow key \~russian Стрелка вверх */,
DownArrow /** \~english Down arrow key \~russian Стрелка вниз */ = -2, DownArrow = -2 /** \~english Down arrow key \~russian Стрелка вниз */,
RightArrow /** \~english Right arrow key \~russian Стрелка вправо */ = -3, RightArrow = -3 /** \~english Right arrow key \~russian Стрелка вправо */,
LeftArrow /** \~english Left arrow key \~russian Стрелка влево */ = -4, LeftArrow = -4 /** \~english Left arrow key \~russian Стрелка влево */,
Home /** \~english Home key \~russian Клавиша Home */ = -5, Home = -5 /** \~english Home key \~russian Клавиша Home */,
End /** \~english End key \~russian Клавиша End */ = -6, End = -6 /** \~english End key \~russian Клавиша End */,
PageUp /** \~english Page Up key \~russian Клавиша Page Up */ = -7, PageUp = -7 /** \~english Page Up key \~russian Клавиша Page Up */,
PageDown /** \~english Page Down key \~russian Клавиша Page Down */ = -8, PageDown = -8 /** \~english Page Down key \~russian Клавиша Page Down */,
Insert /** \~english Insert key \~russian Клавиша Insert */ = -9, Insert = -9 /** \~english Insert key \~russian Клавиша Insert */,
Delete /** \~english Delete key \~russian Клавиша Delete */ = -10, Delete = -10 /** \~english Delete key \~russian Клавиша Delete */,
F1 /** \~english F1 key \~russian Клавиша F1 */ = -11, F1 = -11 /** \~english F1 key \~russian Клавиша F1 */,
F2 /** \~english F2 key \~russian Клавиша F2 */ = -12, F2 = -12 /** \~english F2 key \~russian Клавиша F2 */,
F3 /** \~english F3 key \~russian Клавиша F3 */ = -13, F3 = -13 /** \~english F3 key \~russian Клавиша F3 */,
F4 /** \~english F4 key \~russian Клавиша F4 */ = -14, F4 = -14 /** \~english F4 key \~russian Клавиша F4 */,
F5 /** \~english F5 key \~russian Клавиша F5 */ = -15, F5 = -15 /** \~english F5 key \~russian Клавиша F5 */,
F6 /** \~english F6 key \~russian Клавиша F6 */ = -16, F6 = -16 /** \~english F6 key \~russian Клавиша F6 */,
F7 /** \~english F7 key \~russian Клавиша F7 */ = -17, F7 = -17 /** \~english F7 key \~russian Клавиша F7 */,
F8 /** \~english F8 key \~russian Клавиша F8 */ = -18, F8 = -18 /** \~english F8 key \~russian Клавиша F8 */,
F9 /** \~english F9 key \~russian Клавиша F9 */ = -19, F9 = -19 /** \~english F9 key \~russian Клавиша F9 */,
F10 /** \~english F10 key \~russian Клавиша F10 */ = -20, F10 = -20 /** \~english F10 key \~russian Клавиша F10 */,
F11 /** \~english F11 key \~russian Клавиша F11 */ = -21, F11 = -21 /** \~english F11 key \~russian Клавиша F11 */,
F12 /** \~english F12 key \~russian Клавиша F12 */ = -22 F12 = -22 /** \~english F12 key \~russian Клавиша F12 */
}; };
//! \~english Keyboard modifier bit flags. //! \~english Keyboard modifier bit flags.
//! \~russian Битовые флаги модификаторов клавиатуры. //! \~russian Битовые флаги модификаторов клавиатуры.
enum KeyModifier { enum KeyModifier {
Ctrl /** \~english Control key \~russian Клавиша Control */ = 0x1, Ctrl = 0x1 /** \~english Control key \~russian Клавиша Control */,
Shift /** \~english Shift key \~russian Клавиша Shift */ = 0x2, Shift = 0x2 /** \~english Shift key \~russian Клавиша Shift */,
Alt /** \~english Alt key \~russian Клавиша Alt */ = 0x4 Alt = 0x4 /** \~english Alt key \~russian Клавиша Alt */,
// Meta /** Meta (windows) key */ = 0x8 // Meta = 0x8 /** Meta (windows) key */
}; };
//! \~english Combination of \a KeyModifier flags. //! \~english Combination of \a KeyModifier flags.
//! \~russian Комбинация флагов \a KeyModifier. //! \~russian Комбинация флагов \a KeyModifier.
typedef PIFlags<KeyModifier> KeyModifiers; typedef PIFlags<KeyModifier> KeyModifiers;
//! \~\brief
//! \~english Information about one keyboard event. //! \~english Information about one keyboard event.
//! \~russian Информация об одном событии клавиатуры. //! \~russian Информация об одном событии клавиатуры.
struct PIP_EXPORT KeyEvent { struct PIP_EXPORT KeyEvent {
@@ -119,9 +117,9 @@ public:
//! \~english Mouse button bit flags. //! \~english Mouse button bit flags.
//! \~russian Битовые флаги кнопок мыши. //! \~russian Битовые флаги кнопок мыши.
enum MouseButton { enum MouseButton {
MouseLeft /** \~english Left button \~russian Левая кнопка */ = 0x01, MouseLeft = 0x01 /** \~english Left button \~russian Левая кнопка */,
MouseRight /** \~english Right button \~russian Правая кнопка */ = 0x02, MouseRight = 0x02 /** \~english Right button \~russian Правая кнопка */,
MouseMiddle /** \~english Middle button \~russian Средняя кнопка */ = 0x04 MouseMiddle = 0x04 /** \~english Middle button \~russian Средняя кнопка */
}; };
//! \~english Mouse action kind. //! \~english Mouse action kind.
@@ -138,7 +136,6 @@ public:
//! \~russian Комбинация нажатых флагов \a MouseButton. //! \~russian Комбинация нажатых флагов \a MouseButton.
typedef PIFlags<MouseButton> MouseButtons; typedef PIFlags<MouseButton> MouseButtons;
//! \~\brief
//! \~english Information about one mouse event. //! \~english Information about one mouse event.
//! \~russian Информация об одном событии мыши. //! \~russian Информация об одном событии мыши.
struct PIP_EXPORT MouseEvent { struct PIP_EXPORT MouseEvent {
@@ -172,7 +169,6 @@ public:
KeyModifiers modifiers; KeyModifiers modifiers;
}; };
//! \~\brief
//! \~english Information about one mouse wheel event. //! \~english Information about one mouse wheel event.
//! \~russian Информация об одном событии колеса мыши. //! \~russian Информация об одном событии колеса мыши.
struct PIP_EXPORT WheelEvent: public MouseEvent { struct PIP_EXPORT WheelEvent: public MouseEvent {
@@ -208,7 +204,7 @@ public:
//! \~english Sets the callback receiving both key event and user data. //! \~english Sets the callback receiving both key event and user data.
//! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные. //! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные.
void setSlot(KBFunc slot) { ret_func = slot; } void setSlot(KBFunc slot) { ret_func = std::move(slot); }
//! \~english Sets the callback that only receives the key event and ignores user data. //! \~english Sets the callback that only receives the key event and ignores user data.
//! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные. //! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные.
@@ -248,18 +244,6 @@ public:
//! \~russian Возвращает, включен ли сейчас низкоуровневый захват консольного ввода. //! \~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
//! \{ //! \{
@@ -267,14 +251,22 @@ public:
//! \fn void enableExitCapture(int key = 'Q') //! \fn void enableExitCapture(int key = 'Q')
//! \~english Enables capture of exit key \a key. //! \~english Enables capture of exit key \a key.
//! \~russian Включает перехват клавиши выхода \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()
//! \~english Disables exit key capture. //! \~english Disables exit key capture.
//! \~russian Выключает перехват клавиши выхода. //! \~russian Выключает перехват клавиши выхода.
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
//! \fn void setActive(bool yes = true) //! \fn void setActive(bool yes = true)
//! \~english Enables or disables low-level console input capture. //! \~english Enables or disables low-level console input capture.
//! \~russian Включает или выключает низкоуровневый захват консольного ввода. //! \~russian Включает или выключает низкоуровневый захват консольного ввода.
EVENT_HANDLER(void, setActive) { setActive(true); }
EVENT_HANDLER1(void, setActive, bool, yes);
//! \} //! \}
//! \events //! \events
@@ -283,26 +275,29 @@ public:
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data) //! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \~english Raised when a key event is decoded. \a data is the user data pointer. //! \~english Raised when a key event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие клавиши. \a data содержит указатель на пользовательские данные. //! \~russian Вызывается, когда декодировано событие клавиши. \a data содержит указатель на пользовательские данные.
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
//! \fn void mouseEvent(PIKbdListener::MouseEvent mouse, 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. //! \~english Raised when a mouse button or move event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие кнопки мыши или перемещения. \a data содержит указатель на пользовательские данные. //! \~russian Вызывается, когда декодировано событие кнопки мыши или перемещения. \a data содержит указатель на пользовательские данные.
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
//! \fn void wheelEvent(PIKbdListener::WheelEvent wheel, 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. //! \~english Raised when a mouse wheel event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие колеса мыши. \a data содержит указатель на пользовательские данные. //! \~russian Вызывается, когда декодировано событие колеса мыши. \a data содержит указатель на пользовательские данные.
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
//! \} //! \}
//! \~\brief
//! \~english Becomes \b true after the configured exit key is captured.
//! \~russian Становится \b true после перехвата настроенной клавиши выхода.
static bool exiting;
//! \~english Returns the listener instance currently registered by the console subsystem. //! \~english Returns the listener instance currently registered by the console subsystem.
//! \~russian Возвращает экземпляр слушателя, который сейчас зарегистрирован консольной подсистемой. //! \~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(); }
@@ -321,10 +316,10 @@ private:
}; };
enum VTType { enum VTType {
vt_none /** \~english No specific terminal type is selected. \~russian Конкретный тип терминала не выбран. */, vt_none,
vt_xterm = 0x1 /** \~english XTerm-compatible terminal sequences. \~russian Последовательности терминала, совместимого с XTerm. */, vt_xterm = 0x1,
vt_linux = 0x2 /** \~english Linux virtual console sequences. \~russian Последовательности виртуальной консоли Linux. */, vt_linux = 0x2,
vt_all = 0xFF /** \~english All supported terminal sequence families. \~russian Все поддерживаемые семейства последовательностей терминала. */ vt_all = 0xFF
}; };
static const EscSeq esc_seq[]; static const EscSeq esc_seq[];
@@ -345,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;
@@ -362,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;

View File

@@ -1,9 +1,8 @@
/*! \file piscreen.h //! \~\file piscreen.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \~\brief
* \~english Console screen manager and tile host //! \~english Console screen manager and tile host
* \~russian Менеджер консольного экрана и контейнер тайлов //! \~russian Менеджер консольного экрана и контейнер тайлов
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Console GUI Console GUI
@@ -31,7 +30,7 @@
#include "piscreentile.h" #include "piscreentile.h"
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Console screen manager with tile layout, drawing, and input routing. //! \~english Console screen manager with tile layout, drawing, and input routing.
//! \~russian Менеджер консольного экрана с раскладкой тайлов, отрисовкой и маршрутизацией ввода. //! \~russian Менеджер консольного экрана с раскладкой тайлов, отрисовкой и маршрутизацией ввода.
@@ -44,18 +43,27 @@ class PIP_CONSOLE_EXPORT PIScreen
public: public:
//! \~english Constructs a screen with an internal keyboard listener, optional callback, and auto-start mode. //! \~english Constructs a screen with an internal keyboard listener, optional callback, and auto-start mode.
//! \~russian Создает экран со встроенным слушателем клавиатуры, необязательным обратным вызовом и режимом автозапуска. //! \~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 Stops the drawing thread and destroys the listener. //! \~english Destroys PIScreen and cleans up resources.
//! \~russian Останавливает поток отрисовки и уничтожает слушатель. //! \~russian Уничтожает PIScreen и очищает ресурсы.
~PIScreen(); ~PIScreen();
//! \~english Enables exit key capture in the internal listener used by \a waitForFinish(). //! \~english Enables catching the exit key (default is 'Q') to stop the screen.
//! \~russian Включает перехват клавиши выхода во внутреннем слушателе, используемом методом \a waitForFinish(). //! \~russian Включает захват клавиши выхода (по умолчанию 'Q') для остановки экрана.
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); } void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
//! \~english Disables exit key capture in the internal keyboard listener. //! \~english Disables catching the exit key.
//! \~russian Выключает перехват клавиши выхода во внутреннем слушателе клавиатуры. //! \~russian Отключает захват клавиши выхода.
void disableExitCapture() { listener->disableExitCapture(); } void disableExitCapture() { listener->disableExitCapture(); }
//! \~english Returns whether exit key capture is enabled. //! \~english Returns whether exit key capture is enabled.
@@ -66,12 +74,12 @@ public:
//! \~russian Возвращает настроенную клавишу выхода. //! \~russian Возвращает настроенную клавишу выхода.
int exitKey() const { return listener->exitKey(); } int exitKey() const { return listener->exitKey(); }
//! \~english Returns the current console width in cells. //! \~english Returns the current console width in characters.
//! \~russian Возвращает текущую ширину консоли в ячейках. //! \~russian Возвращает текущую ширину консоли в символах.
int windowWidth() const { return console.width; } int windowWidth() const { return console.width; }
//! \~english Returns the current console height in cells. //! \~english Returns the current console height in characters.
//! \~russian Возвращает текущую высоту консоли в ячейках. //! \~russian Возвращает текущую высоту консоли в символах.
int windowHeight() const { return console.height; } int windowHeight() const { return console.height; }
//! \~english Returns whether mouse hit-testing and routing are enabled. //! \~english Returns whether mouse hit-testing and routing are enabled.
@@ -88,10 +96,14 @@ public:
//! \~english Searches the root tile subtree by object name. //! \~english Searches the root tile subtree by object name.
//! \~russian Ищет тайл по имени объекта в поддереве корневого тайла. //! \~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. //! \~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, чтобы убрать его. //! \~russian Задает диалоговый тайл, рисуемый поверх корневого дерева, центрируемый на экране и первым получающий фокус. Передайте \c
//! nullptr, чтобы убрать его.
void setDialogTile(PIScreenTile * t); void setDialogTile(PIScreenTile * t);
//! \~english Returns the currently active dialog tile or \c nullptr. //! \~english Returns the currently active dialog tile or \c nullptr.
@@ -110,14 +122,6 @@ public:
//! \~russian Изменяет размер внутренних консольных буферов, используемых в следующих кадрах. //! \~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
//! \{ //! \{
@@ -125,14 +129,19 @@ public:
//! \fn void waitForFinish() //! \fn void waitForFinish()
//! \~english Blocks until the captured exit key is pressed and then stops the screen. //! \~english Blocks until the captured exit key is pressed and then stops the screen.
//! \~russian Блокирует выполнение, пока не будет нажата перехватываемая клавиша выхода, затем останавливает экран. //! \~russian Блокирует выполнение, пока не будет нажата перехватываемая клавиша выхода, затем останавливает экран.
EVENT_HANDLER0(void, waitForFinish);
//! \fn void start(bool wait = false) //! \fn void start(bool wait = false)
//! \~english Starts the screen thread and optionally waits until the configured exit key is captured. //! \~english Starts the screen thread and optionally waits until the configured exit key is captured.
//! \~russian Запускает поток экрана и при необходимости ждет, пока не будет перехвачена настроенная клавиша выхода. //! \~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)
//! \~english Stops the screen thread, restores console state, and optionally clears the terminal. //! \~english Stops the screen thread, restores console state, and optionally clears the terminal.
//! \~russian Останавливает поток экрана, восстанавливает состояние консоли и при необходимости очищает терминал. //! \~russian Останавливает поток экрана, восстанавливает состояние консоли и при необходимости очищает терминал.
EVENT_HANDLER0(void, stop) { stop(false); }
EVENT_HANDLER1(void, stop, bool, clear);
//! \} //! \}
//! \events //! \events
@@ -140,11 +149,14 @@ public:
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data) //! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \~english Raised when a key was not consumed by focus navigation or the focused tile. \a data is the screen user data pointer. //! \~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 содержит пользовательский указатель экрана. //! \~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)
//! \~english Raised when a tile reports a custom event \a e. //! \~english Raised when a tile reports a custom event \a e.
//! \~russian Вызывается, когда тайл сообщает пользовательское событие \a e. //! \~russian Вызывается, когда тайл сообщает пользовательское событие \a e.
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
//! \} //! \}

View File

@@ -1,98 +0,0 @@
/*! \file piscreenconsole.h
* \ingroup Console
* \~\brief
* \~english Console-oriented tiles built on top of %PIScreen
* \~russian Консольно-ориентированные тайлы, построенные поверх %PIScreen
*/
/*
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"
//! \ingroup Console
//! \~\brief
//! \~english Reserved tile type for displaying named variables on a screen.
//! \~russian Зарезервированный тип тайла для отображения именованных переменных на экране.
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
public:
//! \~english Constructs a variable-view tile.
//! \~russian Создает тайл просмотра переменных.
TileVars(const PIString & n = PIString());
protected:
//! \~english One variable entry used by the tile layout.
//! \~russian Одна запись переменной, используемая раскладкой тайла.
struct PIP_CONSOLE_EXPORT Variable {
//! \~english Constructs an empty variable descriptor.
//! \~russian Создает пустой дескриптор переменной.
Variable() {
nx = ny = type = offset = bitFrom = bitCount = size = 0;
format = PIScreenTypes::CellFormat();
ptr = 0;
}
//! \~english Returns `true` when the descriptor is not bound to data.
//! \~russian Возвращает `true`, если дескриптор не привязан к данным.
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;
};
//! \ingroup Console
//! \~\brief
//! \~english Minimal base tile for console-oriented screen integrations.
//! \~russian Минимальный базовый тайл для консольно-ориентированных экранных интеграций.
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
public:
//! \~english Constructs a console-oriented screen integration tile.
//! \~russian Создает тайл консольно-ориентированной экранной интеграции.
PIScreenConsoleTile();
};
#endif // PISCREENCONSOLE_H

View File

@@ -1,9 +1,8 @@
/*! \file piscreendrawer.h //! \~\file piscreendrawer.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \~\brief
* \~english Drawing helpers for %PIScreen cell buffers //! \~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,10 +29,13 @@
#include "piscreentypes.h" #include "piscreentypes.h"
#include "pistring.h" #include "pistring.h"
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Helper that draws primitives and text into a %PIScreen cell buffer. //! \~english Helper that draws primitives and text into a %PIScreen cell buffer.
//! \~russian Вспомогательный класс для рисования примитивов и текста в буфере ячеек %PIScreen. //! \~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);
@@ -41,15 +43,18 @@ class PIP_CONSOLE_EXPORT PIScreenDrawer {
public: public:
//! \~english Predefined pseudographic and widget-state symbols. //! \~english Predefined pseudographic and widget-state symbols.
//! \~russian Предопределенные псевдографические символы и символы состояний виджетов. //! \~russian Предопределенные псевдографические символы и символы состояний виджетов.
//! \~\details
//! \~english Defines available characters for drawing ASCII art primitives.
//! \~russian Определяет доступные символы для рисования ASCII-арта примитивов.
enum ArtChar { enum ArtChar {
LineVertical = 1, /** \~english Vertical line symbol. \~russian Символ вертикальной линии. */ LineVertical = 1 /** \~english Vertical line symbol. \~russian Символ вертикальной линии. */,
LineHorizontal, /** \~english Horizontal line symbol. \~russian Символ горизонтальной линии. */ LineHorizontal /** \~english Horizontal line symbol. \~russian Символ горизонтальной линии. */,
Cross, /** \~english Line intersection symbol. \~russian Символ пересечения линий. */ Cross /** \~english Line intersection symbol. \~russian Символ пересечения линий. */,
CornerTopLeft, /** \~english Top-left frame corner. \~russian Левый верхний угол рамки. */ CornerTopLeft /** \~english Top-left frame corner. \~russian Левый верхний угол рамки. */,
CornerTopRight, /** \~english Top-right frame corner. \~russian Правый верхний угол рамки. */ CornerTopRight /** \~english Top-right frame corner. \~russian Правый верхний угол рамки. */,
CornerBottomLeft, /** \~english Bottom-left frame corner. \~russian Левый нижний угол рамки. */ CornerBottomLeft /** \~english Bottom-left frame corner. \~russian Левый нижний угол рамки. */,
CornerBottomRight, /** \~english Bottom-right frame corner. \~russian Правый нижний угол рамки. */ CornerBottomRight /** \~english Bottom-right frame corner. \~russian Правый нижний угол рамки. */,
Unchecked, /** \~english Unchecked box symbol. \~russian Символ неотмеченного флажка. */ Unchecked /** \~english Unchecked box symbol. \~russian Символ неотмеченного флажка. */,
Checked /** \~english Checked box symbol. \~russian Символ отмеченного флажка. */ Checked /** \~english Checked box symbol. \~russian Символ отмеченного флажка. */
}; };

View File

@@ -1,9 +1,8 @@
/*! \file piscreentile.h //! \~\file piscreentile.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \brief
* \~english Base tile for the console screen tree //! \~english Basic PIScreen tile
* \~russian Базовый тайл для дерева консольного экрана //! \~russian Базовый тайл для PIScreen
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Basic PIScreen tile Basic PIScreen tile
@@ -32,10 +31,13 @@
class PIScreenDrawer; class PIScreenDrawer;
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Base tile in the console screen tree. //! \~english Base tile in the console screen tree.
//! \~russian Базовый тайл в дереве консольного экрана. //! \~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);
@@ -185,12 +187,12 @@ protected:
//! \~russian Обрабатывает колесо мыши и возвращает \b true, если событие поглощено. //! \~russian Обрабатывает колесо мыши и возвращает \b true, если событие поглощено.
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; } virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
//! \~english Raises tile event \a e to the owning screen bridge. //! \~english Raises tile event
//! \~russian Передает событие тайла \a e владеющему экранному мосту. //! \~russian Вызывает событие тайла
void raiseEvent(PIScreenTypes::TileEvent e); void raiseEvent(PIScreenTypes::TileEvent e);
//! \~english Attaches the tile subtree to screen bridge \a s. //! \~english Sets screen reference
//! \~russian Подключает поддерево тайла к экранному мосту \a s. //! \~russian Устанавливает ссылку на экран
void setScreen(PIScreenTypes::PIScreenBase * s); void setScreen(PIScreenTypes::PIScreenBase * s);
//! \~english Deletes all owned child tiles. //! \~english Deletes all owned child tiles.
@@ -217,8 +219,8 @@ protected:
//! \~russian Родительский тайл или \c nullptr для корня и отсоединенных тайлов. //! \~russian Родительский тайл или \c nullptr для корня и отсоединенных тайлов.
PIScreenTile * parent; PIScreenTile * parent;
//! \~english Screen bridge receiving tile notifications. //! \~english Screen pointer, receiving tile notifications.
//! \~russian Экранный мост, принимающий уведомления от тайла. //! \~russian Ссылка на экран, принимающий уведомления от тайла.
PIScreenTypes::PIScreenBase * screen; PIScreenTypes::PIScreenBase * screen;
//! \~english Tile position and size in screen cells. //! \~english Tile position and size in screen cells.

View File

@@ -1,9 +1,11 @@
/*! \file piscreentiles.h //! \~\file piscreentiles.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \brief
* \~english Reusable widget 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,7 +32,7 @@
#include "piscreentile.h" #include "piscreentile.h"
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Simple text tile with per-row formatting. //! \~english Simple text tile with per-row formatting.
//! \~russian Простой текстовый тайл с форматированием по строкам. //! \~russian Простой текстовый тайл с форматированием по строкам.
@@ -70,7 +72,7 @@ protected:
class TileList; class TileList;
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Scroll bar tile used by list-like widgets. //! \~english Scroll bar tile used by list-like widgets.
//! \~russian Тайловая полоса прокрутки для списковых виджетов. //! \~russian Тайловая полоса прокрутки для списковых виджетов.
@@ -125,7 +127,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Scrollable list tile with optional row selection. //! \~english Scrollable list tile with optional row selection.
//! \~russian Прокручиваемый тайл списка с необязательным выбором строк. //! \~russian Прокручиваемый тайл списка с необязательным выбором строк.
@@ -136,15 +138,15 @@ public:
//! \~english Selection policy for list rows. //! \~english Selection policy for list rows.
//! \~russian Режим выбора строк списка. //! \~russian Режим выбора строк списка.
enum SelectionMode { enum SelectionMode {
NoSelection, /** \~english Rows are not selectable. \~russian Выбор строк отключен. */ NoSelection /** \~english Rows are not selectable. \~russian Выбор строк отключен. */,
SingleSelection, /** \~english At most one row can be selected. \~russian Можно выбрать не более одной строки. */ SingleSelection /** \~english At most one row can be selected. \~russian Можно выбрать не более одной строки. */,
MultiSelection /** \~english Multiple rows can be selected. \~russian Можно выбрать несколько строк. */ MultiSelection /** \~english Multiple rows can be selected. \~russian Можно выбрать несколько строк. */
}; };
//! \~english Events emitted by the list tile. //! \~english Events emitted by the list tile.
//! \~russian События, генерируемые тайлом списка. //! \~russian События, генерируемые тайлом списка.
enum EventType { enum EventType {
SelectionChanged, /** \~english Selection set changed. \~russian Изменился набор выбранных строк. */ SelectionChanged /** \~english Selection set changed. \~russian Изменился набор выбранных строк. */,
RowPressed /** \~english Current row was activated; event data stores the row index. \~russian Текущая строка была активирована; данные события содержат индекс строки. */ RowPressed /** \~english Current row was activated; event data stores the row index. \~russian Текущая строка была активирована; данные события содержат индекс строки. */
}; };
@@ -200,7 +202,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Push button tile. //! \~english Push button tile.
//! \~russian Тайл кнопки. //! \~russian Тайл кнопки.
@@ -238,7 +240,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Group of selectable buttons arranged in one tile. //! \~english Group of selectable buttons arranged in one tile.
//! \~russian Группа выбираемых кнопок, размещенных в одном тайле. //! \~russian Группа выбираемых кнопок, размещенных в одном тайле.
@@ -289,7 +291,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Check box tile. //! \~english Check box tile.
//! \~russian Тайл флажка. //! \~russian Тайл флажка.
@@ -331,7 +333,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Progress indicator tile. //! \~english Progress indicator tile.
//! \~russian Тайл индикатора прогресса. //! \~russian Тайл индикатора прогресса.
@@ -373,7 +375,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Log view tile backed by the global %PICout buffer. //! \~english Log view tile backed by the global %PICout buffer.
//! \~russian Тайл журнала, использующий глобальный буфер %PICout. //! \~russian Тайл журнала, использующий глобальный буфер %PICout.
@@ -403,7 +405,7 @@ protected:
}; };
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Single-line editable text input tile. //! \~english Single-line editable text input tile.
//! \~russian Однострочный тайл редактируемого текстового ввода. //! \~russian Однострочный тайл редактируемого текстового ввода.

View File

@@ -1,9 +1,11 @@
/*! \file piscreentypes.h //! \~\file piscreentypes.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \brief
* \~english Shared screen cell, layout, and tile event types //! \~english Types for PIScreen
* \~russian Общие типы экранных ячеек, компоновки и событий тайлов //! \~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
@@ -49,16 +51,17 @@ enum Color {
Magenta /** \~english Magenta \~russian Пурпурный */, Magenta /** \~english Magenta \~russian Пурпурный */,
Yellow /** \~english Yellow \~russian Желтый */, Yellow /** \~english Yellow \~russian Желтый */,
White /** \~english White \~russian Белый */, White /** \~english White \~russian Белый */,
Transparent /** \~english Preserve the background already stored in the target cell \~russian Сохранить фон, уже записанный в целевой ячейке */ Transparent /** \~english Preserve the background already stored in the target cell \~russian Сохранить фон, уже записанный в целевой
ячейке */
}; };
//! \~english Character formatting flags. //! \~english Character formatting flags.
//! \~russian Флаги оформления символа. //! \~russian Флаги оформления символа.
enum CharFlag { enum CharFlag {
Bold /** \~english Bold or bright text \~russian Жирный или яркий текст */ = 0x1, Bold = 0x1 /** \~english Bold or bright text \~russian Жирный или яркий текст */,
Blink /** \~english Blinking text \~russian Мигание текста */ = 0x2, Blink = 0x2 /** \~english Blinking text \~russian Мигание текста */,
Underline /** \~english Underlined text \~russian Подчеркнутый текст */ = 0x4, Underline = 0x4 /** \~english Underlined text \~russian Подчеркнутый текст */,
Inverse /** \~english Inverted foreground and background \~russian Инвертированные цвета текста и фона */ = 0x08 Inverse = 0x08 /** \~english Inverted foreground and background \~russian Инвертированные цвета текста и фона */
}; };
//! \~english Horizontal text alignment inside a tile. //! \~english Horizontal text alignment inside a tile.
@@ -73,9 +76,14 @@ enum Alignment {
//! \~russian Политика размера, используемая родительскими тайлами при компоновке. //! \~russian Политика размера, используемая родительскими тайлами при компоновке.
enum SizePolicy { enum SizePolicy {
Fixed /** \~english Keep the requested size \~russian Сохранять запрошенный размер */, Fixed /** \~english Keep the requested size \~russian Сохранять запрошенный размер */,
Preferred /** \~english Use preferred size first and share extra space after fixed tiles \~russian Сначала использовать предпочтительный размер и затем делить свободное место после фиксированных тайлов */, Preferred /** \~english Use preferred size first and share extra space after fixed tiles \~russian Сначала использовать предпочтительный
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 Не участвовать в автоматической компоновке; геометрию нужно задавать вручную */ ,
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 Не участвовать в автоматической компоновке;
геометрию нужно задавать вручную */
}; };
//! \~english Child layout direction. //! \~english Child layout direction.
@@ -88,14 +96,17 @@ enum Direction {
//! \~english Focus and navigation flags for tiles. //! \~english Focus and navigation flags for tiles.
//! \~russian Флаги фокуса и навигации для тайлов. //! \~russian Флаги фокуса и навигации для тайлов.
enum FocusFlag { enum FocusFlag {
CanHasFocus /** \~english Tile can receive focus \~russian Тайл может получать фокус */ = 0x1, CanHasFocus = 0x1 /** \~english Tile can receive focus \~russian Тайл может получать фокус */,
NextByTab /** \~english Tab moves focus to the next tile \~russian Клавиша Tab переводит фокус к следующему тайлу */ = 0x2, NextByTab = 0x2 /** \~english Tab moves focus to the next tile \~russian Клавиша Tab переводит фокус к следующему тайлу */,
NextByArrowsHorizontal /** \~english Left and right arrows move focus \~russian Стрелки влево и вправо переводят фокус */ = 0x4, NextByArrowsHorizontal = 0x4 /** \~english Left and right arrows move focus \~russian Стрелки влево и вправо переводят фокус */,
NextByArrowsVertical /** \~english Up and down arrows move focus \~russian Стрелки вверх и вниз переводят фокус */ = 0x8, NextByArrowsVertical = 0x8 /** \~english Up and down arrows move focus \~russian Стрелки вверх и вниз переводят фокус */,
NextByArrowsAll /** \~english Any arrow key moves focus \~russian Любая стрелка переводит фокус */ = NextByArrowsHorizontal | NextByArrowsVertical, NextByArrowsAll /** \~english Any arrow key moves focus \~russian Любая стрелка переводит фокус */ =
FocusOnMouse /** \~english Mouse press gives focus to the tile \~russian Нажатие мышью переводит фокус на тайл */ = 0x10, NextByArrowsHorizontal | NextByArrowsVertical,
FocusOnWheel /** \~english Mouse wheel gives focus to the tile \~russian Колесо мыши переводит фокус на тайл */ = 0x20, FocusOnMouse = 0x10 /** \~english Mouse press gives focus to the tile \~russian Нажатие мышью переводит фокус на тайл */,
FocusOnMouseOrWheel /** \~english Mouse press or wheel gives focus to the tile \~russian Нажатие мышью или колесо переводят фокус на тайл */ = 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. //! \~english Combination of \a CharFlag values.
@@ -136,7 +147,7 @@ union PIP_CONSOLE_EXPORT CellFormat {
//! \~english Combination of \a CharFlag values. //! \~english Combination of \a CharFlag values.
//! \~russian Комбинация значений \a CharFlag. //! \~russian Комбинация значений \a CharFlag.
ushort flags : 8; ushort flags: 8;
}; };
//! \~english Returns \b true when two formats are identical. //! \~english Returns \b true when two formats are identical.

View File

@@ -1,9 +1,8 @@
/*! \file piterminal.h //! \~\file piterminal.h
* \ingroup Console //! \~\ingroup Console
* \~\brief //! \brief
* \~english Virtual terminal backed by a shell process //! \~english Virtual terminal
* \~russian Виртуальный терминал, поддерживаемый процессом оболочки //! \~russian Виртуальный терминал
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Virtual terminal Virtual terminal
@@ -31,10 +30,15 @@
#include "piscreentypes.h" #include "piscreentypes.h"
//! \ingroup Console //! \~\ingroup Console
//! \~\brief //! \~\brief
//! \~english Virtual terminal that runs a shell and mirrors its screen into a cell buffer. //! \~english Virtual terminal that runs a shell and mirrors its screen into a cell buffer.
//! \~russian Виртуальный терминал, который запускает оболочку и отражает ее экран в буфер ячеек. //! \~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);

View File

@@ -1,7 +1,7 @@
//! \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 Базовые макросы для контейнеров
//! \~\authors //! \~\authors
@@ -49,35 +49,14 @@
#include <type_traits> #include <type_traits>
//! \ingroup Containers
//! \~\brief
//! \~english Reverse-iteration wrapper for range-based loops.
//! \~russian Обёртка для обратного обхода в range-based циклах.
template<typename C> template<typename C>
class _PIReverseWrapper { class _PIReverseWrapper {
public: public:
//! \~english Wraps container `c` for reverse iteration.
//! \~russian Оборачивает контейнер `c` для обратного обхода.
_PIReverseWrapper(C & c): c_(c) {} _PIReverseWrapper(C & c): c_(c) {}
//! \~english Wraps constant container `c` for reverse iteration.
//! \~russian Оборачивает константный контейнер `c` для обратного обхода.
_PIReverseWrapper(const C & c): c_(const_cast<C &>(c)) {} _PIReverseWrapper(const C & c): c_(const_cast<C &>(c)) {}
//! \~english Returns iterator to the first element in reverse order.
//! \~russian Возвращает итератор на первый элемент в обратном порядке.
typename C::reverse_iterator begin() { return c_.rbegin(); } typename C::reverse_iterator begin() { return c_.rbegin(); }
//! \~english Returns iterator following the last reversed element.
//! \~russian Возвращает итератор на элемент за последним при обратном обходе.
typename C::reverse_iterator end() { return c_.rend(); } typename C::reverse_iterator end() { return c_.rend(); }
//! \~english Returns constant iterator to the first element in reverse order.
//! \~russian Возвращает константный итератор на первый элемент в обратном порядке.
typename C::const_reverse_iterator begin() const { return c_.rbegin(); } typename C::const_reverse_iterator begin() const { return c_.rbegin(); }
//! \~english Returns constant iterator following the last reversed element.
//! \~russian Возвращает константный итератор на элемент за последним при обратном обходе.
typename C::const_reverse_iterator end() const { return c_.rend(); } typename C::const_reverse_iterator end() const { return c_.rend(); }
private: private:
@@ -85,55 +64,29 @@ private:
}; };
//! \ingroup Containers
//! \~\brief
//! \~english Common growth constants for generic containers.
//! \~russian Общие константы роста для универсальных контейнеров.
class PIP_EXPORT _PIContainerConstantsBase { class PIP_EXPORT _PIContainerConstantsBase {
public: public:
//! \~english Calculates minimum power-of-two capacity for element size `szof`.
//! \~russian Вычисляет минимальную ёмкость степени двойки для элемента размера `szof`.
static size_t calcMinCountPoT(size_t szof); static size_t calcMinCountPoT(size_t szof);
//! \~english Calculates the last capacity that still grows by powers of two.
//! \~russian Вычисляет последнюю ёмкость, которая ещё растёт степенями двойки.
static size_t calcMaxCountForPoT(size_t szof); static size_t calcMaxCountForPoT(size_t szof);
//! \~english Calculates linear growth step after power-of-two expansion.
//! \~russian Вычисляет линейный шаг роста после расширения степенями двойки.
static size_t calcStepAfterPoT(size_t szof); static size_t calcStepAfterPoT(size_t szof);
}; };
//! \ingroup Containers
//! \~\brief
//! \~english Type-specific container growth constants.
//! \~russian Константы роста контейнеров для заданного типа.
template<typename T> template<typename T>
class _PIContainerConstants { class _PIContainerConstants {
public: public:
//! \~english Returns the minimum power-of-two capacity for type `T`.
//! \~russian Возвращает минимальную ёмкость степени двойки для типа `T`.
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;
} }
//! \~english Returns the maximum capacity that still grows by powers of two for type `T`.
//! \~russian Возвращает максимальную ёмкость со степенным ростом для типа `T`.
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;
} }
//! \~english Returns the linear growth step used after power-of-two expansion for type `T`.
//! \~russian Возвращает линейный шаг роста после степенного расширения для типа `T`.
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;
} }
//! \~english Calculates capacity needed to fit `new_size` elements.
//! \~russian Вычисляет ёмкость, достаточную для размещения `new_size` элементов.
static size_t calcNewSize(size_t old_size, size_t new_size) { static size_t calcNewSize(size_t old_size, size_t new_size) {
if (new_size == 0) return 0; if (new_size == 0) return 0;
if (new_size < maxCountForPoT()) { if (new_size < maxCountForPoT()) {
@@ -156,16 +109,10 @@ 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);
} }
//! \~english Template reverse wrapper over constant container.
//! \~russian Шаблонная функция-обёртка константного контейнера для обратного доступа через итераторы.
template<typename C> template<typename C>
_PIReverseWrapper<C> PIReverseWrap(const C & c) { _PIReverseWrapper<C> PIReverseWrap(const C & c) {
return _PIReverseWrapper<C>(c); return _PIReverseWrapper<C>(c);

View File

@@ -167,8 +167,8 @@
//! Для неконстантных итераторов, возвращаемое значение унарного оператора `*` //! Для неконстантных итераторов, возвращаемое значение унарного оператора `*`
//! может быть использовано с левой стороны от оператора присваивания. //! может быть использовано с левой стороны от оператора присваивания.
//! //!
//! \file picontainersmodule.h //! \~\file picontainersmodule.h
//! \ingroup Containers //! \~\ingroup Containers
//! \~\brief //! \~\brief
//! \~english Umbrella header for the Containers module. //! \~english Umbrella header for the Containers module.
//! \~russian Общий заголовок модуля Containers. //! \~russian Общий заголовок модуля Containers.

View File

@@ -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
@@ -184,7 +184,7 @@ public:
//! \endcode //! \endcode
inline PIDeque(size_t piv_size, std::function<T(size_t i)> f) { inline PIDeque(size_t piv_size, std::function<T(size_t i)> f) {
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
expand(piv_size, f); expand(piv_size, std::move(f));
} }
//! \~english Move constructor. //! \~english Move constructor.
@@ -729,7 +729,7 @@ public:
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
//! \~\sa \a indexWhere() //! \~\sa \a indexWhere()
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const { inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
const ssize_t i = indexWhere(test, start); const ssize_t i = indexWhere(std::move(test), start);
if (i < 0) if (i < 0)
return def; return def;
else else
@@ -743,7 +743,7 @@ public:
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
//! \~\sa \a lastIndexWhere() //! \~\sa \a lastIndexWhere()
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const { inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
const ssize_t i = lastIndexWhere(test, start); const ssize_t i = lastIndexWhere(std::move(test), start);
if (i < 0) if (i < 0)
return def; return def;
else else
@@ -1265,7 +1265,7 @@ public:
deleteT(pid_data + pid_start + new_size, pid_size - new_size); deleteT(pid_data + pid_start + new_size, pid_size - new_size);
pid_size = new_size; pid_size = new_size;
} else if (new_size > pid_size) { } else if (new_size > pid_size) {
expand(new_size, f); expand(new_size, std::move(f));
} }
return *this; return *this;
} }
@@ -1328,15 +1328,15 @@ public:
if (index < pid_size - 1) { if (index < pid_size - 1) {
const size_t os = pid_size - index - 1; const size_t os = pid_size - index - 1;
memmove(reinterpret_cast<void *>(pid_data + pid_start + index + 1), memmove(reinterpret_cast<void *>(pid_data + pid_start + index + 1),
reinterpret_cast<const void *>(pid_data + pid_start + index), reinterpret_cast<const void *>(pid_data + pid_start + index),
os * sizeof(T)); os * sizeof(T));
} }
} else { } else {
alloc_backward(pid_size + 1, -1); alloc_backward(pid_size + 1, -1);
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start), memmove(reinterpret_cast<void *>(pid_data + pid_start),
reinterpret_cast<const void *>(pid_data + pid_start + 1), reinterpret_cast<const void *>(pid_data + pid_start + 1),
index * sizeof(T)); index * sizeof(T));
} }
} }
elementNew(pid_data + pid_start + index, e); elementNew(pid_data + pid_start + index, e);
@@ -1358,15 +1358,15 @@ public:
if (index < pid_size - 1) { if (index < pid_size - 1) {
const size_t os = pid_size - index - 1; const size_t os = pid_size - index - 1;
memmove(reinterpret_cast<void *>(pid_data + pid_start + index + 1), memmove(reinterpret_cast<void *>(pid_data + pid_start + index + 1),
reinterpret_cast<const void *>(pid_data + pid_start + index), reinterpret_cast<const void *>(pid_data + pid_start + index),
os * sizeof(T)); os * sizeof(T));
} }
} else { } else {
alloc_backward(pid_size + 1, -1); alloc_backward(pid_size + 1, -1);
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start), memmove(reinterpret_cast<void *>(pid_data + pid_start),
reinterpret_cast<const void *>(pid_data + pid_start + 1), reinterpret_cast<const void *>(pid_data + pid_start + 1),
index * sizeof(T)); index * sizeof(T));
} }
} }
elementNew(pid_data + pid_start + index, std::move(e)); elementNew(pid_data + pid_start + index, std::move(e));
@@ -1393,15 +1393,15 @@ public:
alloc_forward(pid_size + v.pid_size); alloc_forward(pid_size + v.pid_size);
if (os > 0) { if (os > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + index + v.pid_size), memmove(reinterpret_cast<void *>(pid_data + pid_start + index + v.pid_size),
reinterpret_cast<const void *>(pid_data + pid_start + index), reinterpret_cast<const void *>(pid_data + pid_start + index),
os * sizeof(T)); os * sizeof(T));
} }
} else { } else {
alloc_backward(pid_size + v.pid_size, -v.pid_size); alloc_backward(pid_size + v.pid_size, -v.pid_size);
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start), memmove(reinterpret_cast<void *>(pid_data + pid_start),
reinterpret_cast<const void *>(pid_data + pid_start + v.pid_size), reinterpret_cast<const void *>(pid_data + pid_start + v.pid_size),
index * sizeof(T)); index * sizeof(T));
} }
} }
newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size); newT(pid_data + pid_start + index, v.pid_data + v.pid_start, v.pid_size);
@@ -1426,15 +1426,15 @@ public:
alloc_forward(pid_size + init_list.size()); alloc_forward(pid_size + init_list.size());
if (os > 0) { if (os > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + index + init_list.size()), memmove(reinterpret_cast<void *>(pid_data + pid_start + index + init_list.size()),
reinterpret_cast<const void *>(pid_data + pid_start + index), reinterpret_cast<const void *>(pid_data + pid_start + index),
os * sizeof(T)); os * sizeof(T));
} }
} else { } else {
alloc_backward(pid_size + init_list.size(), -init_list.size()); alloc_backward(pid_size + init_list.size(), -init_list.size());
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start), memmove(reinterpret_cast<void *>(pid_data + pid_start),
reinterpret_cast<const void *>(pid_data + pid_start + init_list.size()), reinterpret_cast<const void *>(pid_data + pid_start + init_list.size()),
index * sizeof(T)); index * sizeof(T));
} }
} }
newT(pid_data + pid_start + index, init_list.begin(), init_list.size()); newT(pid_data + pid_start + index, init_list.begin(), init_list.size());
@@ -1462,13 +1462,13 @@ public:
deleteT(pid_data + pid_start + index, count); deleteT(pid_data + pid_start + index, count);
if (os <= index) { if (os <= index) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + index), memmove(reinterpret_cast<void *>(pid_data + pid_start + index),
reinterpret_cast<const void *>(pid_data + pid_start + index + count), reinterpret_cast<const void *>(pid_data + pid_start + index + count),
os * sizeof(T)); os * sizeof(T));
} else { } else {
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + count), memmove(reinterpret_cast<void *>(pid_data + pid_start + count),
reinterpret_cast<const void *>(pid_data + pid_start), reinterpret_cast<const void *>(pid_data + pid_start),
index * sizeof(T)); index * sizeof(T));
} }
pid_start += count; pid_start += count;
} }
@@ -1540,7 +1540,7 @@ public:
//! \endcode //! \endcode
//! \~\sa \a sort() //! \~\sa \a sort()
inline PIDeque<T> & sort(std::function<bool(const T & a, const T & b)> comp) { inline PIDeque<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
std::stable_sort(begin(), end(), comp); std::stable_sort(begin(), end(), std::move(comp));
return *this; return *this;
} }
@@ -1654,7 +1654,13 @@ public:
//! \endcode //! \endcode
//! \~\sa \a remove(), \a removeOne(), \a removeWhere() //! \~\sa \a remove(), \a removeOne(), \a removeWhere()
inline PIDeque<T> & removeWhere(std::function<bool(const T & e)> test) { inline PIDeque<T> & removeWhere(std::function<bool(const T & e)> test) {
ssize_t j = indexWhere(test); ssize_t j = -1;
for (size_t i = pid_start; i < pid_start + pid_size; ++i) {
if (test(pid_data[i])) {
j = ssize_t(i) - pid_start;
break;
}
}
if (j != -1) { if (j != -1) {
for (size_t i = j + 1; i < pid_size; ++i) { for (size_t i = j + 1; i < pid_size; ++i) {
if (!test(pid_data[i + pid_start])) { if (!test(pid_data[i + pid_start])) {
@@ -2545,21 +2551,21 @@ public:
if (index + count > pid_size) count = pid_size - index; if (index + count > pid_size) count = pid_size - index;
ret.alloc_forward(count); ret.alloc_forward(count);
memcpy(reinterpret_cast<void *>(ret.pid_data + ret.pid_start), memcpy(reinterpret_cast<void *>(ret.pid_data + ret.pid_start),
reinterpret_cast<const void *>(pid_data + pid_start + index), reinterpret_cast<const void *>(pid_data + pid_start + index),
count * sizeof(T)); count * sizeof(T));
const size_t os = pid_size - index - count; const size_t os = pid_size - index - count;
if (os <= index) { if (os <= index) {
if (os > 0) { if (os > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + index), memmove(reinterpret_cast<void *>(pid_data + pid_start + index),
reinterpret_cast<const void *>(pid_data + pid_start + index + count), reinterpret_cast<const void *>(pid_data + pid_start + index + count),
os * sizeof(T)); os * sizeof(T));
} }
} else { } else {
if (index > 0) { if (index > 0) {
memmove(reinterpret_cast<void *>(pid_data + pid_start + count), memmove(reinterpret_cast<void *>(pid_data + pid_start + count),
reinterpret_cast<const void *>(pid_data + pid_start), reinterpret_cast<const void *>(pid_data + pid_start),
index * sizeof(T)); index * sizeof(T));
} }
pid_start += count; pid_start += count;
} }
@@ -2646,8 +2652,8 @@ private:
size_t ns = (pid_rsize - pid_size) / 2; size_t ns = (pid_rsize - pid_size) / 2;
if (pid_start != ns) { if (pid_start != ns) {
memmove(reinterpret_cast<void *>(pid_data + ns), memmove(reinterpret_cast<void *>(pid_data + ns),
reinterpret_cast<const void *>(pid_data + pid_start), reinterpret_cast<const void *>(pid_data + pid_start),
pid_size * sizeof(T)); pid_size * sizeof(T));
pid_start = ns; pid_start = ns;
} }
} }
@@ -2656,8 +2662,8 @@ private:
const size_t ns = (pid_rsize - pid_size) / 2; const size_t ns = (pid_rsize - pid_size) / 2;
if (pid_start != ns) { if (pid_start != ns) {
memmove(reinterpret_cast<void *>(pid_data + ns), memmove(reinterpret_cast<void *>(pid_data + ns),
reinterpret_cast<const void *>(pid_data + pid_start), reinterpret_cast<const void *>(pid_data + pid_start),
pid_size * sizeof(T)); pid_size * sizeof(T));
pid_start = ns; pid_start = ns;
} }
} }
@@ -2694,8 +2700,8 @@ private:
PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize)) PIINTROSPECTION_CONTAINER_ALLOC(T, (as - pid_rsize))
if (pid_rsize > 0 && pid_data) { if (pid_rsize > 0 && pid_data) {
memcpy(reinterpret_cast<void *>(tmp_data + new_start), memcpy(reinterpret_cast<void *>(tmp_data + new_start),
reinterpret_cast<const void *>(pid_data + pid_start), reinterpret_cast<const void *>(pid_data + pid_start),
pid_size * sizeof(T)); pid_size * sizeof(T));
dealloc(); dealloc();
} }
pid_data = tmp_data; pid_data = tmp_data;

View File

@@ -1,6 +1,6 @@
//! \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

View File

@@ -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

View File

@@ -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

View File

@@ -1,6 +1,6 @@
//! \addtogroup Containers //! \addtogroup Containers
//! \{ //! \{
//! \file piset.h //! \~\file piset.h
//! \~\brief //! \~\brief
//! \~english Declares \a PISet //! \~english Declares \a PISet
//! \~russian Объявление \a PISet //! \~russian Объявление \a PISet
@@ -38,13 +38,24 @@
//! \~\} //! \~\}
//! \~\details //! \~\details
//! \~english //! \~english
//! Stores unique values of type `T` and exposes the set interface on top of \a PIMap. //! This class is used to store a collection of unique elements of any type.
//! Values can be inserted with \a operator<<(), checked with \a contains() or \a operator[](), //! You can add values to the set using \a operator<< or the \a insert() function.
//! and combined with \a unite(), \a subtract() and \a intersect(). //! 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 //! \~russian
//! Хранит уникальные значения типа `T` и реализует интерфейс множества поверх \a PIMap. //! Этот класс используется для хранения коллекции уникальных элементов любого типа.
//! Значения можно добавлять через \a operator<<(), проверять через \a contains() или \a operator[](), //! Вы можете добавлять значения в множество с помощью \a operator<< или функции \a insert().
//! а множества комбинировать через \a unite(), \a subtract() и \a intersect(). //! Вы можете проверить, существует ли значение в множестве, используя \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;

View File

@@ -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

View File

@@ -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
@@ -184,7 +184,7 @@ public:
//! \endcode //! \endcode
inline PIVector(size_t size, std::function<T(size_t i)> f) { inline PIVector(size_t size, std::function<T(size_t i)> f) {
PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T)) PIINTROSPECTION_CONTAINER_NEW(T, sizeof(T))
expand(size, f); expand(size, std::move(f));
} }
//! \~english Move constructor. //! \~english Move constructor.
@@ -725,7 +725,7 @@ public:
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
//! \~\sa \a indexWhere() //! \~\sa \a indexWhere()
inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const { inline const T & atWhere(std::function<bool(const T & e)> test, ssize_t start = 0, const T & def = T()) const {
const ssize_t i = indexWhere(test, start); const ssize_t i = indexWhere(std::move(test), start);
if (i < 0) if (i < 0)
return def; return def;
else else
@@ -739,7 +739,7 @@ public:
//! заданному в передаваемой функции `test`, или `def` если такого элемента нет. //! заданному в передаваемой функции `test`, или `def` если такого элемента нет.
//! \~\sa \a lastIndexWhere() //! \~\sa \a lastIndexWhere()
inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const { inline const T & lastAtWhere(std::function<bool(const T & e)> test, ssize_t start = -1, const T & def = T()) const {
const ssize_t i = lastIndexWhere(test, start); const ssize_t i = lastIndexWhere(std::move(test), start);
if (i < 0) if (i < 0)
return def; return def;
else else
@@ -1267,7 +1267,7 @@ public:
deleteT(piv_data + new_size, piv_size - new_size); deleteT(piv_data + new_size, piv_size - new_size);
piv_size = new_size; piv_size = new_size;
} else if (new_size > piv_size) { } else if (new_size > piv_size) {
expand(new_size, f); expand(new_size, std::move(f));
} }
return *this; return *this;
} }
@@ -1486,7 +1486,7 @@ public:
//! \endcode //! \endcode
//! \~\sa \a sort() //! \~\sa \a sort()
inline PIVector<T> & sort(std::function<bool(const T & a, const T & b)> comp) { inline PIVector<T> & sort(std::function<bool(const T & a, const T & b)> comp) {
std::stable_sort(begin(), end(), comp); std::stable_sort(begin(), end(), std::move(comp));
return *this; return *this;
} }
@@ -1599,7 +1599,13 @@ public:
//! \endcode //! \endcode
//! \~\sa \a remove(), \a removeOne(), \a removeWhere() //! \~\sa \a remove(), \a removeOne(), \a removeWhere()
inline PIVector<T> & removeWhere(std::function<bool(const T & e)> test) { inline PIVector<T> & removeWhere(std::function<bool(const T & e)> test) {
ssize_t j = indexWhere(test); ssize_t j = -1;
for (size_t i = 0; i < piv_size; ++i) {
if (test(piv_data[i])) {
j = i;
break;
}
}
if (j != -1) { if (j != -1) {
for (size_t i = j + 1; i < piv_size; ++i) { for (size_t i = j + 1; i < piv_size; ++i) {
if (!test(piv_data[i])) { if (!test(piv_data[i])) {

View File

@@ -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
@@ -1063,7 +1070,7 @@ public:
//! \~english Counts elements in the flat vector that pass the `test`. //! \~english Counts elements in the flat vector that pass the `test`.
//! \~russian Подсчитывает элементы в плоском векторе, проходящие `test`. //! \~russian Подсчитывает элементы в плоском векторе, проходящие `test`.
//! \~\sa PIVector::entries(std::function) //! \~\sa PIVector::entries(std::function)
inline int entries(std::function<bool(const T & e)> test) const { return mat.entries(test); } inline int entries(std::function<bool(const T & e)> test) const { return mat.entries(std::move(test)); }
//! \~english Returns the first index (row, col) of `e` in the 2D array. //! \~english Returns the first index (row, col) of `e` in the 2D array.
@@ -1079,7 +1086,7 @@ public:
//! \~russian Возвращает первый индекс (строка, столбец) в двумерном массиве, проходящий `test`. //! \~russian Возвращает первый индекс (строка, столбец) в двумерном массиве, проходящий `test`.
//! \~\sa PIVector::indexWhere() //! \~\sa PIVector::indexWhere()
inline Index indexWhere(std::function<bool(const T & e)> test, ssize_t start = 0) const { inline Index indexWhere(std::function<bool(const T & e)> test, ssize_t start = 0) const {
ssize_t flat = mat.indexWhere(test, start); ssize_t flat = mat.indexWhere(std::move(test), start);
if (flat < 0 || cols_ == 0) return Index{-1, -1}; if (flat < 0 || cols_ == 0) return Index{-1, -1};
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)}; return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
} }
@@ -1097,7 +1104,7 @@ public:
//! \~russian Возвращает последний индекс (строка, столбец) в двумерном массиве, проходящий `test`. //! \~russian Возвращает последний индекс (строка, столбец) в двумерном массиве, проходящий `test`.
//! \~\sa PIVector::lastIndexWhere() //! \~\sa PIVector::lastIndexWhere()
inline Index lastIndexWhere(std::function<bool(const T & e)> test, ssize_t start = -1) const { inline Index lastIndexWhere(std::function<bool(const T & e)> test, ssize_t start = -1) const {
ssize_t flat = mat.lastIndexWhere(test, start); ssize_t flat = mat.lastIndexWhere(std::move(test), start);
if (flat < 0 || cols_ == 0) return Index{-1, -1}; if (flat < 0 || cols_ == 0) return Index{-1, -1};
return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)}; return Index{flat / static_cast<ssize_t>(cols_), flat % static_cast<ssize_t>(cols_)};
} }
@@ -1106,12 +1113,12 @@ public:
//! \~english Tests if any element in the flat vector passes the `test`. //! \~english Tests if any element in the flat vector passes the `test`.
//! \~russian Проверяет, проходит ли какой-либо элемент в плоском векторе `test`. //! \~russian Проверяет, проходит ли какой-либо элемент в плоском векторе `test`.
//! \~\sa PIVector::any() //! \~\sa PIVector::any()
inline bool any(std::function<bool(const T & e)> test) const { return mat.any(test); } inline bool any(std::function<bool(const T & e)> test) const { return mat.any(std::move(test)); }
//! \~english Tests if all elements in the flat vector pass the `test`. //! \~english Tests if all elements in the flat vector pass the `test`.
//! \~russian Проверяет, проходят ли все элементы в плоском векторе `test`. //! \~russian Проверяет, проходят ли все элементы в плоском векторе `test`.
//! \~\sa PIVector::every() //! \~\sa PIVector::every()
inline bool every(std::function<bool(const T & e)> test) const { return mat.every(test); } inline bool every(std::function<bool(const T & e)> test) const { return mat.every(std::move(test)); }
//! \~english Fills the entire 2D array with copies of `e`. //! \~english Fills the entire 2D array with copies of `e`.
//! \~russian Заполняет весь двумерный массив копиями `e`. //! \~russian Заполняет весь двумерный массив копиями `e`.
@@ -1125,7 +1132,7 @@ public:
//! \~russian Заполняет весь двумерный массив, используя функцию-генератор `f` на основе плоского индекса. //! \~russian Заполняет весь двумерный массив, используя функцию-генератор `f` на основе плоского индекса.
//! \~\sa PIVector::fill(std::function) //! \~\sa PIVector::fill(std::function)
inline PIVector2D<T> & fill(std::function<T(size_t i)> f) { inline PIVector2D<T> & fill(std::function<T(size_t i)> f) {
mat.fill(f); mat.fill(std::move(f));
return *this; return *this;
} }
@@ -1221,7 +1228,7 @@ public:
//! \~\sa PIVector::map() //! \~\sa PIVector::map()
template<typename ST> template<typename ST>
inline PIVector2D<ST> map(std::function<ST(const T & e)> f) const { inline PIVector2D<ST> map(std::function<ST(const T & e)> f) const {
return PIVector2D<ST>(rows_, cols_, mat.template map<ST>(f)); return PIVector2D<ST>(rows_, cols_, mat.template map<ST>(std::move(f)));
} }
//! \~english Applies a function (with row and col indices) to each element and returns a new 2D array. //! \~english Applies a function (with row and col indices) to each element and returns a new 2D array.
@@ -1243,23 +1250,26 @@ public:
//! \~russian Применяет функцию к каждой строке (с возможностью изменения). //! \~russian Применяет функцию к каждой строке (с возможностью изменения).
//! \~\sa forEachRow() const, PIVector::forEach() //! \~\sa forEachRow() const, PIVector::forEach()
inline PIVector2D<T> & forEachRow(std::function<void(Row)> f) { inline PIVector2D<T> & forEachRow(std::function<void(Row)> f) {
for (size_t r = 0; r < rows_; ++r) for (size_t r = 0; r < rows_; ++r) {
f(row(r)); f(row(r));
}
return *this; return *this;
} }
//! \~english Applies a function to each row (read-only). //! \~english Applies a function to each row (read-only).
//! \~russian Применяет функцию к каждой строке (только чтение). //! \~russian Применяет функцию к каждой строке (только чтение).
inline void forEachRow(std::function<void(RowConst)> f) const { inline void forEachRow(std::function<void(RowConst)> f) const {
for (size_t r = 0; r < rows_; ++r) for (size_t r = 0; r < rows_; ++r) {
f(row(r)); f(row(r));
}
} }
//! \~english Applies a function to each column (modifiable). //! \~english Applies a function to each column (modifiable).
//! \~russian Применяет функцию к каждому столбцу (с возможностью изменения). //! \~russian Применяет функцию к каждому столбцу (с возможностью изменения).
inline PIVector2D<T> & forEachColumn(std::function<void(Col)> f) { inline PIVector2D<T> & forEachColumn(std::function<void(Col)> f) {
for (size_t c = 0; c < cols_; ++c) for (size_t c = 0; c < cols_; ++c) {
f(col(c)); f(col(c));
}
return *this; return *this;
} }
@@ -1267,8 +1277,9 @@ public:
//! \~russian Применяет функцию к каждому столбцу (только чтение). //! \~russian Применяет функцию к каждому столбцу (только чтение).
//! \param f Function taking a \a ColConst. //! \param f Function taking a \a ColConst.
inline void forEachColumn(std::function<void(ColConst)> f) const { inline void forEachColumn(std::function<void(ColConst)> f) const {
for (size_t c = 0; c < cols_; ++c) for (size_t c = 0; c < cols_; ++c) {
f(col(c)); f(col(c));
}
} }
//! \~english Accumulates a value across all elements. //! \~english Accumulates a value across all elements.
@@ -1276,7 +1287,7 @@ public:
//! \~\sa PIVector::reduce() //! \~\sa PIVector::reduce()
template<typename ST> template<typename ST>
inline ST reduce(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const { inline ST reduce(std::function<ST(const T & e, const ST & acc)> f, const ST & initial = ST()) const {
return mat.template reduce<ST>(f, initial); return mat.template reduce<ST>(std::move(f), initial);
} }
//! \~english Accumulates a value across all elements with indices. //! \~english Accumulates a value across all elements with indices.

View File

@@ -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));
@@ -684,11 +726,12 @@ inline bool piDeleteSafety(T *& pointer) {
//! \~english In this example "Error!" will be printed on every \b false function return. //! \~english In this example "Error!" will be printed on every \b false function return.
//! \~russian В данном примере будет выведен "Error!" при каждом \b false возврате из функции. //! \~russian В данном примере будет выведен "Error!" при каждом \b false возврате из функции.
class PIP_EXPORT PIScopeExitCall { class PIP_EXPORT PIScopeExitCall {
NO_COPY_CLASS(PIScopeExitCall)
public: public:
//! \~\brief //! \~\brief
//! \~english Constructor that takes a function to execute //! \~english Constructor that takes a function to execute
//! \~russian Конструктор, который принимает функцию для выполнения //! \~russian Конструктор, который принимает функцию для выполнения
explicit PIScopeExitCall(std::function<void()> f): func(f) {} explicit PIScopeExitCall(std::function<void()> f): func(std::move(f)) {}
//! \~\brief //! \~\brief
//! \~english Destructor that executes the function if it exists //! \~english Destructor that executes the function if it exists
@@ -716,8 +759,6 @@ public:
} }
private: private:
NO_COPY_CLASS(PIScopeExitCall)
std::function<void()> func; std::function<void()> func;
}; };
@@ -726,26 +767,40 @@ private:
//! \~english Inherit from this class to make your class non-trivially copyable. //! \~english Inherit from this class to make your class non-trivially copyable.
//! \~russian Наследуйтесь от этого класса чтобы сделать свой класс нетривиально копируемым. //! \~russian Наследуйтесь от этого класса чтобы сделать свой класс нетривиально копируемым.
struct PIP_EXPORT PINonTriviallyCopyable { struct PIP_EXPORT PINonTriviallyCopyable {
PINonTriviallyCopyable() noexcept = default; PINonTriviallyCopyable() = default;
PINonTriviallyCopyable(const PINonTriviallyCopyable &) noexcept = default; PINonTriviallyCopyable(const PINonTriviallyCopyable &) = default;
PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept; PINonTriviallyCopyable(PINonTriviallyCopyable &&) ;
PINonTriviallyCopyable & operator=(const PINonTriviallyCopyable &) noexcept = default; PINonTriviallyCopyable & operator=(const PINonTriviallyCopyable &) = default;
PINonTriviallyCopyable & operator=(PINonTriviallyCopyable &&) noexcept = default; PINonTriviallyCopyable & operator=(PINonTriviallyCopyable &&) = default;
~PINonTriviallyCopyable() = default; ~PINonTriviallyCopyable() = default;
}; };
inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) noexcept = default; inline PINonTriviallyCopyable::PINonTriviallyCopyable(PINonTriviallyCopyable &&) = 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;

View File

@@ -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
@@ -50,147 +52,118 @@
#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 +293,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 +308,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 +337,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 +390,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 +405,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();

View File

@@ -1,9 +1,13 @@
/*! \file picollection.h //! \addtogroup Core
* \ingroup Core //! \{
* \~\brief //! \~\file picollection.h
* \~english Named collection of unique object classes //! \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
@@ -36,11 +40,14 @@
//! \~russian Добавляет существующий объект в группу "group". //! \~russian Добавляет существующий объект в группу "group".
//! \~\details //! \~\details
//! \~english //! \~english
//! Group is created automatically when needed. Only one object of the same //! If this is no group with name "group" it will be created.
//! runtime class can be stored in one group. //! Only one element of the class "object" can be in group. If
//! this is already exists nothing be happens. \n "object" should to
//! be pointer to object based on \a PIObject.
//! \~russian //! \~russian
//! Группа создается автоматически при необходимости. В одной группе может //! Если такой группы нет, она создается. В каждой группе может присутствовать
//! храниться только один объект одного и того же класса времени выполнения. //! только один элемент класса объекта "object". Если такой элемент уже есть,
//! то ничего не изменится. \n "object" должен быть наследником \a PIObject.
# define ADD_TO_COLLECTION(group, object) # define ADD_TO_COLLECTION(group, object)
//! \relatesalso PICollection //! \relatesalso PICollection
@@ -60,11 +67,14 @@
//! \~russian Создает и добавляет новый объект класса "class" в группу "group". //! \~russian Создает и добавляет новый объект класса "class" в группу "group".
//! \~\details //! \~\details
//! \~english //! \~english
//! Group is created automatically when needed. Only one object of the same //! If this is no group with name "group" it will be created.
//! runtime class can be stored in one group. //! Only one element of the class "class" can be in group. If
//! this is already exists nothing be happens. \n "class" should to
//! be name of the any class based on PIObject.
//! \~russian //! \~russian
//! Группа создается автоматически при необходимости. В одной группе может //! Если такой группы нет, она создается. В каждой группе может присутствовать
//! храниться только один объект одного и того же класса времени выполнения. //! только один элемент класса "class". Если такой элемент уже есть,
//! то ничего не изменится. \n "class" должен быть любым классом, наследным от \a PIObject.
# define ADD_NEW_TO_COLLECTION(group, class) # define ADD_NEW_TO_COLLECTION(group, class)
//! \relatesalso PICollection //! \relatesalso PICollection
@@ -96,7 +106,7 @@
#endif #endif
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Global collection of %PIObject-based instances grouped by name. //! \~english Global collection of %PIObject-based instances grouped by name.
//! \~russian Глобальная коллекция экземпляров на базе %PIObject, сгруппированных по имени. //! \~russian Глобальная коллекция экземпляров на базе %PIObject, сгруппированных по имени.
@@ -122,7 +132,7 @@ public:
//! того же класса времени выполнения. //! того же класса времени выполнения.
static bool addToGroup(const PIString & group, const PIObject * element); static bool addToGroup(const PIString & group, const PIObject * element);
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Helper that registers object in collection during static initialization. //! \~english Helper that registers object in collection during static initialization.
//! \~russian Вспомогательный класс, регистрирующий объект в коллекции при статической инициализации. //! \~russian Вспомогательный класс, регистрирующий объект в коллекции при статической инициализации.

View File

@@ -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
@@ -50,13 +51,13 @@
#else #else
# define piCout PICout(piDebug, PICoutStdStream::StdOut) # define piCout PICout(piDebug, PICoutStdStream::StdOut)
# define piCoutObj \ # define piCoutObj \
PICout(piDebug && debug(), PICoutStdStream::StdOut) \ PICout(piDebug && debug(), PICoutStdStream::StdOut) \
<< (PIStringAscii("[") + className() + (name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]"))) << (PIStringAscii("[") + className() + (name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]")))
# define piCerr PICout(piDebug, PICoutStdStream::StdErr) # define piCerr PICout(piDebug, PICoutStdStream::StdErr)
# define piCerrObj \ # define piCerrObj \
PICout(piDebug && debug(), PICoutStdStream::StdErr) \ PICout(piDebug && debug(), PICoutStdStream::StdErr) \
<< (PIStringAscii("[") + className() + (name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]"))) << (PIStringAscii("[") + className() + (name().isEmpty() ? "]" : PIStringAscii(" \"") + name() + PIStringAscii("\"]")))
#endif #endif
@@ -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,14 +464,22 @@ 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);
//! \~english Returns unique external buffer ID for later use in \a withExternalBufferAndID() //! \~english Returns unique external buffer ID for later use in \a withExternalBufferAndID()
//! \~russian Возвращает уникальный ID для внешнего буфера для дальнейшего использования в \a withExternalBufferAndID() //! \~russian Возвращает уникальный ID для внешнего буфера для дальнейшего использования в \a withExternalBufferAndID()

View File

@@ -50,13 +50,13 @@ class PIWaitEvent;
struct lconv; struct lconv;
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Pointer to current C locale numeric settings //! \~english Pointer to current C locale numeric settings
//! \~russian Указатель на текущие числовые настройки C locale //! \~russian Указатель на текущие числовые настройки C locale
extern PIP_EXPORT lconv * currentLocale; extern PIP_EXPORT lconv * currentLocale;
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Returns readable description of the last system error in format //! \~english Returns readable description of the last system error in format
//! "code <number> - <description>" //! "code <number> - <description>"
@@ -64,25 +64,25 @@ extern PIP_EXPORT lconv * currentLocale;
//! "code <номер> - <описание>" //! "code <номер> - <описание>"
PIP_EXPORT PIString errorString(); PIP_EXPORT PIString errorString();
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Clears the last system error //! \~english Clears the last system error
//! \~russian Сбрасывает последнюю системную ошибку //! \~russian Сбрасывает последнюю системную ошибку
PIP_EXPORT void errorClear(); PIP_EXPORT void errorClear();
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Seeds the global pseudo-random generator //! \~english Seeds the global pseudo-random generator
//! \~russian Инициализирует глобальный генератор псевдослучайных чисел //! \~russian Инициализирует глобальный генератор псевдослучайных чисел
PIP_EXPORT void randomize(); PIP_EXPORT void randomize();
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Returns next value from the global pseudo-random generator //! \~english Returns next value from the global pseudo-random generator
//! \~russian Возвращает следующее значение глобального генератора псевдослучайных чисел //! \~russian Возвращает следующее значение глобального генератора псевдослучайных чисел
PIP_EXPORT int randomi(); PIP_EXPORT int randomi();
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Returns readable PIP version string //! \~english Returns readable PIP version string
//! \~russian Возвращает строку версии PIP //! \~russian Возвращает строку версии PIP

View File

@@ -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,36 +39,17 @@
class PIFile; class PIFile;
class PIStringList; class PIStringList;
//! \ingroup Core
//! \~\brief
//! \~english Internal helper that owns the global %PIInit instance.
//! \~russian Внутренний помощник, владеющий глобальным экземпляром %PIInit.
class PIP_EXPORT __PIInit_Initializer__ { class PIP_EXPORT __PIInit_Initializer__ {
public: public:
//! \~english Creates %PIInit on the first initializer instance.
//! \~russian Создает %PIInit при создании первого экземпляра инициализатора.
__PIInit_Initializer__(); __PIInit_Initializer__();
//! \~english Destroys %PIInit after the last initializer instance.
//! \~russian Уничтожает %PIInit после удаления последнего экземпляра инициализатора.
~__PIInit_Initializer__(); ~__PIInit_Initializer__();
//! \~english Number of active initializer instances.
//! \~russian Количество активных экземпляров инициализатора.
static int count_; static int count_;
//! \~english Current global %PIInit instance.
//! \~russian Текущий глобальный экземпляр %PIInit.
static PIInit * __instance__; static PIInit * __instance__;
}; };
//! \ingroup Core
//! \~\brief
//! \~english Translation unit helper that keeps %PIInit initialized.
//! \~russian Вспомогательный объект единицы трансляции, поддерживающий инициализацию %PIInit.
static __PIInit_Initializer__ __piinit_initializer__; static __PIInit_Initializer__ __piinit_initializer__;
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Library initialization singleton and build information access point. //! \~english Library initialization singleton and build information access point.
//! \~russian Синглтон инициализации библиотеки и точка доступа к сведениям о сборке. //! \~russian Синглтон инициализации библиотеки и точка доступа к сведениям о сборке.
@@ -74,11 +58,9 @@ class PIP_EXPORT PIInit {
friend class PIFile; friend class PIFile;
public: public:
//! \~english Finalizes library-wide initialization resources.
//! \~russian Освобождает ресурсы глобальной инициализации библиотеки.
~PIInit(); ~PIInit();
//! \ingroup Core //! \~\ingroup Core
//! \~english Build options enabled in the current PIP library //! \~english Build options enabled in the current PIP library
//! \~russian Опции, включенные в текущей сборке библиотеки PIP //! \~russian Опции, включенные в текущей сборке библиотеки PIP
enum BuildOption { enum BuildOption {
@@ -97,12 +79,12 @@ public:
//! \~russian Возвращает текущий глобальный экземпляр %PIInit. //! \~russian Возвращает текущий глобальный экземпляр %PIInit.
static PIInit * instance() { return __PIInit_Initializer__::__instance__; } static PIInit * instance() { return __PIInit_Initializer__::__instance__; }
//! \ingroup Core //! \~\ingroup Core
//! \~english Returns whether 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 enabled build options as string list //! \~english Returns enabled build options as string list
//! \~russian Возвращает включенные опции сборки в виде списка строк //! \~russian Возвращает включенные опции сборки в виде списка строк
static PIStringList buildOptions(); static PIStringList buildOptions();

View File

@@ -1,9 +1,15 @@
/*! \file pimemoryblock.h //! \~\ingroup Core
* \ingroup Core
* \~\brief //! \~\file pimemoryblock.h
* \~english Non-owning memory block helper //! \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,11 +33,10 @@
#define PIMEMORYBLOCK_H #define PIMEMORYBLOCK_H
//! \ingroup Core
//! \include pimemoryblock.h
//! \~\brief //! \~\brief
//! \~english Helper structure describing a non-owning memory block. //! \~english Helper struct to store and restore custom blocks of data to/from PIBinaryStream
//! \~russian Вспомогательная структура, описывающая невладеющий блок памяти. //! \~russian Вспомогательная структура для сохранения и извлечения произвольных блоков данных в/из PIBinaryStream
struct PIMemoryBlock { struct PIMemoryBlock {
public: public:
//! \~english Constructs empty memory block. //! \~english Constructs empty memory block.
@@ -81,7 +86,7 @@ private:
int s = 0; int s = 0;
}; };
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Creates %PIMemoryBlock for object pointed by "ptr". //! \~english Creates %PIMemoryBlock for object pointed by "ptr".
//! \~russian Создает %PIMemoryBlock для объекта, на который указывает "ptr". //! \~russian Создает %PIMemoryBlock для объекта, на который указывает "ptr".

View File

@@ -1,20 +1,8 @@
/*! \file piobject.h //! \~\ingroup Core
* \ingroup Core //! \~\file piobject.h
* \~\brief //! \~\brief
* \~english Base object for the event and metaobject API //! \~english Base object class providing event -> handler mechanism
* \~russian Базовый объект для событийного и метаобъектного API //! \~russian Базовый класс объектов, обеспечивающий механизм событий -> обработчиков
*
* \~\details
* \~english
* This file declares %PIObject, its connection handle, queued delivery entry
* points and public registered-method introspection helpers. Together with
* \a piobject_macros.h it forms the public event and metaobject surface.
* \~russian
* Этот файл объявляет %PIObject, его объект соединения, точки входа для
* отложенной доставки и публичные методы интроспекции зарегистрированных
* методов. Вместе с \a piobject_macros.h он образует публичный событийный и
* метаобъектный интерфейс.
*/
/* /*
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
@@ -45,17 +33,21 @@
#include "pivariant.h" #include "pivariant.h"
#include "pivariantsimple.h" #include "pivariantsimple.h"
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Base class for objects that declare events, event handlers and registered methods. //! \~english Base class for objects that declare events, event handlers and registered methods.
//! \~russian Базовый класс для объектов, которые объявляют события, обработчики событий и зарегистрированные методы. //! \~russian Базовый класс для объектов, которые объявляют события, обработчики событий и зарегистрированные методы.
//! \~\details //! \~\details
//! \~english //! \~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 //! %PIObject stores named properties, keeps connection state and exposes a
//! small metaobject table used by \a CONNECTU(), \a execute() and related APIs. //! small metaobject table used by \a CONNECTU(), \a execute() and related APIs.
//! Queued delivery runs on the performer object and requires explicit draining //! Queued delivery runs on the performer object and requires explicit draining
//! through \a callQueuedEvents() or \a maybeCallQueuedEvents(). //! through \a callQueuedEvents() or \a maybeCallQueuedEvents().
//! \~russian //! \~russian
//! PIObject является базовым классом для всех классов PIP, которым необходима событийная коммуникация.
//! Он обеспечивает механизм сигналов-слотов, систему свойств и управление жизненным циклом объектов.
//! %PIObject хранит именованные свойства, состояние соединений и небольшую //! %PIObject хранит именованные свойства, состояние соединений и небольшую
//! метаобъектную таблицу, которую используют \a CONNECTU(), \a execute() и //! метаобъектную таблицу, которую используют \a CONNECTU(), \a execute() и
//! связанные методы. Отложенная доставка выполняется на объекте-исполнителе и //! связанные методы. Отложенная доставка выполняется на объекте-исполнителе и
@@ -81,7 +73,7 @@ public:
//! \~russian Уничтожает объект, вызывает \a deleted() и отключает его от событийного графа. //! \~russian Уничтожает объект, вызывает \a deleted() и отключает его от событийного графа.
virtual ~PIObject(); virtual ~PIObject();
//! \ingroup Core //! \~\ingroup Core
//! \~\brief //! \~\brief
//! \~english Handle of one connection between a source object and a destination object or functor. //! \~english Handle of one connection between a source object and a destination object or functor.
//! \~russian Дескриптор одного соединения между объектом-источником и объектом-приемником либо функтором. //! \~russian Дескриптор одного соединения между объектом-источником и объектом-приемником либо функтором.
@@ -165,11 +157,7 @@ public:
return ret; return ret;
} }
//! \~english Returns the compile-time class name used by the macro layer.
//! \~russian Возвращает имя класса времени компиляции, используемое макросным слоем.
static const char * __classNameCC() { return "PIObject"; } static const char * __classNameCC() { return "PIObject"; }
//! \~english Returns the compile-time class name hash used by the metaobject layer.
//! \~russian Возвращает хэш имени класса времени компиляции, используемый метаобъектным слоем.
static uint __classNameIDS() { static uint __classNameIDS() {
static uint ret = PIStringAscii("PIObject").hash(); static uint ret = PIStringAscii("PIObject").hash();
return ret; return ret;
@@ -214,8 +202,10 @@ public:
//! \~english Enables or disables the internal object mutex during handler execution. //! \~english Enables or disables the internal object mutex during handler execution.
//! \~russian Включает или отключает внутренний мьютекс объекта во время выполнения обработчиков. //! \~russian Включает или отключает внутренний мьютекс объекта во время выполнения обработчиков.
//! \~\details //! \~\details
//! \~english This flag affects direct and queued handler invocation for this object, but does not describe full thread-safety of the class. //! \~english This flag affects direct and queued handler invocation for this object, but does not describe full thread-safety of the
//! \~russian Этот флаг влияет на прямой и отложенный вызов обработчиков для данного объекта, но не описывает полную потокобезопасность класса. //! 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. //! \~english Returns whether the internal object mutex is enabled for handler execution.
//! \~russian Возвращает, включен ли внутренний мьютекс объекта для выполнения обработчиков. //! \~russian Возвращает, включен ли внутренний мьютекс объекта для выполнения обработчиков.
@@ -753,8 +743,6 @@ public:
//! \~russian Планирует отложенное удаление объекта. //! \~russian Планирует отложенное удаление объекта.
void deleteLater(); void deleteLater();
EVENT1(deleted, PIObject *, o);
//! \events //! \events
//! \{ //! \{
@@ -769,6 +757,7 @@ public:
//! \~russian //! \~russian
//! Это событие вызывается из деструктора, поэтому используйте //! Это событие вызывается из деструктора, поэтому используйте
//! только численное значение "o", не надо кастовать его в другие типы! //! только численное значение "o", не надо кастовать его в другие типы!
EVENT1(deleted, PIObject *, o);
//! \} //! \}
@@ -848,12 +837,15 @@ private:
}; };
#ifndef MICRO_PIP #ifndef MICRO_PIP
//! \~english Dumps application-level %PIObject diagnostics. //! \~english Dumps application-level %PIObject diagnostics.
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject. //! \~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". //! \~english Dumps application-level %PIObject diagnostics to file "path".
//! \~russian Выводит диагностическую информацию уровня приложения для %PIObject в файл "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

View File

@@ -1,19 +1,17 @@
/*! \file piobject_macros.h //! \~\ingroup Core
* \ingroup Core //! \~\file piobject_macros.h
* \~\brief //! \~\brief
* \~english Macros for the %PIObject event and metaobject API //! \~english PIObject macros for event system and object introspection
* \~russian Макросы для событийного и метаобъектного API %PIObject //! \~russian Макросы PIObject для событийной системы и интроспекции объектов
* //! \~\details
* \~\details //! \~english
* \~english //! This file declares the macro layer used by %PIObject-based classes:
* This file declares the macro layer used by %PIObject-based classes: //! class registration, event declaration, event handler declaration,
* class registration, event declaration, event handler declaration, //! connection helpers and event raising helpers.
* connection helpers and event raising helpers. //! \~russian
* \~russian //! Этот файл объявляет макросный слой для классов на базе %PIObject:
* Этот файл объявляет макросный слой для классов на базе %PIObject: //! регистрацию класса, объявление событий, объявление обработчиков,
* регистрацию класса, объявление событий, объявление обработчиков, //! макросы соединения и макросы вызова событий.
* макросы соединения и макросы вызова событий.
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Macros for PIObject Macros for PIObject

View File

@@ -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,7 +30,7 @@
#include "pip_crypt_export.h" #include "pip_crypt_export.h"
//! \ingroup Crypt //! \~\ingroup Crypt
//! \~\brief //! \~\brief
//! \~english Peer authentication state machine with signed key exchange. //! \~english Peer authentication state machine with signed key exchange.
//! \~russian Машина состояний аутентификации узлов с подписанным обменом ключами. //! \~russian Машина состояний аутентификации узлов с подписанным обменом ключами.
@@ -43,17 +42,22 @@ public:
//! \~russian Состояние рукопожатия. //! \~russian Состояние рукопожатия.
enum State { enum State {
NotConnected /** \~english No active authentication session. \~russian Активной сессии аутентификации нет. */, NotConnected /** \~english No active authentication session. \~russian Активной сессии аутентификации нет. */,
AuthProbe /** \~english Initial probe stage with signed peer introduction. \~russian Начальный этап с подписанным представлением узла. */, AuthProbe /** \~english Initial probe stage with signed peer introduction. \~russian Начальный этап с подписанным представлением
узла. */
,
PassRequest /** \~english Password verification stage for unknown peers. \~russian Этап проверки пароля для неизвестных узлов. */, PassRequest /** \~english Password verification stage for unknown peers. \~russian Этап проверки пароля для неизвестных узлов. */,
AuthReply /** \~english Reply with client authentication data. \~russian Ответ с данными аутентификации клиента. */, AuthReply /** \~english Reply with client authentication data. \~russian Ответ с данными аутентификации клиента. */,
KeyExchange /** \~english Session key exchange stage. \~russian Этап обмена сеансовым ключом. */, KeyExchange /** \~english Session key exchange stage. \~russian Этап обмена сеансовым ключом. */,
Connected /** \~english Authentication finished and session key is established. \~russian Аутентификация завершена и сеансовый ключ установлен. */ Connected /** \~english Authentication finished and session key is established. \~russian Аутентификация завершена и сеансовый ключ
установлен. */
}; };
//! \~english Creates an authentication endpoint from a signing secret key. //! \~english Creates an authentication endpoint from a signing secret key.
//! \~russian Создает конечную точку аутентификации из секретного ключа подписи. //! \~russian Создает конечную точку аутентификации из секретного ключа подписи.
PIAuth(const PIByteArray & sign); PIAuth(const PIByteArray & sign);
//! \~english Sets application-defined info exchanged during authorization. //! \~english Sets application-defined info exchanged during authorization.
//! \~russian Задает прикладные данные, передаваемые во время авторизации. //! \~russian Задает прикладные данные, передаваемые во время авторизации.
void setInfoData(const PIByteArray & info) { custom_info = info; } void setInfoData(const PIByteArray & info) { custom_info = info; }
@@ -100,33 +104,34 @@ public:
static PIByteArray generateSign(const PIByteArray & seed); static PIByteArray generateSign(const PIByteArray & seed);
EVENT1(disconnected, PIString, reason);
EVENT1(connected, PIString, info);
EVENT2(authorize, PIByteArray, info, bool *, ok);
EVENT1(passwordRequest, PIString *, pass);
EVENT1(passwordCheck, bool, result);
//! \events //! \events
//! \{ //! \{
//! \fn void disconnected(PIString reason) //! \fn void disconnected(PIString reason)
//! \~english Raised when the handshake is aborted or an established session is dropped. //! \~english Raised when the handshake is aborted or an established session is dropped.
//! \~russian Вызывается при прерывании рукопожатия или разрыве установленной сессии. //! \~russian Вызывается при прерывании рукопожатия или разрыве установленной сессии.
//! EVENT1(disconnected, PIString, reason);
//! \fn void connected(PIString info) //! \fn void connected(PIString info)
//! \~english Raised after the peer reaches state \a Connected. //! \~english Raised after the peer reaches state \a Connected.
//! \~russian Вызывается после перехода узла в состояние \a Connected. //! \~russian Вызывается после перехода узла в состояние \a Connected.
//! EVENT1(connected, PIString, info);
//! \fn void authorize(PIByteArray info, bool * ok) //! \fn void authorize(PIByteArray info, bool * ok)
//! \~english Client-side callback used to approve an unknown server and optionally trust its signing key. //! \~english Client-side callback used to approve an unknown server and optionally trust its signing key.
//! \~russian Клиентский вызов для подтверждения неизвестного сервера и, при необходимости, доверия его ключу подписи. //! \~russian Клиентский вызов для подтверждения неизвестного сервера и, при необходимости, доверия его ключу подписи.
//! EVENT2(authorize, PIByteArray, info, bool *, ok);
//! \fn void passwordRequest(PIString * pass) //! \fn void passwordRequest(PIString * pass)
//! \~english Client-side callback requesting the server password. //! \~english Client-side callback requesting the server password.
//! \~russian Клиентский вызов для запроса пароля сервера. //! \~russian Клиентский вызов для запроса пароля сервера.
//! EVENT1(passwordRequest, PIString *, pass);
//! \fn void passwordCheck(bool result) //! \fn void passwordCheck(bool result)
//! \~english Server-side callback reporting the result of client password validation. //! \~english Server-side callback reporting the result of client password validation.
//! \~russian Серверный вызов, сообщающий результат проверки пароля клиента. //! \~russian Серверный вызов, сообщающий результат проверки пароля клиента.
EVENT1(passwordCheck, bool, result);
//! \} //! \}
private: private:

View File

@@ -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();

View File

@@ -1,15 +1,8 @@
/*! \file pidigest.h //! \~\file pidigest.h
* \ingroup Digest //! \~\ingroup Digest
* \~\brief //! \~\brief
* \~english Digest calculation helpers //! \~english Digest calculation helpers
* \~russian Вспомогательные методы вычисления хэш-сумм //! \~russian Вспомогательные методы вычисления хэш-сумм
*
* \~\details
* \~english
* Declares one-shot helpers for digest, keyed digest, and HMAC algorithms
* \~russian
* Объявляет одношаговые методы для хэширования, keyed digest и HMAC
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Digest algorithms Digest algorithms
@@ -36,47 +29,45 @@
#include "piconstchars.h" #include "piconstchars.h"
//! \class PIDigest //! \class PIDigest
//! \ingroup Digest //! \~\ingroup Digest
//! \~\brief //! \~\brief
//! \~english One-shot digest API for supported algorithms. //! \~english One-shot digest API for supported algorithms.
//! \~russian Одношаговый API хэширования для поддерживаемых алгоритмов. //! \~russian Одношаговый API хэширования для поддерживаемых алгоритмов.
class PIP_EXPORT PIDigest { class PIP_EXPORT PIDigest {
public: public:
//! \~english Supported digest algorithms. //! \~english Supported digest algorithms.
//! \~russian Поддерживаемые алгоритмы хэширования. //! \~russian Поддерживаемые алгоритмы хэширования.
enum class Type { enum class Type {
SHA1 /** \~english SHA-1 \~russian SHA-1 */, SHA1 /** \~english SHA-1 \~russian SHA-1 */,
SHA2_224, /** \~english SHA-2 with 224-bit digest \~russian SHA-2 с дайджестом 224 бита */ SHA2_224 /** \~english SHA-2 with 224-bit digest \~russian SHA-2 с дайджестом 224 бита */,
SHA2_256, /** \~english SHA-2 with 256-bit digest \~russian SHA-2 с дайджестом 256 бит */ SHA2_256 /** \~english SHA-2 with 256-bit digest \~russian SHA-2 с дайджестом 256 бит */,
SHA2_384, /** \~english SHA-2 with 384-bit digest \~russian SHA-2 с дайджестом 384 бита */ SHA2_384 /** \~english SHA-2 with 384-bit digest \~russian SHA-2 с дайджестом 384 бита */,
SHA2_512, /** \~english SHA-2 with 512-bit digest \~russian SHA-2 с дайджестом 512 бит */ SHA2_512 /** \~english SHA-2 with 512-bit digest \~russian SHA-2 с дайджестом 512 бит */,
SHA2_512_224, /** \~english SHA-512/224 \~russian SHA-512/224 */ SHA2_512_224 /** \~english SHA-512/224 \~russian SHA-512/224 */,
SHA2_512_256, /** \~english SHA-512/256 \~russian SHA-512/256 */ SHA2_512_256 /** \~english SHA-512/256 \~russian SHA-512/256 */,
MD2, /** \~english MD2 \~russian MD2 */ MD2 /** \~english MD2 \~russian MD2 */,
MD4, /** \~english MD4 \~russian MD4 */ MD4 /** \~english MD4 \~russian MD4 */,
MD5, /** \~english MD5 \~russian MD5 */ MD5 /** \~english MD5 \~russian MD5 */,
BLAKE2s_128, /** \~english BLAKE2s with 128-bit digest \~russian BLAKE2s с дайджестом 128 бит */ BLAKE2s_128 /** \~english BLAKE2s with 128-bit digest \~russian BLAKE2s с дайджестом 128 бит */,
BLAKE2s_160, /** \~english BLAKE2s with 160-bit digest \~russian BLAKE2s с дайджестом 160 бит */ BLAKE2s_160 /** \~english BLAKE2s with 160-bit digest \~russian BLAKE2s с дайджестом 160 бит */,
BLAKE2s_224, /** \~english BLAKE2s with 224-bit digest \~russian BLAKE2s с дайджестом 224 бита */ BLAKE2s_224 /** \~english BLAKE2s with 224-bit digest \~russian BLAKE2s с дайджестом 224 бита */,
BLAKE2s_256, /** \~english BLAKE2s with 256-bit digest \~russian BLAKE2s с дайджестом 256 бит */ BLAKE2s_256 /** \~english BLAKE2s with 256-bit digest \~russian BLAKE2s с дайджестом 256 бит */,
BLAKE2b_128, /** \~english BLAKE2b with 128-bit digest \~russian BLAKE2b с дайджестом 128 бит */ BLAKE2b_128 /** \~english BLAKE2b with 128-bit digest \~russian BLAKE2b с дайджестом 128 бит */,
BLAKE2b_160, /** \~english BLAKE2b with 160-bit digest \~russian BLAKE2b с дайджестом 160 бит */ BLAKE2b_160 /** \~english BLAKE2b with 160-bit digest \~russian BLAKE2b с дайджестом 160 бит */,
BLAKE2b_224, /** \~english BLAKE2b with 224-bit digest \~russian BLAKE2b с дайджестом 224 бита */ BLAKE2b_224 /** \~english BLAKE2b with 224-bit digest \~russian BLAKE2b с дайджестом 224 бита */,
BLAKE2b_256, /** \~english BLAKE2b with 256-bit digest \~russian BLAKE2b с дайджестом 256 бит */ BLAKE2b_256 /** \~english BLAKE2b with 256-bit digest \~russian BLAKE2b с дайджестом 256 бит */,
BLAKE2b_384, /** \~english BLAKE2b with 384-bit digest \~russian BLAKE2b с дайджестом 384 бита */ BLAKE2b_384 /** \~english BLAKE2b with 384-bit digest \~russian BLAKE2b с дайджестом 384 бита */,
BLAKE2b_512, /** \~english BLAKE2b with 512-bit digest \~russian BLAKE2b с дайджестом 512 бит */ BLAKE2b_512 /** \~english BLAKE2b with 512-bit digest \~russian BLAKE2b с дайджестом 512 бит */,
SipHash_2_4_64, /** \~english SipHash-2-4 with 64-bit output \~russian 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, /** \~english SipHash-2-4 with 128-bit output \~russian 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, /** \~english HalfSipHash-2-4 with 32-bit output \~russian 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, /** \~english HalfSipHash-2-4 with 64-bit output \~russian HalfSipHash-2-4 с выходом 64 бита */ HalfSipHash_2_4_64 /** \~english HalfSipHash-2-4 with 64-bit output \~russian HalfSipHash-2-4 с выходом 64 бита */,
Count /** \~english Number of supported algorithms \~russian Количество поддерживаемых алгоритмов */, Count /** \~english Number of supported algorithms \~russian Количество поддерживаемых алгоритмов */
}; };

View File

@@ -1,9 +1,8 @@
/*! \file piellipsoidmodel.h //! \~\ingroup Geo
* \ingroup Geo //! \~\file piellipsoidmodel.h
* \~\brief //! \brief
* \~english Earth ellipsoid 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,10 +28,15 @@
#include "pimathbase.h" #include "pimathbase.h"
//! \ingroup Geo //! \~\ingroup Geo
//! \~\brief //! \~\brief
//! \~english Reference ellipsoid parameters used by geographic calculations. //! \~english Reference ellipsoid parameters used by geographic calculations.
//! \~russian Параметры опорного эллипсоида для географических вычислений. //! \~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. //! \~english Constructs an empty ellipsoid description.

View File

@@ -28,8 +28,8 @@
*/ */
//! \defgroup Geo Geo //! \defgroup Geo Geo
//! \~\brief //! \~\brief
//! \~english Geographical position and Earth models //! \~english Geographical position and Earth models module.
//! \~russian Географическая позиция и модели Земли //! \~russian Модуль географической позиции и моделей Земли.
//! //!
//! \~\details //! \~\details
//! \~english \section cmake_module_Geo Building with CMake //! \~english \section cmake_module_Geo Building with CMake
@@ -53,10 +53,8 @@
//! //!
//! \~\authors //! \~\authors
//! \~english //! \~english
//! Ivan Pelipenko peri4ko@yandex.ru;
//! Andrey Bychkov work.a.b@yandex.ru; //! Andrey Bychkov work.a.b@yandex.ru;
//! \~russian //! \~russian
//! Иван Пелипенко peri4ko@yandex.ru;
//! Андрей Бычков work.a.b@yandex.ru; //! Андрей Бычков work.a.b@yandex.ru;
//! //!

View File

@@ -1,9 +1,8 @@
/*! \file pigeoposition.h //! \~\ingroup Geo
* \ingroup Geo //! \~\file pigeoposition.h
* \~\brief //! \brief
* \~english Geographic position storage and coordinate 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,21 +28,27 @@
#include "piellipsoidmodel.h" #include "piellipsoidmodel.h"
#include "pimathvector.h" #include "pimathvector.h"
//! \ingroup Geo //! \~\ingroup Geo
//! \~\brief //! \~\brief
//! \~english Geographic position represented in one of several coordinate systems. //! \~english Geographic position represented in one of several coordinate systems.
//! \~russian Географическая позиция, представленная в одной из нескольких систем координат. //! \~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. //! \~english Coordinate system used by stored components.
//! \~russian Система координат, используемая для хранимых компонент. //! \~russian Система координат, используемая для хранимых компонент.
enum CoordinateSystem { enum CoordinateSystem {
Unknown = 0, /** \~english Unknown coordinate system \~russian Неизвестная система координат */ Unknown = 0 /** \~english Unknown coordinate system \~russian Неизвестная система координат */,
Geodetic, /** \~english Geodetic latitude, longitude and height above the ellipsoid \~russian Геодезическая широта, долгота и высота Geodetic /** \~english Geodetic latitude, longitude and height above the ellipsoid \~russian Геодезическая широта, долгота и высота
над эллипсоидом */ над эллипсоидом */
Geocentric, /** \~english Geocentric latitude, longitude and radius \~russian Геоцентрическая широта, долгота и радиус */ ,
Cartesian, /** \~english Earth-centered Earth-fixed Cartesian coordinates \~russian Декартовы координаты ECEF */ Geocentric /** \~english Geocentric latitude, longitude and radius \~russian Геоцентрическая широта, долгота и радиус */,
Spherical /** \~english Spherical coordinates as theta, phi and radius \~russian Сферические координаты: тета, фи и радиус */ Cartesian /** \~english Earth-centered Earth-fixed Cartesian coordinates \~russian Декартовы координаты ECEF */,
Spherical /** \~english Spherical coordinates as theta, phi and radius \~russian Сферические координаты: тета, фи и радиус */
}; };
//! \~english One centimeter tolerance in meters. //! \~english One centimeter tolerance in meters.
@@ -136,16 +141,16 @@ public:
//! \~russian Возвращает долготу в градусах. //! \~russian Возвращает долготу в градусах.
double longitude() const; double longitude() const;
//! \~english Returns spherical theta angle in degrees. //! \~english Returns spherical theta angle in degrees (angle from Z axis).
//! \~russian Возвращает сферический угол тета в градусах. //! \~russian Возвращает сферический угол тета в градусах (угол от оси Z).
double theta() const; double theta() const;
//! \~english Returns spherical phi angle in degrees. //! \~english Returns spherical phi angle in degrees (angle in XY plane from X axis).
//! \~russian Возвращает сферический угол фи в градусах. //! \~russian Возвращает сферический угол фи в градусах (угол в плоскости XY от оси X).
double phi() const; double phi() const;
//! \~english Returns radius in meters for spherical or geocentric form. //! \~english Returns radius in meters for spherical or geocentric form (distance from Earth center).
//! \~russian Возвращает радиус в метрах для сферического или геоцентрического представления. //! \~russian Возвращает радиус в метрах для сферического или геоцентрического представления (расстояние от центра Земли).
double radius() const; double radius() const;
//! \~english Returns geodetic height above the ellipsoid in meters. //! \~english Returns geodetic height above the ellipsoid in meters.
@@ -313,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);
@@ -320,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);
@@ -327,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);
} }

View File

@@ -1,9 +1,26 @@
/*! \file pihttpclient.h //! \~\file pihttpclient.h
* \ingroup HTTP //! \~\ingroup HTTPClient
* \~\brief //! \~\brief
* \~english Public HTTP client request API //! \~english Public HTTP client request API
* \~russian Публичный API HTTP-клиента для выполнения запросов //! \~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,10 +30,6 @@
#include "pistringlist.h" #include "pistringlist.h"
//! \ingroup HTTP
//! \~\brief
//! \~english Internal callback bridge used by \a PIHTTPClient transport virtual methods.
//! \~russian Внутренний мост callback-ов, используемый транспортными виртуальными методами \a PIHTTPClient.
class PIHTTPClientBase { class PIHTTPClientBase {
public: public:
int __infoFunc(ssize_t dltotal, ssize_t dlnow, ssize_t ultotal, ssize_t ulnow); int __infoFunc(ssize_t dltotal, ssize_t dlnow, ssize_t ultotal, ssize_t ulnow);
@@ -24,7 +37,7 @@ public:
}; };
//! \ingroup HTTP //! \~\ingroup HTTPClient
//! \~\brief //! \~\brief
//! \~english Asynchronous HTTP client request with completion callbacks. //! \~english Asynchronous HTTP client request with completion callbacks.
//! \~russian Асинхронный HTTP-запрос клиента с callback-ами завершения. //! \~russian Асинхронный HTTP-запрос клиента с callback-ами завершения.
@@ -85,11 +98,7 @@ public:
private: private:
NO_COPY_CLASS(PIHTTPClient) NO_COPY_CLASS(PIHTTPClient)
//! \~english Creates an empty client object. Use \a create() for public construction.
//! \~russian Создает пустой объект клиента. Для публичного создания используйте \a create().
PIHTTPClient(); PIHTTPClient();
//! \~english Destroys the client object.
//! \~russian Удаляет объект клиента.
virtual ~PIHTTPClient(); virtual ~PIHTTPClient();
PRIVATE_DECLARATION(PIP_HTTP_CLIENT_EXPORT) PRIVATE_DECLARATION(PIP_HTTP_CLIENT_EXPORT)

View File

@@ -1,17 +1,19 @@
/*! \file pihttpclientmodule.h //! \~\file pihttpclientmodule.h
* \ingroup HTTP //! \~\ingroup HTTPClient
* \~\brief //! \~\brief
* \~english Module include for the public HTTP client API //! \~english HTTP client module includes for PIP library
* \~russian Модульный include для публичного API HTTP-клиента //! \~russian Модуль инклюдов HTTP клиента для библиотеки PIP
* //! \details
* \~\details //! \~english
* \~english Includes the primary public HTTP client class declarations. //! This file includes all HTTP client module headers providing async HTTP client functionality
* \~russian Подключает основные публичные объявления классов HTTP-клиента. //! 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
@@ -26,6 +28,32 @@
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 HTTPClient HTTPClient
//! \~\brief
//! \~english HTTP client
//! \~russian HTTP клиент
//!
//! \~\details
//! \~english \section cmake_module_HTTPClient Building with CMake
//! \~russian \section cmake_module_HTTPClient Сборка с использованием CMake
//!
//! \~\code
//! find_package(PIP REQUIRED)
//! target_link_libraries([target] PIP::HTTPClient)
//! \endcode
//!
//! \~\details
//! \~english
//! These files provide HTTP client functionality using libcurl for performing asynchronous HTTP requests with callbacks.
//! \~russian
//! Эти файлы предоставляют функциональность HTTP клиента с использованием libcurl для выполнения асинхронных HTTP запросов с callback-ми.
//!
//! \~\authors
//! \~english
//! Ivan Pelipenko peri4ko@yandex.ru;
//! \~russian
//! Иван Пелипенко peri4ko@yandex.ru;
//!
#ifndef pihttpclientmodule_H #ifndef pihttpclientmodule_H
#define pihttpclientmodule_H #define pihttpclientmodule_H

View File

@@ -1,9 +1,30 @@
/*! \file pihttpconstants.h //! \~\ingroup HTTP
* \ingroup HTTP //! \~\file pihttpconstants.h
* \~\brief //! \brief HTTP constants and enumerations
* \~english Shared HTTP methods, status codes and header name constants //! \~english Definitions for HTTP methods, status codes and header names
* \~russian Общие HTTP-методы, коды статуса и константы имен заголовков //! \~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
@@ -16,91 +37,91 @@ namespace PIHTTP {
//! \~english HTTP request method. //! \~english HTTP request method.
//! \~russian HTTP-метод запроса. //! \~russian HTTP-метод запроса.
enum class Method { enum class Method {
Unknown /** \~english Unknown or not set method \~russian Неизвестный или не заданный метод */, Unknown,
Get /** \~english GET method \~russian Метод GET */, Get,
Head /** \~english HEAD method \~russian Метод HEAD */, Head,
Post /** \~english POST method \~russian Метод POST */, Post,
Put /** \~english PUT method \~russian Метод PUT */, Put,
Delete /** \~english DELETE method \~russian Метод DELETE */, Delete,
Connect /** \~english CONNECT method \~russian Метод CONNECT */, Connect,
Options /** \~english OPTIONS method \~russian Метод OPTIONS */, Options,
Trace /** \~english TRACE method \~russian Метод TRACE */, Trace,
Patch /** \~english PATCH method \~russian Метод PATCH */, Patch,
}; };
//! \~english HTTP status code. //! \~english HTTP status code.
//! \~russian HTTP-код статуса. //! \~russian HTTP-код статуса.
enum class Code { enum class Code {
Unknown /** \~english Unknown or unset status code \~russian Неизвестный или не заданный код статуса */ = -1, Unknown = -1,
Continue /** \~english 100 Continue \~russian 100 Continue */ = 100, Continue = 100,
SwitchingProtocols /** \~english 101 Switching Protocols \~russian 101 Switching Protocols */ = 101, SwitchingProtocols = 101,
Processing /** \~english 102 Processing \~russian 102 Processing */ = 102, Processing = 102,
EarlyHints /** \~english 103 Early Hints \~russian 103 Early Hints */ = 103, EarlyHints = 103,
Ok /** \~english 200 OK \~russian 200 OK */ = 200, Ok = 200,
Created /** \~english 201 Created \~russian 201 Created */ = 201, Created = 201,
Accepted /** \~english 202 Accepted \~russian 202 Accepted */ = 202, Accepted = 202,
NonAuthoritativeInformation /** \~english 203 Non-Authoritative Information \~russian 203 Non-Authoritative Information */ = 203, NonAuthoritativeInformation = 203,
NoContent /** \~english 204 No Content \~russian 204 No Content */ = 204, NoContent = 204,
ResetContent /** \~english 205 Reset Content \~russian 205 Reset Content */ = 205, ResetContent = 205,
PartialContent /** \~english 206 Partial Content \~russian 206 Partial Content */ = 206, PartialContent = 206,
MultiStatus /** \~english 207 Multi-Status \~russian 207 Multi-Status */ = 207, MultiStatus = 207,
AlreadyReported /** \~english 208 Already Reported \~russian 208 Already Reported */ = 208, AlreadyReported = 208,
IMUsed /** \~english 226 IM Used \~russian 226 IM Used */ = 226, IMUsed = 226,
MultipleChoices /** \~english 300 Multiple Choices \~russian 300 Multiple Choices */ = 300, MultipleChoices = 300,
MovedPermanently /** \~english 301 Moved Permanently \~russian 301 Moved Permanently */ = 301, MovedPermanently = 301,
Found /** \~english 302 Found \~russian 302 Found */ = 302, Found = 302,
SeeOther /** \~english 303 See Other \~russian 303 See Other */ = 303, SeeOther = 303,
NotModified /** \~english 304 Not Modified \~russian 304 Not Modified */ = 304, NotModified = 304,
UseProxy /** \~english 305 Use Proxy \~russian 305 Use Proxy */ = 305, UseProxy = 305,
SwitchProxy /** \~english 306 Switch Proxy \~russian 306 Switch Proxy */ = 306, SwitchProxy = 306,
TemporaryRedirect /** \~english 307 Temporary Redirect \~russian 307 Temporary Redirect */ = 307, TemporaryRedirect = 307,
PermanentRedirect /** \~english 308 Permanent Redirect \~russian 308 Permanent Redirect */ = 308, PermanentRedirect = 308,
BadRequest /** \~english 400 Bad Request \~russian 400 Bad Request */ = 400, BadRequest = 400,
Unauthorized /** \~english 401 Unauthorized \~russian 401 Unauthorized */ = 401, Unauthorized = 401,
PaymentRequired /** \~english 402 Payment Required \~russian 402 Payment Required */ = 402, PaymentRequired = 402,
Forbidden /** \~english 403 Forbidden \~russian 403 Forbidden */ = 403, Forbidden = 403,
NotFound /** \~english 404 Not Found \~russian 404 Not Found */ = 404, NotFound = 404,
MethodNotAllowed /** \~english 405 Method Not Allowed \~russian 405 Method Not Allowed */ = 405, MethodNotAllowed = 405,
NotAcceptable /** \~english 406 Not Acceptable \~russian 406 Not Acceptable */ = 406, NotAcceptable = 406,
ProxyAuthenticationRequired /** \~english 407 Proxy Authentication Required \~russian 407 Proxy Authentication Required */ = 407, ProxyAuthenticationRequired = 407,
RequestTimeout /** \~english 408 Request Timeout \~russian 408 Request Timeout */ = 408, RequestTimeout = 408,
Conflict /** \~english 409 Conflict \~russian 409 Conflict */ = 409, Conflict = 409,
Gone /** \~english 410 Gone \~russian 410 Gone */ = 410, Gone = 410,
LengthRequired /** \~english 411 Length Required \~russian 411 Length Required */ = 411, LengthRequired = 411,
PreconditionFailed /** \~english 412 Precondition Failed \~russian 412 Precondition Failed */ = 412, PreconditionFailed = 412,
ContentTooLarge /** \~english 413 Content Too Large \~russian 413 Content Too Large */ = 413, ContentTooLarge = 413,
UriTooLong /** \~english 414 URI Too Long \~russian 414 URI Too Long */ = 414, UriTooLong = 414,
UnsupportedMediaType /** \~english 415 Unsupported Media Type \~russian 415 Unsupported Media Type */ = 415, UnsupportedMediaType = 415,
RangeNotSatisfiable /** \~english 416 Range Not Satisfiable \~russian 416 Range Not Satisfiable */ = 416, RangeNotSatisfiable = 416,
ExpectationFailed /** \~english 417 Expectation Failed \~russian 417 Expectation Failed */ = 417, ExpectationFailed = 417,
MisdirectedRequest /** \~english 421 Misdirected Request \~russian 421 Misdirected Request */ = 421, MisdirectedRequest = 421,
UnprocessableContent /** \~english 422 Unprocessable Content \~russian 422 Unprocessable Content */ = 422, UnprocessableContent = 422,
Locked /** \~english 423 Locked \~russian 423 Locked */ = 423, Locked = 423,
FailedDependency /** \~english 424 Failed Dependency \~russian 424 Failed Dependency */ = 424, FailedDependency = 424,
TooEarly /** \~english 425 Too Early \~russian 425 Too Early */ = 425, TooEarly = 425,
UpgradeRequired /** \~english 426 Upgrade Required \~russian 426 Upgrade Required */ = 426, UpgradeRequired = 426,
PreconditionRequired /** \~english 428 Precondition Required \~russian 428 Precondition Required */ = 428, PreconditionRequired = 428,
TooManyRequests /** \~english 429 Too Many Requests \~russian 429 Too Many Requests */ = 429, TooManyRequests = 429,
RequestHeaderFieldsTooLarge /** \~english 431 Request Header Fields Too Large \~russian 431 Request Header Fields Too Large */ = 431, RequestHeaderFieldsTooLarge = 431,
RetryWith /** \~english 449 Retry With \~russian 449 Retry With */ = 449, RetryWith = 449,
BlockedByWindowsParentalControls /** \~english 450 Blocked by Windows Parental Controls \~russian 450 Blocked by Windows Parental Controls */ = 450, BlockedByWindowsParentalControls = 450,
UnavailableForLegalReasons /** \~english 451 Unavailable For Legal Reasons \~russian 451 Unavailable For Legal Reasons */ = 451, UnavailableForLegalReasons = 451,
InternalServerError /** \~english 500 Internal Server Error \~russian 500 Internal Server Error */ = 500, InternalServerError = 500,
NotImplemented /** \~english 501 Not Implemented \~russian 501 Not Implemented */ = 501, NotImplemented = 501,
BadGateway /** \~english 502 Bad Gateway \~russian 502 Bad Gateway */ = 502, BadGateway = 502,
ServiceUnavailable /** \~english 503 Service Unavailable \~russian 503 Service Unavailable */ = 503, ServiceUnavailable = 503,
GatewayTimeout /** \~english 504 Gateway Timeout \~russian 504 Gateway Timeout */ = 504, GatewayTimeout = 504,
HttpVersionNotSupported /** \~english 505 HTTP Version Not Supported \~russian 505 HTTP Version Not Supported */ = 505, HttpVersionNotSupported = 505,
VariantAlsoNegotiates /** \~english 506 Variant Also Negotiates \~russian 506 Variant Also Negotiates */ = 506, VariantAlsoNegotiates = 506,
InsufficientStorage /** \~english 507 Insufficient Storage \~russian 507 Insufficient Storage */ = 507, InsufficientStorage = 507,
LoopDetected /** \~english 508 Loop Detected \~russian 508 Loop Detected */ = 508, LoopDetected = 508,
NotExtended /** \~english 510 Not Extended \~russian 510 Not Extended */ = 510, NotExtended = 510,
BandwidthLimitExceeded /** \~english 509 Bandwidth Limit Exceeded \~russian 509 Bandwidth Limit Exceeded */ = 509, BandwidthLimitExceeded = 509,
NetworkAuthenticationRequired /** \~english 511 Network Authentication Required \~russian 511 Network Authentication Required */ = 511, NetworkAuthenticationRequired = 511,
}; };
//! \~english Namespace with shared HTTP header field name literals. //! \~english Namespace with shared HTTP header field name literals.

View File

@@ -1,9 +1,26 @@
/*! \file pihttptypes.h //! \~\file pihttptypes.h
* \ingroup HTTP //! \~\ingroup HTTP
* \~\brief //! \~\brief
* \~english Shared HTTP message container types //! \~english Shared HTTP message container types
* \~russian Общие типы контейнеров HTTP-сообщений //! \~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
@@ -18,7 +35,7 @@
namespace PIHTTP { namespace PIHTTP {
//! \ingroup HTTP //! \~\ingroup HTTP
//! \~\brief //! \~\brief
//! \~english Immutable HTTP message view with accessors for method, path, headers and body. //! \~english Immutable HTTP message view with accessors for method, path, headers and body.
//! \~russian Неизменяемое HTTP-сообщение с доступом к методу, пути, заголовкам и телу. //! \~russian Неизменяемое HTTP-сообщение с доступом к методу, пути, заголовкам и телу.
@@ -56,6 +73,7 @@ public:
//! \~russian Возвращает \c true для любого кода ошибки клиента или сервера. //! \~russian Возвращает \c true для любого кода ошибки клиента или сервера.
bool isCodeError() const { return isCodeClientError() || isCodeServerError(); } bool isCodeError() const { return isCodeClientError() || isCodeServerError(); }
//! \~english Returns the request path or response target path. //! \~english Returns the request path or response target path.
//! \~russian Возвращает путь запроса или целевой путь ответа. //! \~russian Возвращает путь запроса или целевой путь ответа.
const PIString & path() const { return m_path; } const PIString & path() const { return m_path; }
@@ -94,7 +112,7 @@ protected:
}; };
//! \ingroup HTTP //! \~\ingroup HTTP
//! \~\brief //! \~\brief
//! \~english Mutable HTTP message with setters and argument/header modifiers. //! \~english Mutable HTTP message with setters and argument/header modifiers.
//! \~russian Изменяемое HTTP-сообщение с сеттерами и методами изменения аргументов и заголовков. //! \~russian Изменяемое HTTP-сообщение с сеттерами и методами изменения аргументов и заголовков.
@@ -116,22 +134,28 @@ public:
//! \~russian Устанавливает тело сообщения. //! \~russian Устанавливает тело сообщения.
MessageMutable & setBody(PIByteArray b); MessageMutable & setBody(PIByteArray b);
//! \~english Returns 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 Returns a modifiable map of all arguments. //! \~english Returns a modifiable map of all arguments.
//! \~russian Возвращает изменяемую карту всех аргументов. //! \~russian Возвращает изменяемую карту всех аргументов.
PIMap<PIString, PIString> & arguments() { return m_arguments; } PIMap<PIString, PIString> & arguments() { return m_arguments; }
//! \~english Returns all arguments. //! \~english Returns all arguments.
//! \~russian Возвращает все аргументы. //! \~russian Возвращает все аргументы.
const PIMap<PIString, PIString> & arguments() const { return m_arguments; } const PIMap<PIString, PIString> & arguments() const { return m_arguments; }
//! \~english Returns query arguments. //! \~english Returns query arguments.
//! \~russian Возвращает query-аргументы. //! \~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. //! \~english Returns path arguments.
//! \~russian Возвращает аргументы пути. //! \~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. //! \~english Returns a modifiable map of all message headers.
//! \~russian Возвращает изменяемую карту всех заголовков сообщения. //! \~russian Возвращает изменяемую карту всех заголовков сообщения.
PIMap<PIString, PIString> & headers() { return m_headers; } PIMap<PIString, PIString> & headers() { return m_headers; }
@@ -144,6 +168,7 @@ public:
//! \~russian Удаляет заголовок из сообщения. //! \~russian Удаляет заголовок из сообщения.
MessageMutable & removeHeader(const PIString & header); MessageMutable & removeHeader(const PIString & header);
//! \~english Returns a modifiable map of query arguments. //! \~english Returns a modifiable map of query arguments.
//! \~russian Возвращает изменяемую карту query-аргументов. //! \~russian Возвращает изменяемую карту query-аргументов.
PIMap<PIString, PIString> & queryArguments() { return m_query_arguments; } PIMap<PIString, PIString> & queryArguments() { return m_query_arguments; }
@@ -156,6 +181,7 @@ public:
//! \~russian Удаляет query-аргумент. //! \~russian Удаляет query-аргумент.
MessageMutable & removeQueryArgument(const PIString & arg); MessageMutable & removeQueryArgument(const PIString & arg);
//! \~english Returns a modifiable map of path arguments. //! \~english Returns a modifiable map of path arguments.
//! \~russian Возвращает изменяемую карту аргументов пути. //! \~russian Возвращает изменяемую карту аргументов пути.
PIMap<PIString, PIString> & pathArguments() { return m_path_arguments; } PIMap<PIString, PIString> & pathArguments() { return m_path_arguments; }
@@ -168,6 +194,7 @@ public:
//! \~russian Удаляет аргумент пути. //! \~russian Удаляет аргумент пути.
MessageMutable & removePathArgument(const PIString & arg); MessageMutable & removePathArgument(const PIString & arg);
//! \~english Creates a message initialized from an HTTP status code. //! \~english Creates a message initialized from an HTTP status code.
//! \~russian Создает сообщение, инициализированное HTTP-кодом статуса. //! \~russian Создает сообщение, инициализированное HTTP-кодом статуса.
static MessageMutable fromCode(PIHTTP::Code c); static MessageMutable fromCode(PIHTTP::Code c);

View File

@@ -1,9 +1,26 @@
/*! \file microhttpd_server.h //! \~\file microhttpd_server.h
* \ingroup HTTP //! \~\ingroup HTTPServer
* \~\brief //! \~\brief
* \~english Base HTTP server API built on top of libmicrohttpd //! \~english Base HTTP server API built on top of libmicrohttpd
* \~russian Базовый API HTTP-сервера, построенный поверх 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
@@ -14,7 +31,7 @@
struct MicrohttpdServerConnection; struct MicrohttpdServerConnection;
//! \ingroup HTTP //! \~\ingroup HTTPServer
//! \~\brief //! \~\brief
//! \~english Base HTTP server with request dispatch and optional basic authentication. //! \~english Base HTTP server with request dispatch and optional basic authentication.
//! \~russian Базовый HTTP-сервер с диспетчеризацией запросов и необязательной basic-аутентификацией. //! \~russian Базовый HTTP-сервер с диспетчеризацией запросов и необязательной basic-аутентификацией.
@@ -33,12 +50,19 @@ public:
//! \~english Server configuration options accepted by \a setOption(). //! \~english Server configuration options accepted by \a setOption().
//! \~russian Параметры конфигурации сервера, принимаемые методом \a setOption(). //! \~russian Параметры конфигурации сервера, принимаемые методом \a setOption().
enum class Option { enum class Option {
ConnectionLimit, //!< \~english Maximum number of simultaneously accepted connections. \~russian Максимальное число одновременно принимаемых соединений. ConnectionLimit /** \~english Maximum number of simultaneously accepted connections. \~russian Максимальное число одновременно
ConnectionTimeout, //!< \~english Per-connection timeout value. \~russian Значение таймаута для отдельного соединения. принимаемых соединений. */
HTTPSEnabled, //!< \~english Enables TLS mode for the daemon. \~russian Включает режим TLS для демона. ,
HTTPSMemKey, //!< \~english Private key stored in memory as \c PIByteArray. \~russian Приватный ключ, хранящийся в памяти в виде \c PIByteArray. ConnectionTimeout /** \~english Per-connection timeout value. \~russian Значение таймаута для отдельного соединения. */,
HTTPSMemCert, //!< \~english Certificate stored in memory as \c PIByteArray. \~russian Сертификат, хранящийся в памяти в виде \c PIByteArray. HTTPSEnabled /** \~english Enables TLS mode for the daemon. \~russian Включает режим TLS для демона. */,
HTTPSKeyPassword //!< \~english Password for the in-memory private key as \c PIByteArray. \~russian Пароль для приватного ключа в памяти в виде \c PIByteArray. HTTPSMemKey /** \~english Private key stored in memory as \c PIByteArray. \~russian Приватный ключ, хранящийся в памяти в виде \c
PIByteArray. */
,
HTTPSMemCert /** \~english Certificate stored in memory as \c PIByteArray. \~russian Сертификат, хранящийся в памяти в виде \c
PIByteArray. */
,
HTTPSKeyPassword /** \~english Password for the in-memory private key as \c PIByteArray. \~russian Пароль для приватного ключа в
памяти в виде \c PIByteArray. */
}; };
//! \~english Sets a server option. The expected variant payload depends on the selected \a Option. //! \~english Sets a server option. The expected variant payload depends on the selected \a Option.
@@ -89,11 +113,11 @@ public:
//! \~english Sets the callback that receives parsed requests and returns replies. //! \~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 = std::move(c); }
//! \~english Sets the credential validator used when HTTP Basic authentication is enabled. //! \~english Sets the credential validator used when HTTP Basic authentication is enabled.
//! \~russian Устанавливает валидатор учетных данных, используемый при включенной HTTP Basic-аутентификации. //! \~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 = std::move(c); }
private: private:
static void addFixedHeaders(PIHTTP::MessageMutable & msg); static void addFixedHeaders(PIHTTP::MessageMutable & msg);

View File

@@ -1,16 +1,33 @@
/*! \file pihttpserver.h //! \addtogroup HTTPServer
* \ingroup HTTP //! \~\file pihttpserver.h
* \~\brief //! \brief High-level HTTP server implementation
* \~english Path-routing HTTP server API //! \~english High-level HTTP server with path-based routing and handler registration
* \~russian API HTTP-сервера с маршрутизацией по путям //! \~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"
//! \ingroup HTTP //! \~\ingroup HTTPServer
//! \~\brief //! \~\brief
//! \~english HTTP server that routes requests by method and path pattern. //! \~english HTTP server that routes requests by method and path pattern.
//! \~russian HTTP-сервер, маршрутизирующий запросы по методу и шаблону пути. //! \~russian HTTP-сервер, маршрутизирующий запросы по методу и шаблону пути.
@@ -29,6 +46,7 @@ public:
//! \~english Creates a server with built-in path dispatching. //! \~english Creates a server with built-in path dispatching.
//! \~russian Создает сервер со встроенной диспетчеризацией по путям. //! \~russian Создает сервер со встроенной диспетчеризацией по путям.
PIHTTPServer(); PIHTTPServer();
//! \~english Destroys the server and stops listening if needed. //! \~english Destroys the server and stops listening if needed.
//! \~russian Удаляет сервер и при необходимости останавливает прослушивание. //! \~russian Удаляет сервер и при необходимости останавливает прослушивание.
virtual ~PIHTTPServer(); virtual ~PIHTTPServer();

View File

@@ -1,13 +1,11 @@
/*! \file pihttpservermodule.h //! \file pihttpservermodule.h
* \ingroup HTTP //! \ingroup HTTPServer
* \~\brief //! \~\brief
* \~english Module include for the public HTTP server API //! \~english Module include for the public HTTP server API
* \~russian Модульный include для публичного API HTTP-сервера //! \~russian Модульный include для публичного API HTTP-сервера
* //! \~\details
* \~\details //! \~english Includes the primary public HTTP server class declarations.
* \~english Includes the primary public HTTP server class declarations. //! \~russian Подключает основные публичные объявления классов HTTP-сервера.
* \~russian Подключает основные публичные объявления классов HTTP-сервера.
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Module includes Module includes
@@ -26,6 +24,30 @@
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
//!
//! \~\details
//! \~english This file provides includes for the HTTP server module
//! \~russian Этот файл предоставляет включения для модуля HTTP сервера
//!
//! \~\authors
//! \~english
//! Ivan Pelipenko peri4ko@yandex.ru;
//! \~russian
//! Иван Пелипенко peri4ko@yandex.ru;
//!
#ifndef pihttpservermodule_H #ifndef pihttpservermodule_H
#define pihttpservermodule_H #define pihttpservermodule_H

View File

@@ -68,13 +68,13 @@ class PIIntrospectionServer;
#ifdef DOXYGEN #ifdef DOXYGEN
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Declares singleton accessor `instance()` for an introspection interface class. //! \~english Declares singleton accessor `instance()` for an introspection interface class.
//! \~russian Объявляет метод-синглтон `instance()` для класса интерфейса интроспекции. //! \~russian Объявляет метод-синглтон `instance()` для класса интерфейса интроспекции.
# define __PIINTROSPECTION_SINGLETON_H__(T) # define __PIINTROSPECTION_SINGLETON_H__(T)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Defines singleton accessor `instance()` for an introspection interface class. //! \~english Defines singleton accessor `instance()` for an introspection interface class.
//! \~russian Определяет метод-синглтон `instance()` для класса интерфейса интроспекции. //! \~russian Определяет метод-синглтон `instance()` для класса интерфейса интроспекции.

View File

@@ -1,9 +1,8 @@
/*! \file piintrospection_containers.h //! \~\file piintrospection_containers.h
* \ingroup Introspection //! \~\ingroup Introspection
* \~\brief //! \~\brief
* \~english Container introspection helpers //! \~english Container introspection helpers
* \~russian Вспомогательные средства интроспекции контейнеров //! \~russian Вспомогательные средства интроспекции контейнеров
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Introspection module - interface for containers Introspection module - interface for containers
@@ -28,7 +27,7 @@
#include "pibase.h" #include "pibase.h"
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Metadata describing one tracked container element type. //! \~english Metadata describing one tracked container element type.
//! \~russian Метаданные, описывающие один отслеживаемый тип элементов контейнера. //! \~russian Метаданные, описывающие один отслеживаемый тип элементов контейнера.
@@ -68,7 +67,7 @@ struct PIP_EXPORT PIIntrospectionContainersType {
class PIIntrospectionContainers; class PIIntrospectionContainers;
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Lazily builds and caches type metadata for container introspection macros. //! \~english Lazily builds and caches type metadata for container introspection macros.
//! \~russian Лениво создает и кеширует метаданные типа для макросов интроспекции контейнеров. //! \~russian Лениво создает и кеширует метаданные типа для макросов интроспекции контейнеров.
@@ -95,63 +94,63 @@ private:
# ifdef DOXYGEN # ifdef DOXYGEN
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Registers construction of a container storing elements of type `t`. //! \~english Registers construction of a container storing elements of type `t`.
//! \~russian Регистрирует создание контейнера, хранящего элементы типа `t`. //! \~russian Регистрирует создание контейнера, хранящего элементы типа `t`.
# define PIINTROSPECTION_CONTAINER_NEW(t, isz) # define PIINTROSPECTION_CONTAINER_NEW(t, isz)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Registers destruction of a container storing elements of type `t`. //! \~english Registers destruction of a container storing elements of type `t`.
//! \~russian Регистрирует уничтожение контейнера, хранящего элементы типа `t`. //! \~russian Регистрирует уничтожение контейнера, хранящего элементы типа `t`.
# define PIINTROSPECTION_CONTAINER_DELETE(t) # define PIINTROSPECTION_CONTAINER_DELETE(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Adds `cnt` allocated element slots for containers of type `t`. //! \~english Adds `cnt` allocated element slots for containers of type `t`.
//! \~russian Добавляет `cnt` выделенных слотов элементов для контейнеров типа `t`. //! \~russian Добавляет `cnt` выделенных слотов элементов для контейнеров типа `t`.
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt) # define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Removes `cnt` allocated element slots for containers of type `t`. //! \~english Removes `cnt` allocated element slots for containers of type `t`.
//! \~russian Убирает `cnt` выделенных слотов элементов для контейнеров типа `t`. //! \~russian Убирает `cnt` выделенных слотов элементов для контейнеров типа `t`.
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt) # define PIINTROSPECTION_CONTAINER_FREE(t, cnt)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Adds `cnt` used element slots for containers of type `t`. //! \~english Adds `cnt` used element slots for containers of type `t`.
//! \~russian Добавляет `cnt` занятых слотов элементов для контейнеров типа `t`. //! \~russian Добавляет `cnt` занятых слотов элементов для контейнеров типа `t`.
# define PIINTROSPECTION_CONTAINER_USED(t, cnt) # define PIINTROSPECTION_CONTAINER_USED(t, cnt)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionContainersInterface //! \relatesalso PIIntrospectionContainersInterface
//! \~\brief //! \~\brief
//! \~english Removes `cnt` used element slots for containers of type `t`. //! \~english Removes `cnt` used element slots for containers of type `t`.
//! \~russian Убирает `cnt` занятых слотов элементов для контейнеров типа `t`. //! \~russian Убирает `cnt` занятых слотов элементов для контейнеров типа `t`.
# define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt) # define PIINTROSPECTION_CONTAINER_UNUSED(t, cnt)
# else # 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() );
# define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt) PIINTROSPECTION_CONTAINERS->containerAlloc (PIIntrospectionContainersTypeInfo<t>::get(), cnt); # define PIINTROSPECTION_CONTAINER_ALLOC(t, cnt) PIINTROSPECTION_CONTAINERS->containerAlloc (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
# define PIINTROSPECTION_CONTAINER_FREE(t, cnt) PIINTROSPECTION_CONTAINERS->containerFree (PIIntrospectionContainersTypeInfo<t>::get(), cnt); # define PIINTROSPECTION_CONTAINER_FREE(t, cnt) PIINTROSPECTION_CONTAINERS->containerFree (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
# define PIINTROSPECTION_CONTAINER_USED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUsed (PIIntrospectionContainersTypeInfo<t>::get(), cnt); # define PIINTROSPECTION_CONTAINER_USED(t, cnt) PIINTROSPECTION_CONTAINERS->containerUsed (PIIntrospectionContainersTypeInfo<t>::get(), cnt);
# 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 # endif
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Entry point for collecting container allocation and usage statistics. //! \~english Entry point for collecting container allocation and usage statistics.
//! \~russian Точка входа для сбора статистики выделения и использования контейнеров. //! \~russian Точка входа для сбора статистики выделения и использования контейнеров.
@@ -164,7 +163,7 @@ public:
//! \~english Registers construction of a container instance with element size `isz`. //! \~english Registers construction of a container instance with element size `isz`.
//! \~russian Регистрирует создание экземпляра контейнера с размером элемента `isz`. //! \~russian Регистрирует создание экземпляра контейнера с размером элемента `isz`.
void containerNew (const PIIntrospectionContainersType & ti, uint isz); void containerNew(const PIIntrospectionContainersType & ti, uint isz);
//! \~english Registers destruction of a container instance. //! \~english Registers destruction of a container instance.
//! \~russian Регистрирует уничтожение экземпляра контейнера. //! \~russian Регистрирует уничтожение экземпляра контейнера.
@@ -172,15 +171,15 @@ public:
//! \~english Adds `cnt` allocated element slots for tracked type `ti`. //! \~english Adds `cnt` allocated element slots for tracked type `ti`.
//! \~russian Добавляет `cnt` выделенных слотов элементов для отслеживаемого типа `ti`. //! \~russian Добавляет `cnt` выделенных слотов элементов для отслеживаемого типа `ti`.
void containerAlloc (const PIIntrospectionContainersType & ti, ullong cnt); void containerAlloc(const PIIntrospectionContainersType & ti, ullong cnt);
//! \~english Removes `cnt` allocated element slots for tracked type `ti`. //! \~english Removes `cnt` allocated element slots for tracked type `ti`.
//! \~russian Убирает `cnt` выделенных слотов элементов для отслеживаемого типа `ti`. //! \~russian Убирает `cnt` выделенных слотов элементов для отслеживаемого типа `ti`.
void containerFree (const PIIntrospectionContainersType & ti, ullong cnt); void containerFree(const PIIntrospectionContainersType & ti, ullong cnt);
//! \~english Adds `cnt` used element slots for tracked type `ti`. //! \~english Adds `cnt` used element slots for tracked type `ti`.
//! \~russian Добавляет `cnt` занятых слотов элементов для отслеживаемого типа `ti`. //! \~russian Добавляет `cnt` занятых слотов элементов для отслеживаемого типа `ti`.
void containerUsed (const PIIntrospectionContainersType & ti, ullong cnt); void containerUsed(const PIIntrospectionContainersType & ti, ullong cnt);
//! \~english Removes `cnt` used element slots for tracked type `ti`. //! \~english Removes `cnt` used element slots for tracked type `ti`.
//! \~russian Убирает `cnt` занятых слотов элементов для отслеживаемого типа `ti`. //! \~russian Убирает `cnt` занятых слотов элементов для отслеживаемого типа `ti`.

View File

@@ -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,14 +27,14 @@
#ifdef DOXYGEN #ifdef DOXYGEN
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionServer //! \relatesalso PIIntrospectionServer
//! \~\brief //! \~\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 //! \relatesalso PIIntrospectionServer
//! \~\brief //! \~\brief
//! \~english Stop introspection server //! \~english Stop introspection server
@@ -55,7 +54,7 @@ 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 //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Peer-based server that replies to introspection requests for the current process. //! \~english Peer-based server that replies to introspection requests for the current process.
//! \~russian Сервер на основе peer, отвечающий на запросы интроспекции для текущего процесса. //! \~russian Сервер на основе peer, отвечающий на запросы интроспекции для текущего процесса.

View File

@@ -1,9 +1,8 @@
/*! \file piintrospection_threads.h //! \~\file piintrospection_threads.h
* \ingroup Introspection //! \~\ingroup Introspection
* \~\brief //! \~\brief
* \~english Thread introspection helpers //! \~english Thread introspection helpers
* \~russian Вспомогательные средства интроспекции потоков //! \~russian Вспомогательные средства интроспекции потоков
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Introspection module - interface for threads Introspection module - interface for threads
@@ -32,72 +31,72 @@
class PIIntrospectionThreads; class PIIntrospectionThreads;
# define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance()) # define PIINTROSPECTION_THREADS (PIIntrospectionThreadsInterface::instance())
# ifdef DOXYGEN # ifdef DOXYGEN
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Registers creation of thread object `t`. //! \~english Registers creation of thread object `t`.
//! \~russian Регистрирует создание объекта потока `t`. //! \~russian Регистрирует создание объекта потока `t`.
# define PIINTROSPECTION_THREAD_NEW(t) # define PIINTROSPECTION_THREAD_NEW(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Registers destruction of thread object `t`. //! \~english Registers destruction of thread object `t`.
//! \~russian Регистрирует уничтожение объекта потока `t`. //! \~russian Регистрирует уничтожение объекта потока `t`.
# define PIINTROSPECTION_THREAD_DELETE(t) # define PIINTROSPECTION_THREAD_DELETE(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Marks thread `t` as starting. //! \~english Marks thread `t` as starting.
//! \~russian Помечает поток `t` как запускающийся. //! \~russian Помечает поток `t` как запускающийся.
# define PIINTROSPECTION_THREAD_START(t) # define PIINTROSPECTION_THREAD_START(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Marks thread `t` as running. //! \~english Marks thread `t` as running.
//! \~russian Помечает поток `t` как выполняющийся. //! \~russian Помечает поток `t` как выполняющийся.
# define PIINTROSPECTION_THREAD_RUN(t) # define PIINTROSPECTION_THREAD_RUN(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Marks thread `t` as waiting. //! \~english Marks thread `t` as waiting.
//! \~russian Помечает поток `t` как ожидающий. //! \~russian Помечает поток `t` как ожидающий.
# define PIINTROSPECTION_THREAD_WAIT(t) # define PIINTROSPECTION_THREAD_WAIT(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Marks thread `t` as stopped. //! \~english Marks thread `t` as stopped.
//! \~russian Помечает поток `t` как остановленный. //! \~russian Помечает поток `t` как остановленный.
# define PIINTROSPECTION_THREAD_STOP(t) # define PIINTROSPECTION_THREAD_STOP(t)
//! \ingroup Introspection //! \~\ingroup Introspection
//! \relatesalso PIIntrospectionThreadsInterface //! \relatesalso PIIntrospectionThreadsInterface
//! \~\brief //! \~\brief
//! \~english Reports completed run of thread `t` that took `us` microseconds. //! \~english Reports completed run of thread `t` that took `us` microseconds.
//! \~russian Сообщает о завершенном проходе потока `t`, занявшем `us` микросекунд. //! \~russian Сообщает о завершенном проходе потока `t`, занявшем `us` микросекунд.
# define PIINTROSPECTION_THREAD_RUN_DONE(t, us) # define PIINTROSPECTION_THREAD_RUN_DONE(t, us)
# else # 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);
# define PIINTROSPECTION_THREAD_RUN(t) PIINTROSPECTION_THREADS->threadRun(t); # define PIINTROSPECTION_THREAD_RUN(t) PIINTROSPECTION_THREADS->threadRun(t);
# define PIINTROSPECTION_THREAD_WAIT(t) PIINTROSPECTION_THREADS->threadWait(t); # define PIINTROSPECTION_THREAD_WAIT(t) PIINTROSPECTION_THREADS->threadWait(t);
# 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 # endif
//! \ingroup Introspection //! \~\ingroup Introspection
//! \~\brief //! \~\brief
//! \~english Entry point for collecting state and timing statistics of \a PIThread objects. //! \~english Entry point for collecting state and timing statistics of \a PIThread objects.
//! \~russian Точка входа для сбора статистики состояний и времени выполнения объектов \a PIThread. //! \~russian Точка входа для сбора статистики состояний и времени выполнения объектов \a PIThread.
@@ -109,27 +108,27 @@ public:
//! \~english Registers creation of thread object `t`. //! \~english Registers creation of thread object `t`.
//! \~russian Регистрирует создание объекта потока `t`. //! \~russian Регистрирует создание объекта потока `t`.
void threadNew (PIThread * t); void threadNew(PIThread * t);
//! \~english Registers destruction of thread object `t`. //! \~english Registers destruction of thread object `t`.
//! \~russian Регистрирует уничтожение объекта потока `t`. //! \~russian Регистрирует уничтожение объекта потока `t`.
void threadDelete (PIThread * t); void threadDelete(PIThread * t);
//! \~english Updates statistics for thread `t` when it starts. //! \~english Updates statistics for thread `t` when it starts.
//! \~russian Обновляет статистику потока `t` при его запуске. //! \~russian Обновляет статистику потока `t` при его запуске.
void threadStart (PIThread * t); void threadStart(PIThread * t);
//! \~english Updates statistics for thread `t` when its run handler begins. //! \~english Updates statistics for thread `t` when its run handler begins.
//! \~russian Обновляет статистику потока `t`, когда начинается его рабочий проход. //! \~russian Обновляет статистику потока `t`, когда начинается его рабочий проход.
void threadRun (PIThread * t); void threadRun(PIThread * t);
//! \~english Marks thread `t` as waiting for the next run. //! \~english Marks thread `t` as waiting for the next run.
//! \~russian Помечает поток `t` как ожидающий следующего прохода. //! \~russian Помечает поток `t` как ожидающий следующего прохода.
void threadWait (PIThread * t); void threadWait(PIThread * t);
//! \~english Marks thread `t` as stopped. //! \~english Marks thread `t` as stopped.
//! \~russian Помечает поток `t` как остановленный. //! \~russian Помечает поток `t` как остановленный.
void threadStop (PIThread * t); void threadStop(PIThread * t);
//! \~english Updates averaged run time of thread `t` in microseconds. //! \~english Updates averaged run time of thread `t` in microseconds.
//! \~russian Обновляет усредненное время выполнения потока `t` в микросекундах. //! \~russian Обновляет усредненное время выполнения потока `t` в микросекундах.

View File

@@ -29,10 +29,15 @@
#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 device for recording and timed playback of binary records. //! \~\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");
@@ -40,6 +45,7 @@ public:
//! \~english Constructs %PIBinaryLog with default playback and split settings. //! \~english Constructs %PIBinaryLog with default playback and split settings.
//! \~russian Создает %PIBinaryLog со стандартными настройками воспроизведения и разделения файлов. //! \~russian Создает %PIBinaryLog со стандартными настройками воспроизведения и разделения файлов.
explicit PIBinaryLog(); explicit PIBinaryLog();
//! \~english Stops background activity and closes the current log. //! \~english Stops background activity and closes the current log.
//! \~russian Останавливает фоновую активность и закрывает текущий лог. //! \~russian Останавливает фоновую активность и закрывает текущий лог.
virtual ~PIBinaryLog(); virtual ~PIBinaryLog();
@@ -47,18 +53,30 @@ public:
//! \~english Playback modes used by \a PIBinaryLog. //! \~english Playback modes used by \a PIBinaryLog.
//! \~russian Режимы воспроизведения, используемые \a PIBinaryLog. //! \~russian Режимы воспроизведения, используемые \a PIBinaryLog.
enum PlayMode { enum PlayMode {
PlayRealTime /*! \~english Playback follows record timestamps in real time, default mode \~russian Воспроизведение следует временным меткам записей в реальном времени, режим по умолчанию */, PlayRealTime /*! \~english Playback follows record timestamps in real time, default mode \~russian Воспроизведение следует временным
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() и игнорирует временные метки записей */ ,
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() и игнорирует временные метки записей */
,
}; };
//! \~english File splitting modes used while writing logs. //! \~english File splitting modes used while writing logs.
//! \~russian Режимы разделения файлов, используемые при записи логов. //! \~russian Режимы разделения файлов, используемые при записи логов.
enum SplitMode { enum SplitMode {
SplitNone /*! \~english Do not split files, default mode \~russian Не разделять файлы, режим по умолчанию */, SplitNone /*! \~english Do not split files, default mode \~russian Не разделять файлы, режим по умолчанию */,
SplitTime /*! \~english Start a new file when elapsed record time exceeds configured limit \~russian Начинать новый файл, когда накопленное время записей превышает заданный предел */, SplitTime /*! \~english Start a new file when elapsed record time exceeds configured limit \~russian Начинать новый файл, когда
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 Начинать новый файл, когда количество записанных записей превышает заданный предел */ ,
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)
@@ -72,21 +90,27 @@ public:
id = count = 0; id = count = 0;
minimum_size = maximum_size = 0; minimum_size = maximum_size = 0;
} }
//! \~english Record ID described by this entry.
//! \~russian Идентификатор записи, описываемый этой структурой. //! \~english Unique identifier for this record type within the log file.
//! \~russian Уникальный идентификатор для этого типа записи в файле лога.
int id; int id;
//! \~english Number of records with this ID.
//! \~russian Количество записей с этим идентификатором. //! \~english Total number of records with this ID in the log file.
//! \~russian Общее количество записей с этим ID в файле лога.
int count; int count;
//! \~english Minimum payload size among records with this ID.
//! \~russian Минимальный размер данных среди записей с этим идентификатором. //! \~english Size in bytes of the smallest record with this ID.
//! \~russian Размер в байтах самой маленькой записи с этим ID.
int minimum_size; int minimum_size;
//! \~english Maximum payload size among records with this ID.
//! \~russian Максимальный размер данных среди записей с этим идентификатором. //! \~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. //! \~english Timestamp of the first record with this ID.
//! \~russian Временная метка первой записи с этим идентификатором. //! \~russian Метка времени первой записи с этим ID.
PISystemTime start_time; PISystemTime start_time;
//! \~english Timestamp of the last record with this ID. //! \~english Timestamp of the last record with this ID.
//! \~russian Временная метка последней записи с этим идентификатором. //! \~russian Временная метка последней записи с этим идентификатором.
PISystemTime end_time; PISystemTime end_time;
@@ -94,16 +118,24 @@ public:
//! \~english Indexed location of a record inside a log file. //! \~english Indexed location of a record inside a log file.
//! \~russian Индексированное положение записи внутри файла лога. //! \~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. //! \~english Record ID.
//! \~russian Идентификатор записи. //! \~russian Идентификатор записи.
int id; int id;
//! \~english Record payload size in bytes. //! \~english Record payload size in bytes.
//! \~russian Размер данных записи в байтах. //! \~russian Размер данных записи в байтах.
int data_size; int data_size;
//! \~english Byte position of the record header in the file. //! \~english Byte position of the record header in the file.
//! \~russian Позиция заголовка записи в файле в байтах. //! \~russian Позиция заголовка записи в файле в байтах.
llong pos; llong pos;
//! \~english Recorded timestamp. //! \~english Recorded timestamp.
//! \~russian Сохраненная временная метка. //! \~russian Сохраненная временная метка.
PISystemTime timestamp; PISystemTime timestamp;
@@ -113,25 +145,36 @@ public:
//! \~english Summary information about a log file and its indexed record types. //! \~english Summary information about a log file and its indexed record types.
//! \~russian Сводная информация о файле лога и его индексированных типах записей. //! \~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. //! \~english Path to the analyzed log file.
//! \~russian Путь к анализируемому файлу лога. //! \~russian Путь к анализируемому файлу лога.
PIString path; PIString path;
//! \~english Total number of records in the file, or negative error code for invalid logs. //! \~english Total number of records in the file, or negative error code for invalid logs.
//! \~russian Общее количество записей в файле или отрицательный код ошибки для некорректных логов. //! \~russian Общее количество записей в файле или отрицательный код ошибки для некорректных логов.
int records_count = 0; int records_count = 0;
//! \~english File size in bytes. //! \~english File size in bytes.
//! \~russian Размер файла в байтах. //! \~russian Размер файла в байтах.
llong log_size = 0L; llong log_size = 0L;
//! \~english Timestamp of the first record. //! \~english Timestamp of the first record.
//! \~russian Временная метка первой записи. //! \~russian Временная метка первой записи.
PISystemTime start_time; PISystemTime start_time;
//! \~english Timestamp of the last record. //! \~english Timestamp of the last record.
//! \~russian Временная метка последней записи. //! \~russian Временная метка последней записи.
PISystemTime end_time; PISystemTime end_time;
//! \~english Per-ID record statistics. //! \~english Per-ID record statistics.
//! \~russian Статистика записей по идентификаторам. //! \~russian Статистика записей по идентификаторам.
PIMap<int, BinLogRecordInfo> records; PIMap<int, BinLogRecordInfo> records;
//! \~english Custom user header stored in the file header. //! \~english Custom user header stored in the file header.
//! \~russian Пользовательский заголовок, сохраненный в заголовке файла. //! \~russian Пользовательский заголовок, сохраненный в заголовке файла.
PIByteArray user_header; PIByteArray user_header;
@@ -156,6 +199,9 @@ public:
//! \~english Returns default record ID used by \a write(). //! \~english Returns default record ID used by \a write().
//! \~russian Возвращает идентификатор записи по умолчанию, используемый \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; }
//! \~english Returns current playback speed multiplier. //! \~english Returns current playback speed multiplier.
@@ -168,14 +214,23 @@ public:
//! \~english Returns elapsed-time threshold for \a SplitTime mode. //! \~english Returns elapsed-time threshold for \a SplitTime mode.
//! \~russian Возвращает порог накопленного времени для режима \a SplitTime. //! \~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; }
//! \~english Returns size threshold for \a SplitSize mode. //! \~english Returns size threshold for \a SplitSize mode.
//! \~russian Возвращает порог размера для режима \a SplitSize. //! \~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; }
//! \~english Returns record-count threshold for \a SplitCount mode. //! \~english Returns record-count threshold for \a SplitCount mode.
//! \~russian Возвращает порог количества записей для режима \a SplitCount. //! \~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; }
//! \~english Returns whether the first threaded-read record is emitted without initial delay. //! \~english Returns whether the first threaded-read record is emitted without initial delay.
@@ -184,10 +239,16 @@ public:
//! \~english Returns whether index data is collected while writing. //! \~english Returns whether index data is collected while writing.
//! \~russian Возвращает, собираются ли данные индекса во время записи. //! \~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; }
//! \~english Creates or reopens a log file at exact path "path" for writing. //! \~english Creates or reopens a log file at exact path "path" for writing.
//! \~russian Создает или повторно открывает файл лога по точному пути "path" для записи. //! \~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);
//! \~english Sets current \a PlayMode. //! \~english Sets current \a PlayMode.
@@ -204,22 +265,63 @@ public:
//! \~english Sets filename prefix used for newly created log files. //! \~english Sets filename prefix used for newly created log files.
//! \~russian Устанавливает префикс имени файла для вновь создаваемых файлов лога. //! \~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); }
//! \~english Sets default record ID used by \a write(). //! \~english Sets default record ID used by \a write().
//! \~russian Устанавливает идентификатор записи по умолчанию, используемый \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); }
//! \~english Enables immediate delivery of the first record in threaded playback. //! \~english Enables immediate delivery of the first record in threaded playback.
//! \~russian Включает немедленную выдачу первой записи при потоковом воспроизведении. //! \~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); }
//! \~english Enables or disables index collection while writing. //! \~english Enables or disables index collection while writing.
//! \~russian Включает или выключает сбор индекса во время записи. //! \~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);
//! \~english Sets playback speed multiplier and switches mode to \a PlayVariableSpeed. //! \~english Sets playback speed multiplier and switches mode to \a PlayVariableSpeed.
//! \~russian Устанавливает множитель скорости воспроизведения и переключает режим в \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);
@@ -227,6 +329,16 @@ public:
//! \~english Sets fixed delay between records and switches mode to \a PlayStaticDelay. //! \~english Sets fixed delay between records and switches mode to \a PlayStaticDelay.
//! \~russian Устанавливает фиксированную задержку между записями и переключает режим в \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);
@@ -234,10 +346,24 @@ public:
//! \~english Switches playback to \a PlayRealTime. //! \~english Switches playback to \a PlayRealTime.
//! \~russian Переключает воспроизведение в режим \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); }
//! \~english Sets time threshold for file splitting and switches mode to \a SplitTime. //! \~english Sets time threshold for file splitting and switches mode to \a SplitTime.
//! \~russian Устанавливает порог времени для разделения файлов и переключает режим в \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);
@@ -245,6 +371,16 @@ public:
//! \~english Sets size threshold for file splitting and switches mode to \a SplitSize. //! \~english Sets size threshold for file splitting and switches mode to \a SplitSize.
//! \~russian Устанавливает порог размера для разделения файлов и переключает режим в \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);
@@ -252,6 +388,17 @@ public:
//! \~english Sets record-count threshold for file splitting and switches mode to \a SplitCount. //! \~english Sets record-count threshold for file splitting and switches mode to \a SplitCount.
//! \~russian Устанавливает порог количества записей для разделения файлов и переключает режим в \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);
@@ -264,43 +411,134 @@ public:
//! \~english Sets custom path generator used for split files and implicit file creation. //! \~english Sets custom path generator used for split files and implicit file creation.
//! \~russian Устанавливает пользовательский генератор путей, используемый для разделяемых файлов и неявного создания файла. //! \~russian Устанавливает пользовательский генератор путей, используемый для разделяемых файлов и неявного создания файла.
//! \~\details //! \~\details
//! \~english Passing \c nullptr restores the internal generator based on \a logDir(), \a filePrefix() and current time. //! \~english Sets a custom callback function that returns the path for the next log file when using split mode. This overrides the
//! \~russian Передача \c nullptr восстанавливает внутренний генератор на основе \a logDir(), \a filePrefix() и текущего времени. //! internal path generator (logdir() + prefix() + current_time()). To restore the internal generator, set this function to nullptr.
void setFuncGetNewFilePath(std::function<PIString()> f) { f_new_path = f; } //! \~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 = std::move(f); }
//! \~english Writes one record with explicit ID and payload. //! \~english Writes one record with explicit ID and payload.
//! \~russian Записывает одну запись с явным идентификатором и данными. //! \~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()); }
//! \~english Writes one record with explicit ID and payload buffer. //! \~english Writes one record with explicit ID and payload buffer.
//! \~russian Записывает одну запись с явным идентификатором и буфером данных. //! \~russian Записывает одну запись с явным идентификатором и буфером данных.
//! \~\details //! \~\details
//! \~english Returns written payload size, \c 0 while paused, or negative value on error. ID must be greater than zero. //! \~english Returns written payload size, \c 0 while paused, or negative value on error. ID must be greater than zero.
//! \~russian Возвращает размер записанных данных, \c 0 во время паузы или отрицательное значение при ошибке. Идентификатор должен быть больше нуля. //! \~russian Возвращает размер записанных данных, \c 0 во время паузы или отрицательное значение при ошибке. Идентификатор должен быть
//! больше нуля.
int writeBinLog(int id, const void * data, int size); int writeBinLog(int id, const void * data, int size);
//! \~english Writes one record with explicit timestamp. //! \~english Write one RAW record to BinLog file, with ID = id, Timestamp = time
//! \~russian Записывает одну запись с явной временной меткой. //! \~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 Writes one record with explicit timestamp and payload buffer.
//! \~russian Записывает одну запись с явной временной меткой и буфером данных. //! \~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);
//! \~english Returns number of records successfully written in current session. //! \~english Returns number of records successfully written in current session.
//! \~russian Возвращает количество записей, успешно записанных в текущей сессии. //! \~russian Возвращает количество записей, успешно записанных в текущей сессии.
int writeCount() const { return write_count; } int writeCount() const { return write_count; }
//! \~english Reads next record matching "id" from current position. //! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
//! \~russian Читает следующую запись, соответствующую "id", из текущей позиции. //! \~russian Прочитать одну запись из файла BinLog, с ID = id, если id = 0, то будет прочитана любая запись
//! \~\details //! \~\details
//! \~english When "id" is zero, accepts any positive record ID. //! \~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
//! \~russian Если "id" равно нулю, принимает любой положительный идентификатор записи. //! 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);
//! \~english Reads next record matching "id" into caller buffer. //! \~english Read one record from BinLog file, with ID = id, if id = 0 than any id will be readed
//! \~russian Читает следующую запись, соответствующую "id", в буфер вызывающей стороны. //! \~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);
//! \~english Returns current log file size in bytes. //! \~english Returns current log file size in bytes.
@@ -340,6 +578,13 @@ public:
//! \~english Sets custom file header for subsequently created log files. //! \~english Sets custom file header for subsequently created log files.
//! \~russian Устанавливает пользовательский заголовок файла для последовательно создаваемых логов. //! \~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);
//! \~english Returns custom header stored in the currently opened log. //! \~english Returns custom header stored in the currently opened log.
@@ -358,6 +603,10 @@ public:
//! \~english Optional list of record IDs accepted by \a read() and threaded playback. //! \~english Optional list of record IDs accepted by \a read() and threaded playback.
//! \~russian Необязательный список идентификаторов записей, допустимых для \a read() и потокового воспроизведения. //! \~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;
//! \~english Restarts reading and playback from the beginning of the current log. //! \~english Restarts reading and playback from the beginning of the current log.
@@ -366,6 +615,9 @@ public:
//! \~english Returns cached index info when available, otherwise reparses current file info. //! \~english Returns cached index info when available, otherwise reparses current file info.
//! \~russian Возвращает кэшированную информацию индекса, если она есть, иначе заново разбирает информацию текущего файла. //! \~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());
@@ -380,6 +632,14 @@ public:
//! \~english Builds record index for the current log file. //! \~english Builds record index for the current log file.
//! \~russian Строит индекс записей для текущего файла лога. //! \~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();
//! \~english Returns whether the current log has loaded index data. //! \~english Returns whether the current log has loaded index data.
@@ -388,18 +648,51 @@ public:
//! \~english Returns index of the first indexed record at or after "time". //! \~english Returns index of the first indexed record at or after "time".
//! \~russian Возвращает индекс первой индексированной записи в момент "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);
//! \~english Seeks to indexed record number "rindex". //! \~english Seeks to indexed record number "rindex".
//! \~russian Переходит к индексированной записи номер "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);
//! \~english Seeks to the first indexed record at or after "time". //! \~english Seeks to the first indexed record at or after "time".
//! \~russian Переходит к первой индексированной записи в момент "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);
//! \~english Seeks to the first indexed record whose file position is at or after "filepos". //! \~english Seeks to the first indexed record whose file position is at or after "filepos".
//! \~russian Переходит к первой индексированной записи, чья позиция в файле находится в точке "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);
//! \~english Returns current indexed record position, or -1 when not indexed. //! \~english Returns current indexed record position, or -1 when not indexed.
@@ -409,8 +702,18 @@ public:
//! \~english Serializes current index data. //! \~english Serializes current index data.
//! \~russian Сериализует текущие данные индекса. //! \~russian Сериализует текущие данные индекса.
PIByteArray saveIndex() const; PIByteArray saveIndex() const;
//! \~english Loads previously serialized index data for the current readable log. //! \~english Loads previously serialized index data for the current readable log.
//! \~russian Загружает ранее сериализованные данные индекса для текущего читаемого лога. //! \~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
@@ -422,6 +725,7 @@ public:
//! \~\details //! \~\details
//! \~english Default filenames look like \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog". //! \~english Default filenames look like \a filePrefix() + "yyyy_MM_dd__hh_mm_ss.binlog".
//! \~russian Имена файлов по умолчанию имеют вид \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
@@ -430,57 +734,138 @@ public:
//! \fn void fileEnd() //! \fn void fileEnd()
//! \~english Raised when reading reaches the end of file. //! \~english Raised when reading reaches the end of file.
//! \~russian Вызывается, когда чтение достигает конца файла. //! \~russian Вызывается, когда чтение достигает конца файла.
EVENT(fileEnd);
//! \fn void fileError() //! \fn void fileError()
//! \~english Raised when file header validation or file creation fails. //! \~english Raised when file header validation or file creation fails.
//! \~russian Вызывается при ошибке проверки заголовка файла или создания файла. //! \~russian Вызывается при ошибке проверки заголовка файла или создания файла.
EVENT(fileError);
//! \fn void newFile(const PIString & filename) //! \fn void newFile(const PIString & filename)
//! \~english Raised after a new log file is successfully created. //! \~english Raised after a new log file is successfully created.
//! \~russian Вызывается после успешного создания нового файла лога. //! \~russian Вызывается после успешного создания нового файла лога.
EVENT1(newFile, const PIString &, filename);
//! \fn void posChanged(int pos) //! \fn void posChanged(int pos)
//! \~english Raised when current indexed playback position changes. //! \~english Raised when current indexed playback position changes.
//! \~russian Вызывается при изменении текущей индексированной позиции воспроизведения. //! \~russian Вызывается при изменении текущей индексированной позиции воспроизведения.
EVENT1(posChanged, int, pos);
//! \fn void threadedReadRecord(PIByteArray data, int id, PISystemTime time) //! \fn void threadedReadRecord(PIByteArray data, int id, PISystemTime time)
//! \~english Raised after threaded playback emits one record. //! \~english Raised after threaded playback emits one record.
//! \~russian Вызывается после выдачи одной записи потоковым воспроизведением. //! \~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);
//! \~english Parses file at "path" and returns its summary statistics. //! \~english Get binlog info and statistic
//! \~russian Разбирает файл по пути "path" и возвращает его сводную статистику. //! \~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);
//! \~english Creates a new log at "dst" from indexed range of "src". //! \~english Create new binlog from part of "src" with allowed IDs and "from" to "to" file position
//! \~russian Создает новый лог в "dst" из индексированного диапазона "src". //! \~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);
//! \~english Joins sequential split logs from "src" into a single destination log. //! \~english Create new binlog from serial splitted binlogs "src"
//! \~russian Объединяет последовательные разделенные логи из "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:

View File

@@ -1,9 +1,8 @@
/*! \file pican.h //! \~\file pican.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english CAN bus device wrapper //! \~english CAN bus device wrapper
* \~russian Обертка над устройством шины CAN //! \~russian Обертка над устройством шины CAN
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
CAN CAN
@@ -29,7 +28,7 @@
#include "piiodevice.h" #include "piiodevice.h"
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english CAN device based on interface name and frame identifier. //! \~english CAN device based on interface name and frame identifier.
//! \~russian CAN-устройство, настраиваемое именем интерфейса и идентификатором кадра. //! \~russian CAN-устройство, настраиваемое именем интерфейса и идентификатором кадра.
@@ -37,7 +36,7 @@ class PIP_EXPORT PICAN: public PIIODevice {
PIIODEVICE(PICAN, "can"); PIIODEVICE(PICAN, "can");
public: public:
//! \~english Constructs a CAN device for interface "path". //! \~english Constructs a CAN device for interface "path".
//! \~russian Создает CAN-устройство для интерфейса "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);

View File

@@ -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,13 +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 //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Tree-based parser and writer for PIP configuration sources. //! \~english Parser and writer for configuration files with tree structure support
//! \~russian Древовидный парсер и записыватель конфигурационных источников PIP. //! \~russian Разбор и запись конфигурационных файлов с поддержкой древовидной структуры
//! \~\details //! \details
//! \~english Supports dotted paths, INI-style section prefixes, multiline values and \c include entries resolved during parsing. //! \~english
//! \~russian Поддерживает точечные пути, префиксы секций в стиле INI, многострочные значения и записи \c include, разрешаемые при разборе. //! 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;
@@ -91,10 +94,10 @@ public:
class Entry; class Entry;
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english List-like view over a set of configuration entries. //! \~english Branch class - container for Entry objects
//! \~russian Список-представление набора конфигурационных записей. //! \~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;
@@ -104,51 +107,92 @@ public:
friend PICout operator<<(PICout s, const Branch & v); friend PICout operator<<(PICout s, const Branch & v);
public: public:
//! \~english Constructs an empty branch view.
//! \~russian Создает пустое представление ветви.
Branch() { ; } Branch() { ; }
//! \~english Resolves descendant "vname" inside this branch. //! \~\brief
//! \~russian Разрешает потомка "vname" внутри этой ветви. //! \~english Get value from branch by name with default value
//! \~russian Получить значение из ветки по имени со значением по умолчанию
//! \~\details //! \~\details
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided. //! \~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, если указатель передан. //! \~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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \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) //! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
//! \~english Typed overloads of \a getValue() convert "def" to the config string representation before lookup. //! \~english Get entry with name "vname" and default value "def"
//! \~russian Типизированные перегрузки \a getValue() преобразуют "def" в строковое представление конфигурации перед поиском. //! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
//! \~english Returns all leaf descendants reachable from this branch. //! \~english Returns all leaf descendants reachable from this branch.
//! \~russian Возвращает все листовые потомки, достижимые из этой ветви. //! \~russian Возвращает все листовые потомки, достижимые из этой ветви.
Branch allLeaves(); Branch allLeaves();
//! \~english Returns entries in this branch whose names contain "name".
//! \~russian Возвращает записи этой ветви, чьи имена содержат "name". //! \~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. //! \~english Returns only entries in this branch that have no children.
//! \~russian Возвращает только записи этой ветви без дочерних элементов. //! \~russian Возвращает только записи этой ветви без дочерних элементов.
Branch getLeaves(); Branch getLeaves();
//! \~english Returns only entries in this branch that have children. //! \~english Returns only entries in this branch that have children.
//! \~russian Возвращает только записи этой ветви, имеющие дочерние элементы. //! \~russian Возвращает только записи этой ветви, имеющие дочерние элементы.
Branch getBranches(); Branch getBranches();
//! \~english Removes entries whose names do not contain "f". //! \~english Removes entries whose names do not contain "f".
//! \~russian Удаляет записи, чьи имена не содержат "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". //! \~english Returns \b true if any entry in this branch or its descendants has name "name".
//! \~russian Возвращает \b true, если какая-либо запись этой ветви или ее потомков имеет имя "name". //! \~russian Возвращает \b true, если какая-либо запись этой ветви или ее потомков имеет имя "name".
bool isEntryExists(const PIString & name) const { bool isEntryExists(const PIString & name) const {
@@ -156,6 +200,7 @@ public:
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. //! \~english Returns position of entry pointer "e" inside this branch, or -1.
//! \~russian Возвращает позицию указателя на запись "e" в этой ветви или -1. //! \~russian Возвращает позицию указателя на запись "e" в этой ветви или -1.
int indexOf(const Entry * e) { int indexOf(const Entry * e) {
@@ -190,7 +235,7 @@ public:
}; };
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Node of the parsed configuration tree. //! \~english Node of the parsed configuration tree.
//! \~russian Узел разобранного дерева конфигурации. //! \~russian Узел разобранного дерева конфигурации.
@@ -265,16 +310,13 @@ public:
//! \~russian Возвращает встроенный комментарий, сохраненный после метки типа. //! \~russian Возвращает встроенный комментарий, сохраненный после метки типа.
const PIString & comment() const { return _comment; } const PIString & comment() const { return _comment; }
/*! //! \~\brief
* \~\brief //! \~english Returns full dotted name as it appears in the tree.
* \~english Returns full dotted name as it appears in the tree. //! \~russian Возвращает полное точечное имя в дереве.
* \~russian Возвращает полное точечное имя в дереве. //! \~\details
* //! \~english Default placeholder entries always have empty full name.
* \~\details //! \~russian У placeholder-записей по умолчанию полное имя всегда пустое.
* \~english Default placeholder entries always have empty full name. //! \snippet piconfig.cpp fullName
* \~russian У placeholder-записей по умолчанию полное имя всегда пустое.
* \snippet piconfig.cpp fullName
*/
const PIString & fullName() const { return _full_name; } const PIString & fullName() const { return _full_name; }
//! \~english Sets local name to "value" and returns this entry. //! \~english Sets local name to "value" and returns this entry.
@@ -410,35 +452,66 @@ public:
} }
/*! //! \~\brief
* \~\brief //! \~english Get entry with name "vname" and default value "def"
* \~english Resolves descendant "vname" below this entry. //! \~russian Получить запись с именем "vname" и значением по умолчанию "def"
* \~russian Разрешает потомка "vname" ниже этой записи. //! \~\details
* //! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided.
* \~\details //! \~russian Если поиск не удался, возвращает общий внутренний entry со значением "def" и устанавливает \a exists в \b false, если
* \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~english Typed overloads of \a getValue() convert "def" to the stored string form before lookup.
//! \~russian Типизированные перегрузки \a getValue() преобразуют "def" в сохраненную строковую форму перед поиском.
//! \~english Returns direct children whose names contain substring "vname". //! \~english Returns direct children whose names contain substring "vname".
@@ -559,7 +632,8 @@ public:
//! \~russian Разрешает путь верхнего уровня "vname". //! \~russian Разрешает путь верхнего уровня "vname".
//! \~\details //! \~\details
//! \~english If lookup fails, returns a shared default entry filled with "def" and sets \a exists to \b false when provided. //! \~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, если указатель передан. //! \~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);
@@ -567,21 +641,53 @@ 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)
//! \fn Entry & getValue(const PIString & vname, const PIStringList & def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const bool def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const short def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const int def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const long def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const uchar def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const ushort def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const uint def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const ulong def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const float def, bool * exists = 0)
//! \fn Entry & getValue(const PIString & vname, const double def, bool * exists = 0)
//! \~english Typed overloads of \a getValue() convert "def" to the stored string form before lookup.
//! \~russian Типизированные перегрузки \a getValue() преобразуют "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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~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)
//! \~english Returns top-level entries whose names contain substring "vname". //! \~english Returns top-level entries whose names contain substring "vname".
//! \~russian Возвращает записи верхнего уровня, чьи имена содержат подстроку "vname". //! \~russian Возвращает записи верхнего уровня, чьи имена содержат подстроку "vname".
@@ -589,7 +695,8 @@ public:
//! \~english Sets or creates top-level path "name", stores "value", assigns type mark "type" and optionally writes changes immediately. //! \~english Sets or creates top-level path "name", stores "value", assigns type mark "type" and optionally writes changes immediately.
//! \~russian Устанавливает или создает путь верхнего уровня "name", сохраняет "value", назначает метку типа "type" и при необходимости сразу записывает изменения. //! \~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);
//! \~english Stores string list and marks type as "l". //! \~english Stores string list and marks type as "l".
@@ -679,35 +786,45 @@ public:
//! \~english Returns entry name by \a allLeaves() index. //! \~english Returns entry name by \a allLeaves() index.
//! \~russian Возвращает имя записи по индексу в \a allLeaves(). //! \~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. //! \~english Returns entry value by \a allLeaves() index.
//! \~russian Возвращает значение записи по индексу в \a allLeaves(). //! \~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. //! \~english Returns entry type mark by \a allLeaves() index.
//! \~russian Возвращает метку типа записи по индексу в \a allLeaves(). //! \~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. //! \~english Returns entry comment by \a allLeaves() index.
//! \~russian Возвращает комментарий записи по индексу в \a allLeaves(). //! \~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. //! \~english Creates new path "name" when it does not already exist and optionally writes changes immediately.
//! \~russian Создает новый путь "name", если он еще не существует, и при необходимости сразу записывает изменения. //! \~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". //! \~english Renames entry referenced by \a allLeaves() index "number".
//! \~russian Переименовывает запись, на которую ссылается индекс "number" в \a allLeaves(). //! \~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". //! \~english Replaces stored value of entry referenced by \a allLeaves() index "number".
//! \~russian Заменяет сохраненное значение записи, на которую ссылается индекс "number" в \a allLeaves(). //! \~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". //! \~english Replaces type mark of entry referenced by \a allLeaves() index "number".
//! \~russian Заменяет метку типа записи, на которую ссылается индекс "number" в \a allLeaves(). //! \~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". //! \~english Replaces comment of entry referenced by \a allLeaves() index "number".
//! \~russian Заменяет комментарий записи, на которую ссылается индекс "number" в \a allLeaves(). //! \~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. //! \~english Removes entry path "name" and its subtree when needed.
//! \~russian Удаляет путь записи "name" и при необходимости его поддерево. //! \~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". //! \~english Removes entry referenced by \a allLeaves() index "number".
//! \~russian Удаляет запись, на которую ссылается индекс "number" в \a allLeaves(). //! \~russian Удаляет запись, на которую ссылается индекс "number" в \a allLeaves().
void removeEntry(uint number, bool write = true); void removeEntry(uint number, bool write = true);
@@ -805,12 +922,15 @@ private:
#ifdef PIP_STD_IOSTREAM #ifdef PIP_STD_IOSTREAM
//! \~english Writes branch contents to \a std::ostream in tree form. //! \~english Writes branch contents to \a std::ostream in tree form.
//! \~russian Выводит содержимое ветви в \a std::ostream в виде дерева. //! \~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. //! \~english Writes entry value to \a std::ostream.
//! \~russian Выводит значение записи в \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. //! \~english Writes branch contents to \a PICout in tree form.
@@ -821,6 +941,7 @@ inline PICout operator<<(PICout s, const PIConfig::Branch & v) {
s.restoreControls(); s.restoreControls();
return s; return s;
} }
//! \~english Writes entry value, type and comment to \a PICout. //! \~english Writes entry value, type and comment to \a PICout.
//! \~russian Выводит значение, тип и комментарий записи в \a PICout. //! \~russian Выводит значение, тип и комментарий записи в \a PICout.
inline PICout operator<<(PICout s, const PIConfig::Entry & v) { inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
@@ -829,17 +950,17 @@ inline PICout operator<<(PICout s, const PIConfig::Entry & v) {
} }
/*! //! \relatesalso PIConfig
* \relatesalso PIConfig //! \relatesalso PIIODevice
* \relatesalso PIIODevice //! \~\brief
* \~\brief //! \~english Helper for reading device settings from configuration entries.
* \~english Helper for reading device settings from configuration entries. //! \~russian Вспомогательная функция для чтения настроек устройства из записей конфигурации.
* \~russian Вспомогательная функция для чтения настроек устройства из записей конфигурации. //! \~\details
* //! \~english
* \~\details //! Tries to read "name" from parent section \a ep first, then from local section \a em, and falls back to "def" when neither exists.
* \~english 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
* \~russian Сначала пытается прочитать "name" из родительской секции \a ep, затем из локальной секции \a em и возвращает "def", если запись не найдена. //! Сначала пытается прочитать "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);

View File

@@ -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:

View File

@@ -527,6 +527,7 @@ bool PIEthernet::listen(bool threaded) {
listen_threaded = true; listen_threaded = true;
server_bounded = false; server_bounded = false;
server_thread_.start(server_func); server_thread_.start(server_func);
server_thread_.waitForStart();
return true; return true;
} }
listen_threaded = server_bounded = false; listen_threaded = server_bounded = false;

View File

@@ -1,9 +1,8 @@
/*! \file piethernet.h //! \~\file piethernet.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english Ethernet-backed UDP and TCP device //! \~english Ethernet-backed UDP and TCP device
* \~russian Устройство UDP и TCP поверх Ethernet //! \~russian Устройство UDP и TCP поверх Ethernet
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Ethernet, UDP/TCP Broadcast/Multicast Ethernet, UDP/TCP Broadcast/Multicast
@@ -36,7 +35,7 @@ class
#endif #endif
sockaddr; sockaddr;
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english %PIIODevice implementation for UDP sockets, TCP clients and TCP servers. //! \~english %PIIODevice implementation for UDP sockets, TCP clients and TCP servers.
//! \~russian Реализация %PIIODevice для UDP-сокетов, TCP-клиентов и TCP-серверов. //! \~russian Реализация %PIIODevice для UDP-сокетов, TCP-клиентов и TCP-серверов.
@@ -60,14 +59,26 @@ public:
//! \~english Extra socket parameters for %PIEthernet. //! \~english Extra socket parameters for %PIEthernet.
//! \~russian Дополнительные параметры сокета %PIEthernet. //! \~russian Дополнительные параметры сокета %PIEthernet.
enum Parameters { enum Parameters {
ReuseAddress /** \~english Allow rebinding an already bound address; enabled by default \~russian Разрешает повторную привязку уже занятого адреса; включено по умолчанию */ = 0x1, ReuseAddress = 0x1 /** \~english Allow rebinding an already bound address; enabled by default \~russian Разрешает повторную привязку
Broadcast /** \~english Enable broadcast sending; disabled by default \~russian Включает отправку broadcast-пакетов; выключено по умолчанию */ = 0x2, уже занятого адреса; включено по умолчанию */
SeparateSockets /** \~english Use separate sockets for receiving and sending instead of a single one; disabled by default \~russian Использует отдельные сокеты для приема и передачи вместо одного общего; выключено по умолчанию */ ,
= 0x4, Broadcast = 0x2 /** \~english Enable broadcast sending; disabled by default \~russian Включает отправку broadcast-пакетов; выключено
MulticastLoop /** \~english Receive multicast packets sent by the same host; enabled by default \~russian Разрешает получать multicast-пакеты от того же хоста; включено по умолчанию */ = 0x8, по умолчанию */
KeepConnection /** \~english Reconnect TCP connection automatically after disconnect; enabled by default \~russian Автоматически переподключает TCP-соединение после разрыва; включено по умолчанию */ = 0x10, ,
DisonnectOnTimeout /** \~english Disconnect TCP connection when read timeout expires; disabled by default \~russian Разрывает TCP-соединение при истечении таймаута чтения; выключено по умолчанию */ = 0x20, SeparateSockets = 0x4 /** \~english Use separate sockets for receiving and sending instead of a single one; disabled by default
NoDelay /** \~english Enable the TCP no-delay option; disabled by default \~russian Включает опцию TCP no-delay; выключено по умолчанию */ = 0x40 \~russian Использует отдельные сокеты для приема и передачи вместо одного общего; выключено по умолчанию */
,
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. //! \~english Deprecated alias for \a PINetworkAddress.
@@ -289,48 +300,51 @@ public:
return connect(threaded); return connect(threaded);
} }
//! \~english Connects to the TCP server at "addr". //! \~english Connects to the TCP server at "addr". Use only for TCP_Client
//! \~russian Подключается к TCP-серверу по адресу "addr". //! \~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);
} }
//! \~english Returns whether the TCP client is connected. //! \~english Returns whether the TCP client is connected. Use only for TCP_Client
//! \~russian Возвращает, подключен ли TCP-клиент. //! \~russian Возвращает, подключен ли TCP-клиент. Только для TCP_Client
bool isConnected() const { return connected_; } bool isConnected() const { return connected_; }
//! \~english Returns whether the TCP client is currently connecting. //! \~english Returns whether the TCP client is currently connecting. Use only for TCP_Client
//! \~russian Возвращает, выполняется ли сейчас подключение TCP-клиента. //! \~russian Возвращает, выполняется ли сейчас подключение TCP-клиента. Только для TCP_Client
bool isConnecting() const { return connecting_; } bool isConnecting() const { return connecting_; }
//! \~english Starts listening for incoming TCP connections at \a readAddress(). //! \~english Starts listen for incoming TCP connections on address \a readAddress(). Use only for TCP_Server
//! \~russian Начинает принимать входящие TCP-соединения по адресу \a readAddress(). //! \~russian Начинает прослушивание входящих TCP подключений на адресе \a readAddress(). Только для TCP_Server
bool listen(bool threaded = false); bool listen(bool threaded = false);
//! \~english Starts listening for incoming TCP connections at "ip":"port". //! \~english Starts listen for incoming TCP connections on address "ip":"port". Use only for TCP_Server
//! \~russian Начинает принимать входящие TCP-соединения по адресу "ip":"port". //! \~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); }
//! \~english Starts listening for incoming TCP connections at "ip_port". //! \~english Starts listen for incoming TCP connections on address "ip_port". Use only for TCP_Server
//! \~russian Начинает принимать входящие TCP-соединения по адресу "ip_port". //! \~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); }
//! \~english Starts listening for incoming TCP connections at "addr". //! \~english Starts listen for incoming TCP connections on address "addr". Use only for TCP_Server
//! \~russian Начинает принимать входящие TCP-соединения по адресу "addr". //! \~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. //! \~english Stops the background listen loop started with threaded listening.
//! \~russian Останавливает фоновый цикл прослушивания, запущенный в потоковом режиме. //! \~russian Останавливает фоновый цикл прослушивания, запущенный в потоковом режиме.
void stopThreadedListen(); void stopThreadedListen();
//! \~english Returns accepted TCP client by index. //! \~english Returns accepted TCP client by index.
//! \~russian Возвращает принятый TCP-клиент по индексу. //! \~russian Возвращает принятый TCP-клиент по индексу.
PIEthernet * client(int index); PIEthernet * client(int index);
//! \~english Returns the number of accepted TCP clients. //! \~english Returns the number of accepted TCP clients.
//! \~russian Возвращает количество принятых TCP-клиентов. //! \~russian Возвращает количество принятых TCP-клиентов.
int clientsCount() const; int clientsCount() const;
//! \~english Returns all accepted TCP clients. //! \~english Returns all accepted TCP clients.
//! \~russian Возвращает всех принятых TCP-клиентов. //! \~russian Возвращает всех принятых TCP-клиентов.
PIVector<PIEthernet *> clients() const; PIVector<PIEthernet *> clients() const;
@@ -391,20 +405,16 @@ public:
//! \~russian Возвращает дескриптор нативного сокета. //! \~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. //! \~english Flags describing a network interface.
//! \~russian Флаги, описывающие сетевой интерфейс. //! \~russian Флаги, описывающие сетевой интерфейс.
enum InterfaceFlag { enum InterfaceFlag {
ifActive /** \~english Interface is active \~russian Интерфейс активен */ = 0x1, ifActive = 0x1 /** \~english Interface is active \~russian Интерфейс активен */,
ifRunning /** \~english Interface is running \~russian Интерфейс работает */ = 0x2, ifRunning = 0x2 /** \~english Interface is running \~russian Интерфейс работает */,
ifBroadcast /** \~english Interface supports broadcast \~russian Интерфейс поддерживает broadcast */ = 0x4, ifBroadcast = 0x4 /** \~english Interface supports broadcast \~russian Интерфейс поддерживает broadcast */,
ifMulticast /** \~english Interface supports multicast \~russian Интерфейс поддерживает multicast */ = 0x8, ifMulticast = 0x8 /** \~english Interface supports multicast \~russian Интерфейс поддерживает multicast */,
ifLoopback /** \~english Interface is loopback \~russian Интерфейс является loopback */ = 0x10, ifLoopback = 0x10 /** \~english Interface is loopback \~russian Интерфейс является loopback */,
ifPTP /** \~english Interface is point-to-point \~russian Интерфейс работает в режиме point-to-point */ = 0x20 ifPTP = 0x20 /** \~english Interface is point-to-point \~russian Интерфейс работает в режиме point-to-point */
}; };
//! \~english Bitmask of \a InterfaceFlag values. //! \~english Bitmask of \a InterfaceFlag values.
@@ -412,7 +422,7 @@ public:
typedef PIFlags<InterfaceFlag> InterfaceFlags; typedef PIFlags<InterfaceFlag> InterfaceFlags;
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Public descriptor of a system network interface. //! \~english Public descriptor of a system network interface.
//! \~russian Публичное описание системного сетевого интерфейса. //! \~russian Публичное описание системного сетевого интерфейса.
@@ -483,7 +493,7 @@ public:
}; };
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Collection of \a Interface descriptors with lookup helpers. //! \~english Collection of \a Interface descriptors with lookup helpers.
//! \~russian Коллекция описаний \a Interface с методами поиска. //! \~russian Коллекция описаний \a Interface с методами поиска.
@@ -540,41 +550,51 @@ public:
//! \~english Converts a MAC address byte array to text form. //! \~english Converts a MAC address byte array to text form.
//! \~russian Преобразует массив байт MAC-адреса в текстовый вид. //! \~russian Преобразует массив байт MAC-адреса в текстовый вид.
static PIString macFromBytes(const PIByteArray & mac); static PIString macFromBytes(const PIByteArray & mac);
//! \~english Converts a textual MAC address to bytes. //! \~english Converts a textual MAC address to bytes.
//! \~russian Преобразует текстовый MAC-адрес в массив байт. //! \~russian Преобразует текстовый MAC-адрес в массив байт.
static PIByteArray macToBytes(const PIString & mac); static PIByteArray macToBytes(const PIString & mac);
//! \~english Applies network mask "mask" to IPv4 string "ip". //! \~english Applies network mask "mask" to IPv4 string "ip".
//! \~russian Применяет сетевую маску "mask" к строковому IPv4-адресу "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". //! \~english Applies network mask "mask" to address "ip".
//! \~russian Применяет сетевую маску "mask" к адресу "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. //! \~english Calculates broadcast address from IPv4 string and mask.
//! \~russian Вычисляет broadcast-адрес по строковому IPv4-адресу и маске. //! \~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. //! \~english Calculates broadcast address from address and mask.
//! \~russian Вычисляет broadcast-адрес по адресу и маске. //! \~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)
//! \~english Raised when a new TCP client connection is accepted. //! \~english Raised when a new TCP client connection is accepted.
//! \~russian Вызывается при принятии нового TCP-клиентского соединения. //! \~russian Вызывается при принятии нового TCP-клиентского соединения.
EVENT1(newConnection, PIEthernet *, client);
//! \fn void connected() //! \fn void connected()
//! \~english Raised after a successful TCP client connection. //! \~english Raised after a successful TCP client connection.
//! \~russian Вызывается после успешного подключения TCP-клиента. //! \~russian Вызывается после успешного подключения TCP-клиента.
EVENT0(connected);
//! \fn void disconnected(bool withError) //! \fn void disconnected(bool withError)
//! \~english Raised when the TCP connection is closed. //! \~english Raised when the TCP connection is closed.
//! \~russian Вызывается при закрытии TCP-соединения. //! \~russian Вызывается при закрытии TCP-соединения.
EVENT1(disconnected, bool, withError);
//! \} //! \}
//! \ioparams //! \ioparams
//! \{ //! \{
#ifdef DOXYGEN #ifdef DOXYGEN
//! \~english Read IP address, default "" //! \~english Read IP address, default ""
//! \~russian IP-адрес чтения, по умолчанию "" //! \~russian IP-адрес чтения, по умолчанию ""
string ip; string ip;
@@ -602,6 +622,7 @@ public:
//! \~english Multicast TTL, default 1 //! \~english Multicast TTL, default 1
//! \~russian TTL multicast-пакетов, по умолчанию 1 //! \~russian TTL multicast-пакетов, по умолчанию 1
int multicastTTL; int multicastTTL;
#endif #endif
//! \} //! \}

View File

@@ -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;

View File

@@ -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() для начала наблюдения за пинами.
//! \} //! \}

View File

@@ -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_;
}; };

View File

@@ -177,7 +177,7 @@ void PIIODevice::setReopenTimeout(PISystemTime timeout) {
//! после каждого успешного потокового чтения. Метод должен быть //! после каждого успешного потокового чтения. Метод должен быть
//! в формате "bool func(void * data, uchar * readed, int size)" //! в формате "bool func(void * data, uchar * readed, int size)"
void PIIODevice::setThreadedReadSlot(ReadRetFunc func) { void PIIODevice::setThreadedReadSlot(ReadRetFunc func) {
func_read = func; func_read = std::move(func);
} }

View File

@@ -1,9 +1,8 @@
/*! \file piiodevice.h //! \~\file piiodevice.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english Core abstraction for configurable input/output devices //! \~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
@@ -34,7 +33,8 @@
//! \~russian Callback, используемый методом \a setThreadedReadSlot(). //! \~russian Callback, используемый методом \a setThreadedReadSlot().
//! \~\details //! \~\details
//! \~english Receives pointer to data read by the background thread, number of bytes and user data set by \a setThreadedReadData(). //! \~english Receives pointer to data read by the background thread, number of bytes and user data set by \a setThreadedReadData().
//! \~russian Принимает указатель на данные, прочитанные фоновым потоком, количество байт и пользовательские данные, заданные через \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
@@ -83,7 +83,7 @@ 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 Базовый класс устройств ввода/вывода.
@@ -124,19 +124,9 @@ public:
Reliable /*! \~english Channel without data errors or corruptions \~russian Канал без ошибок или повреждений данных */ = 0x02 Reliable /*! \~english Channel without data errors or corruptions \~russian Канал без ошибок или повреждений данных */ = 0x02
}; };
//! \~english Information required to create a device by registered prefix.
//! \~russian Информация, необходимая для создания устройства по зарегистрированному префиксу.
struct FabricInfo { struct FabricInfo {
//! \~english Device prefix used in full-path notation.
//! \~russian Префикс устройства, используемый в полной строке пути.
PIConstChars prefix; PIConstChars prefix;
//! \~english Registered C++ class name.
//! \~russian Зарегистрированное имя класса C++.
PIConstChars classname; PIConstChars classname;
//! \~english Factory function that creates a device instance.
//! \~russian Фабричная функция, создающая экземпляр устройства.
PIIODevice * (*fabricator)() = nullptr; PIIODevice * (*fabricator)() = nullptr;
}; };
@@ -358,14 +348,14 @@ public:
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 Writes at most "max_size" bytes from "data". //! \~english Writes at most "max_size" bytes from "data".
@@ -389,21 +379,21 @@ public:
//! \~english Configures the device from section "section" of file "config_file". //! \~english Configures the device from section "section" of file "config_file".
//! \~russian Настраивает устройство из секции "section" файла "config_file". //! \~russian Настраивает устройство из секции "section" файла "config_file".
//! \~\details //! \~\details
//! \~english If "parent_section" is true, inherited parameters are also read from the parent section. //! \~english
//! \~russian Если "parent_section" равно true, то дополнительные параметры также читаются из родительской секции. //! If "parent_section" is true, inherited parameters are also read from the parent section.
//! \~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 device prefix used in full-path notation. //! \~english Returns device prefix used in full-path notation. \ref PIIODevice_sec7
//! \~russian Возвращает префикс устройства, используемый в полной строке пути. //! \~russian Возвращает префикс устройства, используемый в полной строке пути. \ref PIIODevice_sec7
virtual PIConstChars fullPathPrefix() const { return ""; } virtual PIConstChars fullPathPrefix() const { return ""; }
//! \~english Returns default static device prefix.
//! \~russian Возвращает статический префикс устройства по умолчанию.
static PIConstChars fullPathPrefixS() { return ""; } static PIConstChars fullPathPrefixS() { return ""; }
//! \~english Returns full-path representation of this device. //! \~english Returns full-path representation of this device, \a fullPathPrefix() + "://" + ...
//! \~russian Возвращает полную строку описания этого устройства. //! \~russian Возвращает полную строку описания этого устройства, \a fullPathPrefix() + "://" + ...
PIString constructFullPath() const; PIString constructFullPath() const;
//! \~english Configures the device from full-path parameters. //! \~english Configures the device from full-path parameters.
@@ -418,12 +408,12 @@ public:
//! \~russian Настраивает устройство из \a PIVariantTypes::IODevice. //! \~russian Настраивает устройство из \a PIVariantTypes::IODevice.
void configureFromVariant(const PIVariantTypes::IODevice & d); void configureFromVariant(const PIVariantTypes::IODevice & d);
//! \~english Creates a device by full path and configures it. //! \~english Try to create new device by prefix, configure it with \a configureFromFullPath() and returns it.
//! \~russian Создает устройство по полной строке пути и настраивает его. //! \~russian Пытается создать новое устройство по префиксу, настраивает с помощью \a configureFromFullPath() и возвращает его.
static PIIODevice * createFromFullPath(const PIString & full_path); static PIIODevice * createFromFullPath(const PIString & full_path);
//! \~english Creates a device by variant description and configures it. //! \~english Try to create new device by prefix, configure it with \a configureFromVariant() and returns it.
//! \~russian Создает устройство по variant-описанию и настраивает его. //! \~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". //! \~english Returns normalized full-path representation for "full_path".
@@ -442,28 +432,13 @@ public:
//! \~russian Возвращает имена классов всех зарегистрированных устройств. //! \~russian Возвращает имена классов всех зарегистрированных устройств.
static PIStringList availableClasses(); static PIStringList availableClasses();
//! \~english Registers a device factory for prefix-based creation.
//! \~russian Регистрирует фабрику устройства для создания по префиксу.
static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)()); static void registerDevice(PIConstChars prefix, PIConstChars classname, PIIODevice * (*fabric)());
EVENT_HANDLER(bool, open);
EVENT_HANDLER1(bool, open, const PIString &, _path);
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 Writes memory block "mb" to the device. //! \~english Writes memory block "mb" to the device.
//! \~russian Записывает в устройство блок памяти "mb". //! \~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
//! \{ //! \{
@@ -471,26 +446,32 @@ public:
//! \fn bool open() //! \fn bool open()
//! \~english Opens the device with current path and mode. //! \~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 Opens the 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(DeviceMode mode) //! \fn bool open(DeviceMode mode)
//! \~english Opens the 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, DeviceMode mode) //! \fn bool open(const PIString & path, DeviceMode mode)
//! \~english Opens the 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 Closes the device. //! \~english Closes the device.
//! \~russian Закрывает устройство. //! \~russian Закрывает устройство.
EVENT_HANDLER(bool, close);
//! \fn ssize_t write(PIByteArray data) //! \fn ssize_t write(PIByteArray data)
//! \~english Writes "data" to the device. //! \~english Writes "data" to the device.
//! \~russian Записывает "data" в устройство. //! \~russian Записывает "data" в устройство.
EVENT_HANDLER1(ssize_t, write, PIByteArray, data);
//! \} //! \}
//! \vhandlers //! \vhandlers
@@ -499,6 +480,7 @@ public:
//! \fn void flush() //! \fn void flush()
//! \~english Immediately flushes device buffers. //! \~english Immediately flushes device buffers.
//! \~russian Немедленно сбрасывает буферы устройства. //! \~russian Немедленно сбрасывает буферы устройства.
EVENT_VHANDLER(void, flush) { ; }
//! \} //! \}
//! \events //! \events
@@ -507,40 +489,45 @@ public:
//! \fn void opened() //! \fn void opened()
//! \~english Raised after successful opening. //! \~english Raised after successful opening.
//! \~russian Вызывается после успешного открытия. //! \~russian Вызывается после успешного открытия.
EVENT(opened);
//! \fn void closed() //! \fn void closed()
//! \~english Raised after successful closing. //! \~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 Raised after threaded read receives 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 Raised after threaded write processes 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 the device from "e_main" and optional "e_parent" entries cast to \a PIConfig::Entry*. //! \~english Reimplement to configure the device from "e_main" and optional "e_parent" entries cast to \a PIConfig::Entry*.
//! \~russian Переопределите для настройки устройства из записей "e_main" и необязательной "e_parent", приведённых к \a PIConfig::Entry*. //! \~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.
@@ -567,8 +554,10 @@ protected:
return -2; return -2;
} }
//! \~english Called after threaded read receives data; default implementation calls the external callback set by \a setThreadedReadSlot(). //! \~english Called after threaded read receives data; default implementation calls the external callback set by \a
//! \~russian Вызывается после успешного потокового чтения; по умолчанию вызывает внешний callback, заданный через \a setThreadedReadSlot(). //! 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 build device-specific part of full-path string. Default implementation returns \a path(). //! \~english Reimplement to build device-specific part of full-path string. Default implementation returns \a path().
@@ -576,17 +565,19 @@ protected:
virtual PIString constructFullPathDevice() const { return path(); } virtual PIString constructFullPathDevice() const { return path(); }
//! \~english Reimplement to configure the device from device-specific full-path parameters. Default implementation calls \a setPath(). //! \~english Reimplement to configure the device from device-specific full-path parameters. Default implementation calls \a setPath().
//! \~russian Переопределите для настройки устройства из device-specific параметров полной строки пути. По умолчанию вызывает \a setPath(). //! \~russian Переопределите для настройки устройства из device-specific параметров полной строки пути. По умолчанию вызывает \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 build device-specific variant properties. Default implementation returns \a PIPropertyStorage with "path". //! \~english Reimplement to build device-specific variant properties. Default implementation returns \a PIPropertyStorage with "path".
//! \~russian Переопределите для построения device-specific свойств варианта. По умолчанию возвращает \a PIPropertyStorage со свойством "path". //! \~russian Переопределите для построения device-specific свойств варианта. По умолчанию возвращает \a PIPropertyStorage со свойством
//! "path".
virtual PIPropertyStorage constructVariantDevice() const; virtual PIPropertyStorage constructVariantDevice() const;
//! \~english Reimplement to configure the device from \a PIPropertyStorage. Mode and options are already applied. //! \~english Reimplement to configure the device from \a PIPropertyStorage. Mode and options are already applied.
//! Default implementation applies "path".
//! \~russian Переопределите для настройки устройства из \a PIPropertyStorage. Режим и опции уже применены. //! \~russian Переопределите для настройки устройства из \a PIPropertyStorage. Режим и опции уже применены.
//! \~english Default implementation applies "path". //! Реализация по умолчанию применяет "path".
//! \~russian Реализация по умолчанию применяет "path".
virtual void configureFromVariantDevice(const PIPropertyStorage & d); virtual void configureFromVariantDevice(const PIPropertyStorage & d);
//! \~english Reimplement to react to changed device options. //! \~english Reimplement to react to changed device options.

View File

@@ -1,9 +1,8 @@
/*! \file piiostream.h //! \~\file piiostream.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english Text and binary stream adapters for PIIODevice //! \~english Text and binary stream adapters for PIIODevice
* \~russian Адаптеры текстовых и бинарных потоков для PIIODevice //! \~russian Адаптеры текстовых и бинарных потоков для PIIODevice
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
PIBinaryStream functionality for PIIODevice PIBinaryStream functionality for PIIODevice
@@ -30,13 +29,17 @@
#include "pitextstream.h" #include "pitextstream.h"
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english %PIBinaryStream adapter over a \a PIIODevice. //! \~english %PIBinaryStream adapter over a \a PIIODevice.
//! \~russian Адаптер %PIBinaryStream поверх \a PIIODevice. //! \~russian Адаптер %PIBinaryStream поверх \a PIIODevice.
//! \~\details //! \~\details
//! \~english See \ref iostream for the generic stream API. //! \~english
//! \~russian Общий API потоков описан в \ref iostream. //! 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 Constructs a stream bound to "device". //! \~english Constructs a stream bound to "device".
@@ -76,10 +79,15 @@ private:
}; };
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english %PITextStream adapter over a \a PIIODevice. //! \~english %PITextStream adapter over a \a PIIODevice.
//! \~russian Адаптер %PITextStream поверх \a 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 Constructs a text stream bound to "device". //! \~english Constructs a text stream bound to "device".

View File

@@ -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;

View File

@@ -1,9 +1,8 @@
/*! \file pipeer.h //! \~\file pipeer.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english Peer-to-peer network 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,13 +28,16 @@
#include "pidiagnostics.h" #include "pidiagnostics.h"
#include "piethernet.h" #include "piethernet.h"
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Named network peer built on top of %PIIODevice. //! \~english Named network peer built on top of %PIIODevice.
//! \~russian Именованный сетевой пир, построенный поверх %PIIODevice. //! \~russian Именованный сетевой пир, построенный поверх %PIIODevice.
//! \~\details //! \~\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(). //! \~english
//! \~russian Класс обнаруживает пиры, маршрутизирует пакеты по имени пира и может предоставлять поток trusted-peer через унаследованные \a read() и \a write(). //! 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");
@@ -51,7 +53,7 @@ public:
//! \~russian Уничтожает пиринговый узел. //! \~russian Уничтожает пиринговый узел.
virtual ~PIPeer(); virtual ~PIPeer();
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Public information about a discovered peer. //! \~english Public information about a discovered peer.
//! \~russian Общедоступная информация об обнаруженном пире. //! \~russian Общедоступная информация об обнаруженном пире.
@@ -68,11 +70,12 @@ public:
was_update = false; was_update = false;
_data = 0; _data = 0;
} }
//! \~english Destroys the peer description. //! \~english Destroys the peer description.
//! \~russian Уничтожает описание пира. //! \~russian Уничтожает описание пира.
~PeerInfo() {} ~PeerInfo() {}
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english Network address of a peer endpoint. //! \~english Network address of a peer endpoint.
//! \~russian Сетевой адрес конечной точки пира. //! \~russian Сетевой адрес конечной точки пира.
@@ -114,8 +117,8 @@ public:
//! \~russian Известные адреса пира. //! \~russian Известные адреса пира.
PIVector<PeerAddress> addresses; PIVector<PeerAddress> addresses;
//! \~english Distance in hops from the local peer. //! \~english Distance in hops from the local peer (0 for direct neighbours).
//! \~russian Расстояние в хопах от локального пира. //! \~russian Расстояние в хопах от локального пира (0 для прямых соседей).
int dist; int dist;
//! \~english Names of direct neighbours for this peer. //! \~english Names of direct neighbours for this peer.
@@ -152,10 +155,16 @@ public:
//! \~english Sends byte array "data" to peer "to". //! \~english Sends byte array "data" to peer "to".
//! \~russian Отправляет массив байт "data" пиру "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". //! \~english Sends string "data" to peer "to".
//! \~russian Отправляет строку "data" пиру "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". //! \~english Sends raw buffer to peer "to".
@@ -266,24 +275,24 @@ public:
//! \~russian Возвращает размер следующей буферизованной полезной нагрузки из trusted-peer потока. //! \~russian Возвращает размер следующей буферизованной полезной нагрузки из trusted-peer потока.
ssize_t bytesAvailable() const override; ssize_t bytesAvailable() const override;
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
EVENT1(peerConnectedEvent, const PIString &, name);
EVENT1(peerDisconnectedEvent, const PIString &, name);
//! \events //! \events
//! \{ //! \{
//! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data) //! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data)
//! \~english Raised when payload data is delivered from peer "from". //! \~english Raised when payload data is delivered from peer "from".
//! \~russian Вызывается, когда полезные данные доставлены от пира "from". //! \~russian Вызывается, когда полезные данные доставлены от пира "from".
//! EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
//! \fn void peerConnectedEvent(const PIString & name) //! \fn void peerConnectedEvent(const PIString & name)
//! \~english Raised when a new peer becomes available. //! \~english Raised when a new peer becomes available.
//! \~russian Вызывается, когда становится доступен новый пир. //! \~russian Вызывается, когда становится доступен новый пир.
//! EVENT1(peerConnectedEvent, const PIString &, name);
//! \fn void peerDisconnectedEvent(const PIString & name) //! \fn void peerDisconnectedEvent(const PIString & name)
//! \~english Raised when a known peer disappears from the network. //! \~english Raised when a known peer disappears from the network.
//! \~russian Вызывается, когда известный пир исчезает из сети. //! \~russian Вызывается, когда известный пир исчезает из сети.
EVENT1(peerDisconnectedEvent, const PIString &, name);
//! \} //! \}
// bool lockedEth() const {return eth_mutex.isLocked();} // bool lockedEth() const {return eth_mutex.isLocked();}

View File

@@ -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();

View File

@@ -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:

View File

@@ -1,9 +1,8 @@
/*! \file pispi.h //! \~\file pispi.h
* \ingroup IO //! \~\ingroup IO
* \~\brief //! \~\brief
* \~english SPI device wrapper //! \~english SPI device wrapper
* \~russian Обертка над SPI-устройством //! \~russian Обертка над SPI-устройством
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
SPI SPI
@@ -29,7 +28,7 @@
#include "piiodevice.h" #include "piiodevice.h"
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english SPI device with configurable speed, word size and clock mode. //! \~english SPI device with configurable speed, word size and clock mode.
//! \~russian SPI-устройство с настраиваемыми скоростью, размером слова и режимом тактирования. //! \~russian SPI-устройство с настраиваемыми скоростью, размером слова и режимом тактирования.
@@ -51,20 +50,27 @@ public:
//! \~english SPI mode flags. //! \~english SPI mode flags.
//! \~russian Флаги режима SPI. //! \~russian Флаги режима SPI.
enum Parameters { enum Parameters {
ClockInverse /*! \~english Invert clock polarity \~russian Инвертировать полярность тактового сигнала */ = 0x1, ClockInverse = 0x1 /*! \~english Invert clock polarity \~russian Инвертировать полярность тактового сигнала */,
ClockPhaseShift /*! \~english Shift sampling phase \~russian Сдвинуть фазу выборки */ = 0x2, ClockPhaseShift = 0x2 /*! \~english Shift sampling phase \~russian Сдвинуть фазу выборки */,
}; };
//! \~english Sets SPI clock speed in hertz. //! \~english Sets SPI clock speed in hertz.
//! \~russian Устанавливает частоту SPI в герцах. //! \~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. //! \~english Returns SPI clock speed in hertz.
//! \~russian Возвращает частоту SPI в герцах. //! \~russian Возвращает частоту SPI в герцах.
//! \~\sa setSpeed()
uint speed() const { return spi_speed; } uint speed() const { return spi_speed; }
//! \~english Sets bits per transferred word. //! \~english Sets bits per transferred word.
//! \~russian Устанавливает количество бит в передаваемом слове. //! \~russian Устанавливает количество бит в передаваемом слове.
//! \~\sa bits()
void setBits(uchar bits = 8); void setBits(uchar bits = 8);
//! \~english Returns bits per transferred word. //! \~english Returns bits per transferred word.
@@ -77,14 +83,17 @@ public:
//! \~english Enables or disables a single SPI mode flag. //! \~english Enables or disables a single SPI mode flag.
//! \~russian Включает или выключает отдельный флаг режима SPI. //! \~russian Включает или выключает отдельный флаг режима SPI.
//! \~\sa isParameterSet()
void setParameter(PISPI::Parameters parameter, bool on = true); void setParameter(PISPI::Parameters parameter, bool on = true);
//! \~english Returns whether SPI mode flag "parameter" is enabled. //! \~english Returns whether SPI mode flag "parameter" is enabled.
//! \~russian Возвращает, включен ли флаг режима SPI "parameter". //! \~russian Возвращает, включен ли флаг режима SPI "parameter".
//! \~\sa setParameter()
bool isParameterSet(PISPI::Parameters parameter) const; bool isParameterSet(PISPI::Parameters parameter) const;
//! \~english Returns current SPI mode flags. //! \~english Returns current SPI mode flags.
//! \~russian Возвращает текущие флаги режима SPI. //! \~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(). //! \~english Returns how many received bytes are buffered for \a read().

View File

@@ -1,8 +1,8 @@
/*! \file pitransparentdevice.h /*! \file pitransparentdevice.h
* \ingroup IO * \ingroup IO
* \~\brief * \~\brief
* \~english Loopback-style transparent device * \~english PIIODevice that pass write to read
* \~russian Прозрачное устройство с loopback-поведением * \~russian PIIODevice который транслирует запись на чтение
*/ */
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
@@ -29,7 +29,7 @@
#include "piiodevice.h" #include "piiodevice.h"
//! \ingroup IO //! \~\ingroup IO
//! \~\brief //! \~\brief
//! \~english %PIIODevice that returns written packets through \a read(). //! \~english %PIIODevice that returns written packets through \a read().
//! \~russian %PIIODevice, который возвращает записанные пакеты через \a read(). //! \~russian %PIIODevice, который возвращает записанные пакеты через \a read().

View File

@@ -1,9 +1,8 @@
/*! \file piusb.h //! \~\file piusb.h
* \ingroup USB //! \~\ingroup USB
* \~\brief //! \~\brief
* \~english USB input/output device declarations //! \~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
@@ -62,10 +61,13 @@
struct usb_dev_handle; struct usb_dev_handle;
//! \ingroup USB //! \~\ingroup USB
//! \~\brief //! \~\brief
//! \~english USB implementation of \a PIIODevice. //! \~english USB implementation of \a PIIODevice.
//! \~russian USB-реализация \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");
@@ -78,7 +80,7 @@ public:
//! \~russian Уничтожает обертку USB-устройства. //! \~russian Уничтожает обертку USB-устройства.
virtual ~PIUSB(); virtual ~PIUSB();
//! \ingroup USB //! \~\ingroup USB
//! \~\brief //! \~\brief
//! \~english Parsed USB endpoint descriptor. //! \~english Parsed USB endpoint descriptor.
//! \~russian Разобранный дескриптор USB endpoint. //! \~russian Разобранный дескриптор USB endpoint.
@@ -95,34 +97,35 @@ public:
//! \~english Transfer direction encoded in endpoint address. //! \~english Transfer direction encoded in endpoint address.
//! \~russian Направление передачи, закодированное в адресе endpoint. //! \~russian Направление передачи, закодированное в адресе endpoint.
enum Direction { enum Direction {
Write = 0, /** \~english Host-to-device endpoint \~russian Endpoint от хоста к устройству */ Write = 0 /** \~english Host-to-device endpoint \~russian Endpoint от хоста к устройству */,
Read = 1 /** \~english Device-to-host endpoint \~russian Endpoint от устройства к хосту */ Read = 1 /** \~english Device-to-host endpoint \~russian Endpoint от устройства к хосту */
}; };
//! \~english USB transfer type encoded in endpoint attributes. //! \~english USB transfer type encoded in endpoint attributes.
//! \~russian Тип USB-передачи, закодированный в атрибутах endpoint. //! \~russian Тип USB-передачи, закодированный в атрибутах endpoint.
enum TransferType { enum TransferType {
Control = 0, /** \~english Control endpoint \~russian Control-endpoint */ Control = 0 /** \~english Control endpoint \~russian Control-endpoint */,
Isochronous = 1, /** \~english Isochronous endpoint \~russian Isochronous-endpoint */ Isochronous = 1 /** \~english Isochronous endpoint \~russian Isochronous-endpoint */,
Bulk = 2, /** \~english Bulk endpoint \~russian Bulk-endpoint */ Bulk = 2 /** \~english Bulk endpoint \~russian Bulk-endpoint */,
Interrupt = 3 /** \~english Interrupt endpoint \~russian Interrupt-endpoint */ Interrupt = 3 /** \~english Interrupt endpoint \~russian Interrupt-endpoint */
}; };
//! \~english Synchronisation mode for isochronous endpoints. //! \~english Synchronisation mode for isochronous endpoints.
//! \~russian Режим синхронизации для isochronous-endpoint. //! \~russian Режим синхронизации для isochronous-endpoint.
enum SynchronisationType { enum SynchronisationType {
NoSynchonisation = 0, /** \~english No synchronisation \~russian Без синхронизации */ NoSynchonisation = 0 /** \~english No synchronisation \~russian Без синхронизации */,
Asynchronous = 2, /** \~english Asynchronous synchronisation \~russian Асинхронная синхронизация */ Asynchronous = 2 /** \~english Asynchronous synchronisation \~russian Асинхронная синхронизация */,
Adaptive = 1, /** \~english Adaptive synchronisation \~russian Адаптивная синхронизация */ Adaptive = 1 /** \~english Adaptive synchronisation \~russian Адаптивная синхронизация */,
Synchronous = 3 /** \~english Synchronous synchronisation \~russian Синхронная синхронизация */ Synchronous = 3 /** \~english Synchronous synchronisation \~russian Синхронная синхронизация */
}; };
//! \~english Usage mode for isochronous endpoints. //! \~english Usage mode for isochronous endpoints.
//! \~russian Режим использования для isochronous-endpoint. //! \~russian Режим использования для isochronous-endpoint.
enum UsageType { enum UsageType {
DataEndpoint = 0, /** \~english Data endpoint \~russian Endpoint данных */ DataEndpoint = 0 /** \~english Data endpoint \~russian Endpoint данных */,
FeedbackEndpoint = 2, /** \~english Feedback endpoint \~russian Endpoint обратной связи */ FeedbackEndpoint = 2 /** \~english Feedback endpoint \~russian Endpoint обратной связи */,
ExplicitFeedbackDataEndpoint = 1 /** \~english Explicit feedback data endpoint \~russian Endpoint данных с явной обратной связью */ ExplicitFeedbackDataEndpoint =
1 /** \~english Explicit feedback data endpoint \~russian Endpoint данных с явной обратной связью */
}; };
//! \~english Parses direction and transfer information from \a address and \a attributes. //! \~english Parses direction and transfer information from \a address and \a attributes.
@@ -162,7 +165,7 @@ public:
UsageType usage_type = DataEndpoint; UsageType usage_type = DataEndpoint;
}; };
//! \ingroup USB //! \~\ingroup USB
//! \~\brief //! \~\brief
//! \~english USB interface description with its endpoints. //! \~english USB interface description with its endpoints.
//! \~russian Описание USB-интерфейса и его endpoint. //! \~russian Описание USB-интерфейса и его endpoint.
@@ -192,7 +195,7 @@ public:
PIVector<PIUSB::Endpoint> endpoints; PIVector<PIUSB::Endpoint> endpoints;
}; };
//! \ingroup USB //! \~\ingroup USB
//! \~\brief //! \~\brief
//! \~english USB configuration description with available interfaces. //! \~english USB configuration description with available interfaces.
//! \~russian Описание USB-конфигурации с доступными интерфейсами. //! \~russian Описание USB-конфигурации с доступными интерфейсами.
@@ -226,7 +229,7 @@ public:
PIVector<PIUSB::Interface> interfaces; PIVector<PIUSB::Interface> interfaces;
}; };
//! \ingroup USB //! \~\ingroup USB
//! \~\brief //! \~\brief
//! \~english Top-level USB device descriptor collected during opening. //! \~english Top-level USB device descriptor collected during opening.
//! \~russian Верхнеуровневый USB-дескриптор, собранный при открытии. //! \~russian Верхнеуровневый USB-дескриптор, собранный при открытии.
@@ -401,6 +404,8 @@ protected:
usb_dev_handle * hdev; usb_dev_handle * hdev;
}; };
//! \relatesalso PICout
//! \~english Writes endpoint description to \a PICout. //! \~english Writes endpoint description to \a PICout.
//! \~russian Выводит описание endpoint в \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);

View File

@@ -1,9 +1,8 @@
/*! \file pibasetransfer.h //! \~\file pibasetransfer.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Base class for reliable packet sessions with acknowledgements, 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,14 +28,19 @@
#include "picrc.h" #include "picrc.h"
#include "pidiagnostics.h" #include "pidiagnostics.h"
//! \ingroup IO-Utils
//! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Base transport for reliable fixed-size packet exchange over an external channel. //! \~english Base transport for reliable fixed-size packet exchange over an external channel.
//! \~russian Базовый транспорт для надежного обмена пакетами фиксированного размера через внешний канал. //! \~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. //! \~english Constructs transfer with default packet size, timeout and diagnostics.
//! \~russian Создает передачу с размером пакета, таймаутом и диагностикой по умолчанию. //! \~russian Создает передачу с размером пакета, таймаутом и диагностикой по умолчанию.
@@ -46,7 +50,6 @@ public:
//! \~russian Останавливает активное состояние передачи и встроенную диагностику. //! \~russian Останавливает активное состояние передачи и встроенную диагностику.
~PIBaseTransfer(); ~PIBaseTransfer();
#pragma pack(push, 1) #pragma pack(push, 1)
//! \~english Common header placed before every protocol packet. //! \~english Common header placed before every protocol packet.
//! \~russian Общий заголовок, размещаемый перед каждым пакетом протокола. //! \~russian Общий заголовок, размещаемый перед каждым пакетом протокола.
@@ -116,16 +119,18 @@ public:
void setPause(bool pause_); void setPause(bool pause_);
//! \~english Sets maximum encoded packet size. //! \~english Sets maximum encoded packet size in bytes.
//! \~russian Устанавливает максимальный размер кодированного пакета. //! \~russian Устанавливает максимальный размер кодированного пакета в байтах.
void setPacketSize(int size) { packet_size = size; } void setPacketSize(int size) { packet_size = size; }
//! \~english Returns maximum encoded packet size.
//! \~russian Возвращает максимальный размер кодированного пакета. //! \~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 for start negotiation, acknowledgements and pause recovery. //! \~english Sets session timeout in seconds for start negotiation, acknowledgements and pause recovery.
//! \~russian Устанавливает таймаут сессии для согласования старта, подтверждений и восстановления после паузы. //! \~russian Устанавливает таймаут сессии в секундах для согласования старта, подтверждений и восстановления после паузы.
void setTimeout(double sec); void setTimeout(double sec);
//! \~english Returns session timeout in seconds. //! \~english Returns session timeout in seconds.
//! \~russian Возвращает таймаут сессии в секундах. //! \~russian Возвращает таймаут сессии в секундах.
double timeout() const { return timeout_; } double timeout() const { return timeout_; }
@@ -133,6 +138,7 @@ public:
//! \~english Enables or disables CRC validation for data packets. //! \~english Enables or disables CRC validation for data packets.
//! \~russian Включает или выключает проверку CRC для пакетов данных. //! \~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. //! \~english Returns whether CRC validation is enabled.
//! \~russian Возвращает, включена ли проверка CRC. //! \~russian Возвращает, включена ли проверка CRC.
bool isCRCEnabled() const { return crc_enabled; } bool isCRCEnabled() const { return crc_enabled; }
@@ -140,108 +146,156 @@ public:
//! \~english Returns short textual state of the current session. //! \~english Returns short textual state of the current session.
//! \~russian Возвращает краткое текстовое состояние текущей сессии. //! \~russian Возвращает краткое текстовое состояние текущей сессии.
PIString stateString() const { return state_string; } PIString stateString() const { return state_string; }
//! \~english Returns acknowledgement map for the current session.
//! \~russian Возвращает карту подтверждений для текущей сессии. //! \~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. //! \~english Returns total number of bytes planned for the current session.
//! \~russian Возвращает общее число байтов, запланированных для текущей сессии. //! \~russian Возвращает общее число байтов, запланированных для текущей сессии.
llong bytesAll() const { return bytes_all; } llong bytesAll() const { return bytes_all; }
//! \~english Returns number of bytes already processed in the current session. //! \~english Returns number of bytes already processed in the current session.
//! \~russian Возвращает число байтов, уже обработанных в текущей сессии. //! \~russian Возвращает число байтов, уже обработанных в текущей сессии.
llong bytesCur() const { return bytes_cur; } llong bytesCur() const { return bytes_cur; }
//! \~english Returns live transport diagnostics.
//! \~russian Возвращает текущую диагностику транспорта. //! \~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. //! \~english Returns the packet signature constant used by the protocol.
//! \~russian Возвращает константу сигнатуры пакета, используемую протоколом. //! \~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();
} }
EVENT_HANDLER(void, pause) { setPause(true); }
EVENT_HANDLER(void, resume) { setPause(false); }
EVENT(receiveStarted); //! \~\fn void pause()
EVENT(paused);
EVENT(resumed);
EVENT1(receiveFinished, bool, ok);
EVENT(sendStarted);
EVENT1(sendFinished, bool, ok);
EVENT1(sendRequest, PIByteArray &, data);
//! \handlers
//! \{
//!
//! \fn void received(PIByteArray data)
//! \~english Feeds one encoded packet received from the external transport.
//! \~russian Передает один закодированный пакет, полученный от внешнего транспорта.
//!
//! \fn void stop()
//! \~english Stops both sending and receiving sides of the current session.
//! \~russian Останавливает и отправку, и прием текущей сессии.
//!
//! \fn void pause()
//! \~english Switches current session to paused state. //! \~english Switches current session to paused state.
//! \~russian Переводит текущую сессию в состояние паузы. //! \~russian Переводит текущую сессию в состояние паузы.
//! //! \~\note
//! \fn void resume() //! \~english Triggers the `paused()` signal.
//! \~russian Генерирует событие `paused()`.
EVENT_HANDLER(void, pause) { setPause(true); }
//! \~\fn void resume()
//! \~english Resumes the current paused session. //! \~english Resumes the current paused session.
//! \~russian Продолжает текущую приостановленную сессию. //! \~russian Продолжает текущую приостановленную сессию.
//! //! \~\note
//! \} //! \~english Triggers the `resumed()` signal.
//! \events //! \~russian Генерирует событие `resumed()`.
//! \{ EVENT_HANDLER(void, resume) { setPause(false); }
//!
//! \fn void receiveStarted() //! \~\}
//! \~\events
//! \~\{
//! \~\fn void receiveStarted()
//! \~english Emitted when a receive session is accepted and initialized. //! \~english Emitted when a receive session is accepted and initialized.
//! \~russian Генерируется, когда сессия приема принята и инициализирована. //! \~russian Генерируется, когда сессия приема принята и инициализирована.
//! //! \~\note
//! \fn void paused() //! \~english Triggered by internal logic after receiving a valid `pt_Start` packet.
//! \~russian Генерируется внутренней логикой после получения корректного пакета типа `pt_Start`.
EVENT(receiveStarted);
//! \~\fn void paused()
//! \~english Emitted when the transfer enters paused state. //! \~english Emitted when the transfer enters paused state.
//! \~russian Генерируется, когда передача переходит в состояние паузы. //! \~russian Генерируется, когда передача переходит в состояние паузы.
//! //! \~\note
//! \fn void resumed() //! \~english Triggered when `pause` handler is invoked (e.g., via `setPause(true)` or incoming `pt_Pause`).
//! \~russian Генерируется при вызове обработчика `pause` (например, через `setPause(true)` или получении `pt_Pause`).
EVENT(paused);
//! \~\fn void resumed()
//! \~english Emitted when the transfer leaves paused state. //! \~english Emitted when the transfer leaves paused state.
//! \~russian Генерируется, когда передача выходит из состояния паузы. //! \~russian Генерируется, когда передача выходит из состояния паузы.
//! //! \~\note
//! \fn void receiveFinished(bool ok) //! \~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);
//! \~\fn void receiveFinished(bool ok)
//! \~english Emitted when the receive session finishes with result "ok". //! \~english Emitted when the receive session finishes with result "ok".
//! \~russian Генерируется, когда сессия приема завершается с результатом "ok". //! \~russian Генерируется, когда сессия приема завершается с результатом "ok".
//! //! \~\param ok
//! \fn void sendStarted() //! \~english `true` if all packets were received and verified, `false` on error or interruption.
//! \~russian `true`, если все пакеты получены и проверены, `false` — при ошибке или прерывании.
EVENT1(receiveFinished, bool, ok);
//! \~\fn void sendStarted()
//! \~english Emitted when a prepared send session starts. //! \~english Emitted when a prepared send session starts.
//! \~russian Генерируется при запуске подготовленной сессии отправки. //! \~russian Генерируется при запуске подготовленной сессии отправки.
//! //! \~\note
//! \fn void sendFinished(bool ok) //! \~english Triggered after `buildSession()` and before the first packet is sent.
//! \~russian Генерируется после `buildSession()` и до отправки первого пакета.
EVENT(sendStarted);
//! \~\fn void sendFinished(bool ok)
//! \~english Emitted when the send session finishes with result "ok". //! \~english Emitted when the send session finishes with result "ok".
//! \~russian Генерируется, когда сессия отправки завершается с результатом "ok". //! \~russian Генерируется, когда сессия отправки завершается с результатом "ok".
//! //! \~\param ok
//! \fn void sendRequest(PIByteArray data) //! \~english `true` if all packets were sent and acknowledged, `false` on error or timeout.
//! \~russian `true`, если все пакеты отправлены и подтверждены, `false` — при ошибке или таймауте.
EVENT1(sendFinished, bool, ok);
//! \~\fn void sendRequest(PIByteArray &data)
//! \~english Emitted for every encoded packet that must be written to the external transport. //! \~english Emitted for every encoded packet that must be written to the external transport.
//! \~russian Генерируется для каждого закодированного пакета, который нужно записать во внешний транспорт. //! \~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);
//! \~\}
protected: protected:
//! \~english Builds session packet layout for logical parts in "parts". //! \~english Builds session packet layout for logical parts in "parts".
//! \~russian Формирует раскладку пакетов сессии для логических частей из "parts". //! \~russian Формирует раскладку пакетов сессии для логических частей из "parts".
void buildSession(PIVector<Part> parts); void buildSession(PIVector<Part> parts);
//! \~english Returns payload bytes for one requested logical fragment. //! \~english Returns payload bytes for one requested logical fragment.
//! \~russian Возвращает байты полезной нагрузки для одного запрошенного логического фрагмента. //! \~russian Возвращает байты полезной нагрузки для одного запрошенного логического фрагмента.
virtual PIByteArray buildPacket(Part fi) = 0; virtual PIByteArray buildPacket(Part fi) = 0;
//! \~english Consumes one received logical fragment and optional custom packet header. //! \~english Consumes one received logical fragment and optional custom packet header.
//! \~russian Обрабатывает один принятый логический фрагмент и необязательный пользовательский заголовок пакета. //! \~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. //! \~english Called after a new receive session is accepted and initialized.
//! \~russian Вызывается после принятия и инициализации новой сессии приема. //! \~russian Вызывается после принятия и инициализации новой сессии приема.
virtual void beginReceive() { ; } virtual void beginReceive() { ; }
//! \~english Returns custom header bytes inserted after \a PacketHeader in each data packet.
//! \~russian Возвращает байты пользовательского заголовка, вставляемые после \a PacketHeader в каждом пакете данных. //! \~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. //! \~english Runs the prepared send session until success, failure or cancellation.
//! \~russian Выполняет подготовленную сессию отправки до успеха, ошибки или отмены. //! \~russian Выполняет подготовленную сессию отправки до успеха, ошибки или отмены.
bool send_process(); bool send_process();
@@ -299,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)";

View File

@@ -1,9 +1,8 @@
/*! \file pibroadcast.h //! \~\file pibroadcast.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Multi-interface UDP broadcast, multicast and loopback helper //! \~english Multi-interface UDP broadcast, multicast and loopback helper
* \~russian Вспомогательный класс для UDP broadcast, multicast и loopback на нескольких интерфейсах //! \~russian Вспомогательный класс для UDP broadcast, multicast и loopback на нескольких интерфейсах
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Broadcast for all interfaces, including loopback Broadcast for all interfaces, including loopback
@@ -31,7 +30,7 @@
#include "pip_io_utils_export.h" #include "pip_io_utils_export.h"
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Multi-channel sender and receiver over multicast, broadcast and loopback endpoints. //! \~english Multi-channel sender and receiver over multicast, broadcast and loopback endpoints.
//! \~russian Многоканальный отправитель и приемник через multicast-, broadcast- и loopback-конечные точки. //! \~russian Многоканальный отправитель и приемник через multicast-, broadcast- и loopback-конечные точки.
@@ -44,10 +43,10 @@ public:
//! \~english Transport channels that may be enabled independently. //! \~english Transport channels that may be enabled independently.
//! \~russian Транспортные каналы, которые можно включать независимо. //! \~russian Транспортные каналы, которые можно включать независимо.
enum Channel { enum Channel {
Multicast /** \~english Use multicast addresses \~russian Использовать multicast-адреса */ = 0x01, Multicast = 0x01 /** \~english Use multicast addresses \~russian Использовать multicast-адреса */,
Broadcast /** \~english Use broadcast addresses \~russian Использовать broadcast-адреса */ = 0x02, Broadcast = 0x02 /** \~english Use broadcast addresses \~russian Использовать broadcast-адреса */,
Loopback /** \~english Use loopback addresses \~russian Использовать loopback-адреса */ = 0x04, Loopback = 0x04 /** \~english Use loopback addresses \~russian Использовать loopback-адреса */,
All /** \~english Use all channels \~russian Использовать все каналы */ = 0xFFFF, All = 0xFFFF /** \~english Use all channels \~russian Использовать все каналы */
}; };
//! \~english Bitmask of enabled \a Channel values. //! \~english Bitmask of enabled \a Channel values.
@@ -148,14 +147,13 @@ public:
//! \~russian Отправляет один пакет через все включенные каналы. //! \~russian Отправляет один пакет через все включенные каналы.
void send(const PIByteArray & data); void send(const PIByteArray & data);
EVENT1(receiveEvent, PIByteArray, data);
//! \events //! \events
//! \{ //! \{
//! \fn void receiveEvent(PIByteArray data) //! \fn void receiveEvent(PIByteArray data)
//! \~english Emitted when a packet is received on any active channel. //! \~english Emitted when a packet is received on any active channel.
//! \~russian Генерируется при получении пакета на любом активном канале. //! \~russian Генерируется при получении пакета на любом активном канале.
EVENT1(receiveEvent, PIByteArray, data);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file piconnection.h //! \~\file piconnection.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Connection routing helper built on shared devices and packet filters //! \~english Connection routing helper built on shared devices and packet filters
* \~russian Вспомогательный класс маршрутизации поверх общих устройств и пакетных фильтров //! \~russian Вспомогательный класс маршрутизации поверх общих устройств и пакетных фильтров
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Complex I/O point Complex I/O point
@@ -31,7 +30,7 @@
class PIConfig; class PIConfig;
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Routes data between shared devices, packet extractors, channels and periodic senders. //! \~english Routes data between shared devices, packet extractors, channels and periodic senders.
//! \~russian Маршрутизирует данные между общими устройствами, извлекателями пакетов, каналами и периодическими отправителями. //! \~russian Маршрутизирует данные между общими устройствами, извлекателями пакетов, каналами и периодическими отправителями.
@@ -70,14 +69,16 @@ public:
//! \~english Reconfigures the connection from section "name" of file "config". //! \~english Reconfigures the connection from section "name" of file "config".
//! \~russian Перенастраивает соединение из секции "name" файла "config". //! \~russian Перенастраивает соединение из секции "name" файла "config".
//! \~english Clears current devices, filters, channels and senders before applying the new configuration. //! \~\details
//! \~russian Перед применением новой конфигурации удаляет текущие устройства, фильтры, каналы и отправители. //! \~english \b Warning: all devices, filters and channels removed before configure!
//! \~russian \b Внимание: все устройства, фильтры и каналы удаляются перед настройкой!
bool configureFromConfig(const PIString & config, const PIString & name = PIStringAscii("connection")); bool configureFromConfig(const PIString & config, const PIString & name = PIStringAscii("connection"));
//! \~english Reconfigures the connection from section "name" stored in "string". //! \~english Reconfigures the connection from section "name" stored in "string".
//! \~russian Перенастраивает соединение из секции "name", хранящейся в "string". //! \~russian Перенастраивает соединение из секции "name", хранящейся в "string".
//! \~english Clears current devices, filters, channels and senders before applying the new configuration. //! \~\details
//! \~russian Перед применением новой конфигурации удаляет текущие устройства, фильтры, каналы и отправители. //! \~english \b Warning: all devices, filters and channels removed before configure!
//! \~russian \b Внимание: все устройства, фильтры и каналы удаляются перед настройкой!
bool configureFromString(PIString * string, const PIString & name = PIStringAscii("connection")); bool configureFromString(PIString * string, const PIString & name = PIStringAscii("connection"));
//! \~english Serializes current connection state into one configuration section. //! \~english Serializes current connection state into one configuration section.
@@ -87,8 +88,11 @@ public:
//! \~english Adds device "full_path" to the shared device pool and binds it to this connection. //! \~english Adds device "full_path" to the shared device pool and binds it to this connection.
//! \~russian Добавляет устройство "full_path" в общий пул устройств и привязывает его к этому соединению. //! \~russian Добавляет устройство "full_path" в общий пул устройств и привязывает его к этому соединению.
//! \~english Returns the shared device instance or \c nullptr when creation fails. When "start" is \b true, threaded read starts immediately. //! \~\details
//! \~russian Возвращает общий экземпляр устройства или \c nullptr, если создание не удалось. Если "start" равно \b true, потоковое чтение запускается сразу. //! \~english Returns the shared device instance or \c nullptr when creation fails. When "start" is \b true, threaded read starts
//! immediately.
//! \~russian Возвращает общий экземпляр устройства или \c nullptr, если создание не удалось. Если "start" равно \b true, потоковое
//! чтение запускается сразу.
PIIODevice * addDevice(const PIString & full_path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite, bool start = false); PIIODevice * addDevice(const PIString & full_path, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite, bool start = false);
//! \~english Assigns alias "name" to device "dev" inside this connection. //! \~english Assigns alias "name" to device "dev" inside this connection.
@@ -101,12 +105,14 @@ public:
//! \~english Unbinds device "full_path" from this connection. //! \~english Unbinds device "full_path" from this connection.
//! \~russian Отвязывает устройство "full_path" от этого соединения. //! \~russian Отвязывает устройство "full_path" от этого соединения.
//! \~\details
//! \~english The shared device object is deleted from the pool only when no connections still use it. //! \~english The shared device object is deleted from the pool only when no connections still use it.
//! \~russian Общий объект устройства удаляется из пула только тогда, когда им больше не пользуется ни одно соединение. //! \~russian Общий объект устройства удаляется из пула только тогда, когда им больше не пользуется ни одно соединение.
bool removeDevice(const PIString & full_path); bool removeDevice(const PIString & full_path);
//! \~english Removes all devices currently bound to this connection. //! \~english Removes all devices currently bound to this connection.
//! \~russian Удаляет все устройства, привязанные к этому соединению. //! \~russian Удаляет все устройства, привязанные к этому соединению.
//! \~\details
//! \~english Devices remain in the shared pool while they are still referenced by other connections. //! \~english Devices remain in the shared pool while they are still referenced by other connections.
//! \~russian Устройства остаются в общем пуле, пока на них ссылаются другие соединения. //! \~russian Устройства остаются в общем пуле, пока на них ссылаются другие соединения.
void removeAllDevices(); void removeAllDevices();
@@ -125,8 +131,19 @@ public:
//! \~english Creates or reuses filter "name" and binds source "full_path_name" to it. //! \~english Creates or reuses filter "name" and binds source "full_path_name" to it.
//! \~russian Создает или повторно использует фильтр "name" и привязывает к нему источник "full_path_name". //! \~russian Создает или повторно использует фильтр "name" и привязывает к нему источник "full_path_name".
//! \~english The source may resolve to a device full path, a device alias or another filter. "mode" is used only when a new filter is created. //! \~\details
//! \~russian Источник может ссылаться на полный путь устройства, псевдоним устройства или другой фильтр. "mode" используется только при создании нового фильтра. //! \~english If there is no filter with name "name", connection create new with split mode "mode" and bound
//! to it device "full_path_name" or filter "full_path_name". If filter with name "name" already exists,
//! device "full_path_name" or filter "full_path_name" add to this filter.
//! This function returns PIPacketExtractor * assosiated with this filter.
//! \~russian Если фильтра с именем "name" не существует, соединение создаст новый фильтр с режимом разделения "mode"
//! и привяжет к нему устройство "full_path_name" или фильтр "full_path_name". Если фильтр с именем "name" уже существует,
//! устройство "full_path_name" или фильтр "full_path_name" добавляется к этому фильтру.
//! Эта функция возвращает PIPacketExtractor *, связанный с этим фильтром.
//! \~\note
//! \~english \b Attention! "mode" is altual olny if new filter was created!
//! \~russian \b Внимание! "mode" актуален только если был создан новый фильтр!
//! \~\sa PIPacketExtractor
PIPacketExtractor * PIPacketExtractor *
addFilter(const PIString & name, const PIString & full_path_name, PIPacketExtractor::SplitMode mode = PIPacketExtractor::None); addFilter(const PIString & name, const PIString & full_path_name, PIPacketExtractor::SplitMode mode = PIPacketExtractor::None);
@@ -147,6 +164,7 @@ public:
//! \~english Unbinds source "full_path_name" from filter "name". //! \~english Unbinds source "full_path_name" from filter "name".
//! \~russian Отвязывает источник "full_path_name" от фильтра "name". //! \~russian Отвязывает источник "full_path_name" от фильтра "name".
//! \~\details
//! \~english Removes the filter itself when it no longer has any bound sources. //! \~english Removes the filter itself when it no longer has any bound sources.
//! \~russian Удаляет сам фильтр, когда у него больше не остается привязанных источников. //! \~russian Удаляет сам фильтр, когда у него больше не остается привязанных источников.
bool removeFilter(const PIString & name, const PIString & full_path_name); bool removeFilter(const PIString & name, const PIString & full_path_name);
@@ -181,6 +199,7 @@ public:
//! \~english Adds a routing channel from "name_from" to "name_to". //! \~english Adds a routing channel from "name_from" to "name_to".
//! \~russian Добавляет канал маршрутизации от "name_from" к "name_to". //! \~russian Добавляет канал маршрутизации от "name_from" к "name_to".
//! \~\details
//! \~english Both endpoints may reference a device full path, a device alias or a filter name. //! \~english Both endpoints may reference a device full path, a device alias or a filter name.
//! \~russian Оба конца канала могут ссылаться на полный путь устройства, псевдоним устройства или имя фильтра. //! \~russian Оба конца канала могут ссылаться на полный путь устройства, псевдоним устройства или имя фильтра.
bool addChannel(const PIString & name_from, const PIString & name_to); bool addChannel(const PIString & name_from, const PIString & name_to);
@@ -233,8 +252,21 @@ public:
//! \~english Creates or reuses sender "name" and binds device "full_path_name" to it. //! \~english Creates or reuses sender "name" and binds device "full_path_name" to it.
//! \~russian Создает или повторно использует отправитель "name" и привязывает к нему устройство "full_path_name". //! \~russian Создает или повторно использует отправитель "name" и привязывает к нему устройство "full_path_name".
//! \~english "frequency" is applied when a new sender is created. When "start" is \b true, the timer starts immediately. //! \~\details
//! \~russian "frequency" применяется при создании нового отправителя. Если "start" равно \b true, таймер запускается сразу. //! \~english If there is no sender with name "name", connection create new, bound
//! to it device "full_path_name" and start sender timer with frequency "frequency".
//! If sender with name "name" already exists, device "full_path_name" add to this sender
//! If "start" is true, sender is started immediately. Else, you can start sender with
//! functions \a startSender().
//! \~russian Если отправителя с именем "name" не существует, соединение создаст новый отправитель, привяжет
//! к нему устройство "full_path_name" и запускает таймер отправителя с частотой "frequency".
//! Если отправитель с именем "name" уже существует, устройство "full_path_name" добавляется к этому отправителю
//! Если "start" равно true, отправитель запускается немедленно. В противном случае можно запустить отправителя с помощью
//! функций \a startSender().
//! \~\note
//! \~english \b Attention! "frequency" is actual olny if new sender was created!
//! \~russian \b Внимание! "frequency" актуален только если был создан новый отправитель!
//! \~\sa startSender()
void addSender(const PIString & name, const PIString & full_path_name, float frequency, bool start = false); void addSender(const PIString & name, const PIString & full_path_name, float frequency, bool start = false);
//! \~english Creates or reuses sender "name" and binds device "dev" to it. //! \~english Creates or reuses sender "name" and binds device "dev" to it.
@@ -245,6 +277,9 @@ public:
//! \~english Unbinds device "full_path_name" from sender "name". //! \~english Unbinds device "full_path_name" from sender "name".
//! \~russian Отвязывает устройство "full_path_name" от отправителя "name". //! \~russian Отвязывает устройство "full_path_name" от отправителя "name".
//! \~\details
//! \~english If there is no devices bounded to this sender, it will be removed. Returns if sender was removed.
//! \~russian Если к этому отправителю не привязано устройств, он будет удален. Возвращает успешность удаления отправителя.
bool removeSender(const PIString & name, const PIString & full_path_name); bool removeSender(const PIString & name, const PIString & full_path_name);
//! \~english Unbinds device "dev" from sender "name". //! \~english Unbinds device "dev" from sender "name".
@@ -269,6 +304,7 @@ public:
//! \~english Returns sender timer frequency. //! \~english Returns sender timer frequency.
//! \~russian Возвращает частоту таймера отправителя. //! \~russian Возвращает частоту таймера отправителя.
//! \~\details
//! \~english Returns -1 when the sender does not exist and 0 when it exists but is not running. //! \~english Returns -1 when the sender does not exist and 0 when it exists but is not running.
//! \~russian Возвращает -1, если отправителя не существует, и 0, если он существует, но не запущен. //! \~russian Возвращает -1, если отправителя не существует, и 0, если он существует, но не запущен.
float senderFrequency(const PIString & name) const; float senderFrequency(const PIString & name) const;
@@ -379,8 +415,6 @@ public:
//! \~russian Возвращает, работает ли общий пул устройств в режиме имитации. //! \~russian Возвращает, работает ли общий пул устройств в режиме имитации.
static bool isFakeMode(); static bool isFakeMode();
//! \~english Process-wide pool of shared devices used by %PIConnection.
//! \~russian Глобальный для процесса пул общих устройств, используемый %PIConnection.
class PIP_EXPORT DevicePool: public PIThread { class PIP_EXPORT DevicePool: public PIThread {
PIOBJECT_SUBCLASS(DevicePool, PIThread); PIOBJECT_SUBCLASS(DevicePool, PIThread);
friend void __DevicePool_threadReadDP(void * ddp); friend void __DevicePool_threadReadDP(void * ddp);
@@ -390,45 +424,22 @@ public:
struct DeviceData; struct DeviceData;
public: public:
//! \~english Constructs an empty device pool controller.
//! \~russian Создает пустой контроллер пула устройств.
DevicePool(); DevicePool();
//! \~english Destroys the device pool controller.
//! \~russian Уничтожает контроллер пула устройств.
~DevicePool(); ~DevicePool();
//! \~english Starts internal pool processing if it is not running yet.
//! \~russian Запускает внутреннюю обработку пула, если она еще не выполняется.
void init(); void init();
//! \~english Creates or reuses shared device "fp" for connection "parent".
//! \~russian Создает или повторно использует общее устройство "fp" для соединения "parent".
PIIODevice * PIIODevice *
addDevice(PIConnection * parent, const PIString & fp, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite, bool start = true); addDevice(PIConnection * parent, const PIString & fp, PIIODevice::DeviceMode mode = PIIODevice::ReadWrite, bool start = true);
//! \~english Removes binding between connection "parent" and shared device "fp".
//! \~russian Удаляет привязку между соединением "parent" и общим устройством "fp".
bool removeDevice(PIConnection * parent, const PIString & fp); bool removeDevice(PIConnection * parent, const PIString & fp);
//! \~english Removes every binding owned by connection "parent".
//! \~russian Удаляет все привязки, принадлежащие соединению "parent".
void unboundConnection(PIConnection * parent); void unboundConnection(PIConnection * parent);
//! \~english Returns shared device by normalized full path "fp".
//! \~russian Возвращает общее устройство по нормализованному полному пути "fp".
PIIODevice * device(const PIString & fp) const; PIIODevice * device(const PIString & fp) const;
//! \~english Returns internal bookkeeping for device "d".
//! \~russian Возвращает внутренние служебные данные устройства "d".
DeviceData * deviceData(PIIODevice * d) const; DeviceData * deviceData(PIIODevice * d) const;
//! \~english Returns all connections currently using this pool.
//! \~russian Возвращает все соединения, которые сейчас используют этот пул.
PIVector<PIConnection *> boundedConnections() const; PIVector<PIConnection *> boundedConnections() const;
//! \~english Returns all devices currently stored in this pool.
//! \~russian Возвращает все устройства, которые сейчас хранятся в этом пуле.
PIVector<PIIODevice *> boundedDevices() const; PIVector<PIIODevice *> boundedDevices() const;
//! \~english Returns devices currently bound to connection "parent".
//! \~russian Возвращает устройства, которые сейчас привязаны к соединению "parent".
PIVector<PIIODevice *> boundedDevices(const PIConnection * parent) const; PIVector<PIIODevice *> boundedDevices(const PIConnection * parent) const;
protected: protected:
//! \~english Internal state of one shared device entry.
//! \~russian Внутреннее состояние одной записи общего устройства.
struct PIP_EXPORT DeviceData { struct PIP_EXPORT DeviceData {
DeviceData(): dev(0), rthread(0), started(false) {} DeviceData(): dev(0), rthread(0), started(false) {}
~DeviceData(); ~DeviceData();
@@ -446,9 +457,6 @@ public:
bool fake; bool fake;
}; };
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
EVENT2(packetReceivedEvent, const PIString &, from, const PIByteArray &, data);
EVENT3(qualityChanged, const PIIODevice *, dev, PIDiagnostics::Quality, new_quality, PIDiagnostics::Quality, old_quality);
//! \events //! \events
//! \{ //! \{
@@ -456,14 +464,17 @@ public:
//! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data) //! \fn void dataReceivedEvent(const PIString & from, const PIByteArray & data)
//! \~english Emitted when raw data is received from source "from". //! \~english Emitted when raw data is received from source "from".
//! \~russian Генерируется при получении сырых данных от источника "from". //! \~russian Генерируется при получении сырых данных от источника "from".
EVENT2(dataReceivedEvent, const PIString &, from, const PIByteArray &, data);
//! \fn void packetReceivedEvent(const PIString & from, const PIByteArray & data) //! \fn void packetReceivedEvent(const PIString & from, const PIByteArray & data)
//! \~english Emitted when filter "from" produces a packet. //! \~english Emitted when filter "from" produces a packet.
//! \~russian Генерируется, когда фильтр "from" выдает пакет. //! \~russian Генерируется, когда фильтр "from" выдает пакет.
EVENT2(packetReceivedEvent, const PIString &, from, const PIByteArray &, data);
//! \fn void qualityChanged(const PIIODevice * device, PIDiagnostics::Quality new_quality, PIDiagnostics::Quality old_quality) //! \fn void qualityChanged(const PIIODevice * device, PIDiagnostics::Quality new_quality, PIDiagnostics::Quality old_quality)
//! \~english Emitted when diagnostics quality of "device" changes. //! \~english Emitted when diagnostics quality of "device" changes.
//! \~russian Генерируется при изменении качества диагностики устройства "device". //! \~russian Генерируется при изменении качества диагностики устройства "device".
EVENT3(qualityChanged, const PIIODevice *, dev, PIDiagnostics::Quality, new_quality, PIDiagnostics::Quality, old_quality);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file pidatatransfer.h //! \~\ingroup IO-Utils
* \ingroup IO-Utils //! \~\file pidatatransfer.h
* \~\brief //! \~\brief
* \~english Transfer helper for raw \a PIByteArray payloads over \a PIBaseTransfer //! \~english Class for send and receive PIByteArray via \a PIBaseTransfer
* \~russian Вспомогательный класс передачи сырых данных \a PIByteArray поверх \a PIBaseTransfer //! \~russian Класс для отправки и приема PIByteArray с помощью \a PIBaseTransfer
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Class for send and receive PIByteArray via PIBaseTransfer Class for send and receive PIByteArray via PIBaseTransfer
@@ -29,10 +28,11 @@
#include "pibasetransfer.h" #include "pibasetransfer.h"
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Ready-to-use transfer for one contiguous \a PIByteArray payload. //! \~english Class for send and receive PIByteArray via \a PIBaseTransfer
//! \~russian Готовая передача для одной непрерывной полезной нагрузки \a PIByteArray. //! \~russian Класс для отправки и приема PIByteArray с помощью \a PIBaseTransfer
//! \~\sa PIBaseTransfer
class PIP_EXPORT PIDataTransfer: public PIBaseTransfer { class PIP_EXPORT PIDataTransfer: public PIBaseTransfer {
PIOBJECT_SUBCLASS(PIDataTransfer, PIBaseTransfer); PIOBJECT_SUBCLASS(PIDataTransfer, PIBaseTransfer);
@@ -40,15 +40,20 @@ public:
//! \~english Constructs byte-array transfer. //! \~english Constructs byte-array transfer.
//! \~russian Создает передачу массива байтов. //! \~russian Создает передачу массива байтов.
PIDataTransfer() { ; } PIDataTransfer() { ; }
//! \~english Destroys byte-array transfer.
//! \~russian Уничтожает передачу массива байтов. //! \~english Destructor
//! \~russian Деструктор
~PIDataTransfer() { ; } ~PIDataTransfer() { ; }
//! \~english Sends "ba" as a single logical item through the base transfer session. //! \~english Send data
//! \~russian Отправляет "ba" как один логический элемент через базовую сессию передачи. //! \~russian Отправить данные
bool send(const PIByteArray & ba); bool send(const PIByteArray & ba);
//! \~english Returns the internal byte buffer used for the current or last transfer.
//! \~russian Возвращает внутренний буфер байтов для текущей или последней передачи. //! \~english Get received data
//! \~russian Получить принятые данные
//! \~\note
//! \~english The data will be valid only after the successful completion of receiving \a receiveFinished.
//! \~russian Данные будут валидные только после успешного завершения приёма \a receiveFinished.
const PIByteArray & data() { return data_; } const PIByteArray & data() { return data_; }
private: private:

View File

@@ -1,9 +1,8 @@
/*! \file pidiagnostics.h //! \~\file pidiagnostics.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Connection diagnostics for packet frequency, throughput and receive quality //! \~english Connection quality diagnostics
* \~russian Диагностика соединения для частоты пакетов, пропускной способности и качества приема //! \~russian Диагностика качества связи
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Speed and quality in/out diagnostics Speed and quality in/out diagnostics
@@ -30,10 +29,13 @@
#include "pitimer.h" #include "pitimer.h"
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \brief
//! \~english Rolling diagnostics for packet-based send and receive activity. //! \~english Connection diagnostics for packet frequency, throughput and receive quality
//! \~russian Скользящая диагностика пакетной отправки и приема. //! \~russian Диагностика соединения для частоты пакетов, пропускной способности и качества приема
//! \details
//! \~english This class provides connection quality diagnostics based on packet reception statistics
//! \~russian Класс обеспечивает диагностику качества связи на основе статистики приема пакетов
class PIP_EXPORT PIDiagnostics: public PITimer { class PIP_EXPORT PIDiagnostics: public PITimer {
PIOBJECT_SUBCLASS(PIDiagnostics, PITimer); PIOBJECT_SUBCLASS(PIDiagnostics, PITimer);
friend class PIConnection; friend class PIConnection;
@@ -52,11 +54,13 @@ public:
//! \~english Receive quality estimated from recent packet history. //! \~english Receive quality estimated from recent packet history.
//! \~russian Качество приема, оцениваемое по недавней истории пакетов. //! \~russian Качество приема, оцениваемое по недавней истории пакетов.
enum Quality { enum Quality {
Unknown /** \~english No receive history yet \~russian История приема еще отсутствует */ = 1, Unknown = 1 /** \~english No receive history yet \~russian История приема еще отсутствует */,
Failure /** \~english No correct packets in the recent window \~russian В недавнем окне нет корректных пакетов */ = 2, Failure = 2 /** \~english No correct packets in the recent window \~russian В недавнем окне нет корректных пакетов */,
Bad /** \~english Correct packets are at most 20 percent \~russian Корректных пакетов не более 20 процентов */ = 3, Bad = 3 /** \~english Correct packets are at most 20 percent \~russian Корректных пакетов не более 20 процентов */,
Average /** \~english Correct packets are above 20 and up to 80 percent \~russian Корректных пакетов больше 20 и до 80 процентов */ = 4, Average =
Good /** \~english Correct packets are above 80 percent \~russian Корректных пакетов больше 80 процентов */ = 5 4 /** \~english Correct packets are above 20 and up to 80 percent \~russian Корректных пакетов больше 20 и до 80 процентов */
,
Good = 5 /** \~english Correct packets are above 80 percent \~russian Корректных пакетов больше 80 процентов */
}; };
//! \~english Snapshot of current counters and derived statistics. //! \~english Snapshot of current counters and derived statistics.
@@ -65,48 +69,63 @@ public:
//! \~english Constructs zeroed state with formatted speed strings. //! \~english Constructs zeroed state with formatted speed strings.
//! \~russian Создает обнуленное состояние с отформатированными строками скоростей. //! \~russian Создает обнуленное состояние с отформатированными строками скоростей.
State(); State();
//! \~english Latest receive frequency for the current timer interval. //! \~english Latest receive frequency for the current timer interval.
//! \~russian Последняя частота приема для текущего интервала таймера. //! \~russian Последняя частота приема для текущего интервала таймера.
float immediate_freq = 0.f; float immediate_freq = 0.f;
//! \~english Averaged receive frequency over the disconnect window. //! \~english Averaged receive frequency over the disconnect window.
//! \~russian Усредненная частота приема по окну отключения. //! \~russian Усредненная частота приема по окну отключения.
float integral_freq = 0.f; float integral_freq = 0.f;
//! \~english Number of correct received packets per second. //! \~english Number of correct received packets per second.
//! \~russian Число корректно принятых пакетов в секунду. //! \~russian Число корректно принятых пакетов в секунду.
ullong received_packets_per_sec = 0ull; ullong received_packets_per_sec = 0ull;
//! \~english Total number of correct received packets. //! \~english Total number of correct received packets.
//! \~russian Общее число корректно принятых пакетов. //! \~russian Общее число корректно принятых пакетов.
ullong received_packets = 0ull; ullong received_packets = 0ull;
//! \~english Total number of incorrect received packets. //! \~english Total number of incorrect received packets.
//! \~russian Общее число некорректно принятых пакетов. //! \~russian Общее число некорректно принятых пакетов.
ullong received_packets_wrong = 0ull; ullong received_packets_wrong = 0ull;
//! \~english Number of received bytes per second. //! \~english Number of received bytes per second.
//! \~russian Число принятых байтов в секунду. //! \~russian Число принятых байтов в секунду.
ullong received_bytes_per_sec = 0ull; ullong received_bytes_per_sec = 0ull;
//! \~english Total number of correctly received bytes. //! \~english Total number of correctly received bytes.
//! \~russian Общее число корректно принятых байтов. //! \~russian Общее число корректно принятых байтов.
ullong received_bytes = 0ull; ullong received_bytes = 0ull;
//! \~english Total number of bytes from incorrect packets. //! \~english Total number of bytes from incorrect packets.
//! \~russian Общее число байтов из некорректных пакетов. //! \~russian Общее число байтов из некорректных пакетов.
ullong received_bytes_wrong = 0ull; ullong received_bytes_wrong = 0ull;
//! \~english Number of sent packets per second. //! \~english Number of sent packets per second.
//! \~russian Число отправленных пакетов в секунду. //! \~russian Число отправленных пакетов в секунду.
ullong sended_packets_per_sec = 0ull; ullong sended_packets_per_sec = 0ull;
//! \~english Total number of sent packets. //! \~english Total number of sent packets.
//! \~russian Общее число отправленных пакетов. //! \~russian Общее число отправленных пакетов.
ullong sended_packets = 0ull; ullong sended_packets = 0ull;
//! \~english Number of sent bytes per second. //! \~english Number of sent bytes per second.
//! \~russian Число отправленных байтов в секунду. //! \~russian Число отправленных байтов в секунду.
ullong sended_bytes_per_sec = 0ull; ullong sended_bytes_per_sec = 0ull;
//! \~english Total number of sent bytes. //! \~english Total number of sent bytes.
//! \~russian Общее число отправленных байтов. //! \~russian Общее число отправленных байтов.
ullong sended_bytes = 0ull; ullong sended_bytes = 0ull;
//! \~english Human-readable receive speed string. //! \~english Human-readable receive speed string.
//! \~russian Строка скорости приема в человекочитаемом виде. //! \~russian Строка скорости приема в человекочитаемом виде.
PIString receive_speed; PIString receive_speed;
//! \~english Human-readable send speed string. //! \~english Human-readable send speed string.
//! \~russian Строка скорости отправки в человекочитаемом виде. //! \~russian Строка скорости отправки в человекочитаемом виде.
PIString send_speed; PIString send_speed;
//! \~english Current receive quality category. //! \~english Current receive quality category.
//! \~russian Текущая категория качества приема. //! \~russian Текущая категория качества приема.
PIDiagnostics::Quality quality = PIDiagnostics::Unknown; PIDiagnostics::Quality quality = PIDiagnostics::Unknown;
@@ -143,38 +162,34 @@ public:
PIString sendSpeed() const; PIString sendSpeed() const;
EVENT_HANDLER0(void, start);
EVENT_HANDLER1(void, start, PISystemTime, interval);
EVENT_HANDLER0(void, reset);
EVENT_HANDLER1(void, received, int, size) { received(size, true); }
EVENT_HANDLER2(void, received, int, size, bool, correct);
EVENT_HANDLER1(void, sended, int, size);
EVENT2(qualityChanged, PIDiagnostics::Quality, new_quality, PIDiagnostics::Quality, old_quality);
//! \handlers //! \handlers
//! \{ //! \{
//! \fn void start() //! \fn void start()
//! \~english Starts periodic diagnostics evaluation with the default interval. //! \~english Starts periodic diagnostics evaluation with the default interval.
//! \~russian Запускает периодическую оценку диагностики с интервалом по умолчанию. //! \~russian Запускает периодическую оценку диагностики с интервалом по умолчанию.
EVENT_HANDLER0(void, start);
//! \fn void start(PISystemTime interval) //! \fn void start(PISystemTime interval)
//! \~english Starts periodic diagnostics evaluation with interval "interval". //! \~english Starts periodic diagnostics evaluation with interval "interval".
//! \~russian Запускает периодическую оценку диагностики с интервалом "interval". //! \~russian Запускает периодическую оценку диагностики с интервалом "interval".
EVENT_HANDLER1(void, start, PISystemTime, interval);
//! \fn void reset() //! \fn void reset()
//! \~english Resets counters, rolling history and derived statistics. //! \~english Resets counters, rolling history and derived statistics.
//! \~russian Сбрасывает счетчики, скользящую историю и производные статистики. //! \~russian Сбрасывает счетчики, скользящую историю и производные статистики.
EVENT_HANDLER0(void, reset);
//! \fn void received(int size, bool correct = true) //! \fn void received(int size, bool correct = true)
//! \~english Notifies diagnostics about one received packet of size "size". //! \~english Notifies diagnostics about one received packet of size "size".
//! \~russian Уведомляет диагностику об одном принятом пакете размером "size". //! \~russian Уведомляет диагностику об одном принятом пакете размером "size".
EVENT_HANDLER1(void, received, int, size) { received(size, true); }
EVENT_HANDLER2(void, received, int, size, bool, correct);
//! \fn void sended(int size) //! \fn void sended(int size)
//! \~english Notifies diagnostics about one sent packet of size "size". //! \~english Notifies diagnostics about one sent packet of size "size".
//! \~russian Уведомляет диагностику об одном отправленном пакете размером "size". //! \~russian Уведомляет диагностику об одном отправленном пакете размером "size".
EVENT_HANDLER1(void, sended, int, size);
//! \} //! \}
//! \events //! \events
@@ -183,6 +198,7 @@ public:
//! \fn void qualityChanged(PIDiagnostics::Quality new_quality, PIDiagnostics::Quality old_quality) //! \fn void qualityChanged(PIDiagnostics::Quality new_quality, PIDiagnostics::Quality old_quality)
//! \~english Emitted when receive quality changes from "old_quality" to "new_quality". //! \~english Emitted when receive quality changes from "old_quality" to "new_quality".
//! \~russian Генерируется при изменении качества приема с "old_quality" на "new_quality". //! \~russian Генерируется при изменении качества приема с "old_quality" на "new_quality".
EVENT2(qualityChanged, PIDiagnostics::Quality, new_quality, PIDiagnostics::Quality, old_quality);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file piethutilbase.h //! \~\file piethutilbase.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Base helper for optional crypt layer in IO-Utils transports //! \~english Base helper for optional crypt layer in IO-Utils transports
* \~russian Базовый помощник для необязательного слоя шифрования в транспортах IO-Utils //! \~russian Базовый помощник для необязательного слоя шифрования в транспортах IO-Utils
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Base class for ethernet utils Base class for ethernet utils
@@ -29,7 +28,7 @@
#include "pibytearray.h" #include "pibytearray.h"
#include "pip_io_utils_export.h" #include "pip_io_utils_export.h"
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Base helper that adds optional packet encryption to transport utilities. //! \~english Base helper that adds optional packet encryption to transport utilities.
//! \~russian Базовый помощник, добавляющий необязательное шифрование пакетов в транспортные утилиты. //! \~russian Базовый помощник, добавляющий необязательное шифрование пакетов в транспортные утилиты.
@@ -84,8 +83,12 @@ protected:
//! \~english Decrypts "data" when the crypt layer is enabled. //! \~english Decrypts "data" when the crypt layer is enabled.
//! \~russian Дешифрует "data", если слой шифрования включен. //! \~russian Дешифрует "data", если слой шифрования включен.
//! \~\details //! \~\details
//! \~english Returns empty %PIByteArray when decryption fails. //! \~english
//! \~russian Возвращает пустой %PIByteArray, если дешифрование не удалось. //! Returns decrypted data if layer enabled, otherwise returns unchanged "data". If decryption was unsuccessful returns empty
//! %PIByteArray
//! \~russian
//! Возвращает расшифрованные данные, если слой включен, иначе возвращает неизмененные "data". Если расшифровка неуспешна, возвращает
//! пустой %PIByteArray
PIByteArray decryptData(const PIByteArray & data); PIByteArray decryptData(const PIByteArray & data);
private: private:

View File

@@ -1,9 +1,11 @@
/*! \file pifiletransfer.h //! \~\file pifiletransfer.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Transfer helper for files and directory trees over \a PIBaseTransfer //! \~english Class for sending and receiving files and directories via \a PIBaseTransfer
* \~russian Вспомогательный класс передачи файлов и деревьев каталогов поверх \a PIBaseTransfer //! \~russian Класс для отправки и приема файлов и папок с помощью \a PIBaseTransfer
*/ //! \~\details
//! \~english PIFileTransfer provides functionality for transferring files and directories over a network using PIBaseTransfer protocol
//! \~russian PIFileTransfer предоставляет функциональность для передачи файлов и папок по сети с использованием протокола PIBaseTransfer
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Class for send and receive files and directories via PIBaseTransfer Class for send and receive files and directories via PIBaseTransfer
@@ -31,21 +33,21 @@
#define __PIFILETRANSFER_VERSION 2 #define __PIFILETRANSFER_VERSION 2
//! \ingroup IO-Utils
//! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Two-phase file transfer that first exchanges descriptions and then file contents. //! \~english Class for sending and receiving files and directories via \a PIBaseTransfer
//! \~russian Двухфазная передача файлов, которая сначала обменивается описаниями, а затем содержимым файлов. //! \~russian Класс для отправки и приема файлов и папок с помощью \a PIBaseTransfer
class PIP_EXPORT PIFileTransfer: public PIBaseTransfer { class PIP_EXPORT PIFileTransfer: public PIBaseTransfer {
PIOBJECT_SUBCLASS(PIFileTransfer, PIBaseTransfer); PIOBJECT_SUBCLASS(PIFileTransfer, PIBaseTransfer);
public: public:
//! \~english Constructs file transfer rooted at the current directory for receiving. //! \~english Constructs empty file transfer
//! \~russian Создает файловую передачу с текущим каталогом как корнем приема. //! \~russian Создает пустой transfer файлов
PIFileTransfer(); PIFileTransfer();
//! \~english Stops active work and closes the current file handle. //! \~english Destructor
//! \~russian Останавливает активную работу и закрывает текущий файловый дескриптор. //! \~russian Деструктор
~PIFileTransfer(); ~PIFileTransfer();
@@ -69,6 +71,7 @@ public:
}; };
#pragma pack(push, 1) #pragma pack(push, 1)
//! \~english Custom packet header used by the file-transfer protocol. //! \~english Custom packet header used by the file-transfer protocol.
//! \~russian Пользовательский заголовок пакета, используемый протоколом передачи файлов. //! \~russian Пользовательский заголовок пакета, используемый протоколом передачи файлов.
struct PIP_EXPORT PFTHeader { struct PIP_EXPORT PFTHeader {
@@ -85,14 +88,17 @@ public:
//! \~russian Сырое 32-битное представление сигнатуры и версии. //! \~russian Сырое 32-битное представление сигнатуры и версии.
uint raw_sig; uint raw_sig;
}; };
//! \~english Current transfer step from \a StepType. //! \~english Current transfer step from \a StepType.
//! \~russian Текущий этап передачи из \a StepType. //! \~russian Текущий этап передачи из \a StepType.
int step; // PacketType int step;
//! \~english File-transfer session identifier. //! \~english File-transfer session identifier.
//! \~russian Идентификатор сессии передачи файлов. //! \~russian Идентификатор сессии передачи файлов.
int session_id; int session_id;
//! \~english Returns whether header signature and protocol version are supported.
//! \~russian Возвращает, поддерживаются ли сигнатура заголовка и версия протокола. //! \~english Check if signature is valid
//! \~russian Проверка валидности сигнатуры
bool check_sig() { bool check_sig() {
if (sig[0] != sign[0] || sig[1] != sign[1] || sig[2] != sign[2] || version != __PIFILETRANSFER_VERSION) return false; if (sig[0] != sign[0] || sig[1] != sign[1] || sig[2] != sign[2] || version != __PIFILETRANSFER_VERSION) return false;
return true; return true;
@@ -125,8 +131,10 @@ public:
//! \~english Sets destination directory used for received files. //! \~english Sets destination directory used for received files.
//! \~russian Устанавливает каталог назначения для принимаемых файлов. //! \~russian Устанавливает каталог назначения для принимаемых файлов.
void setDirectory(const PIDir & d) { dir = d; } void setDirectory(const PIDir & d) { dir = d; }
//! \~english Sets destination directory used for received files by path. //! \~english Sets destination directory used for received files by path.
//! \~russian Устанавливает каталог назначения для принимаемых файлов по пути. //! \~russian Устанавливает каталог назначения для принимаемых файлов по пути.
//! \~russian Установить директорию по пути
void setDirectory(const PIString & path) { dir.setDir(path); } void setDirectory(const PIString & path) { dir.setDir(path); }
//! \~english Returns destination directory used for received files. //! \~english Returns destination directory used for received files.
@@ -141,53 +149,55 @@ public:
//! \~english Returns current file path or scanning status string. //! \~english Returns current file path or scanning status string.
//! \~russian Возвращает путь текущего файла или строку состояния сканирования. //! \~russian Возвращает путь текущего файла или строку состояния сканирования.
PIString curFile() const; PIString curFile() const;
//! \~english Returns total size of the current file being processed. //! \~english Returns total size of the current file being processed.
//! \~russian Возвращает общий размер текущего обрабатываемого файла. //! \~russian Возвращает общий размер текущего обрабатываемого файла.
llong bytesFileAll() const { return bytes_file_all; } llong bytesFileAll() const { return bytes_file_all; }
//! \~english Returns processed size of the current file being processed. //! \~english Returns processed size of the current file being processed.
//! \~russian Возвращает уже обработанный объем текущего файла. //! \~russian Возвращает уже обработанный объем текущего файла.
llong bytesFileCur() const { return bytes_file_cur; } llong bytesFileCur() const { return bytes_file_cur; }
//! \~english Returns pointer to the current file status string for bindings.
//! \~russian Возвращает указатель на строку состояния текущего файла для привязок.
const PIString * curFile_ptr() const { return &cur_file_string; }
//! \~english Returns pointer to \a bytesFileAll() for bindings.
//! \~russian Возвращает указатель на \a bytesFileAll() для привязок.
const llong * bytesFileAll_ptr() const { return &bytes_file_all; }
//! \~english Returns pointer to \a bytesFileCur() for bindings.
//! \~russian Возвращает указатель на \a bytesFileCur() для привязок.
const llong * bytesFileCur_ptr() const { return &bytes_file_cur; }
EVENT(receiveFilesStarted); //! \~english Get pointer to current file name
EVENT1(receiveFilesFinished, bool, ok); //! \~russian Получить указатель на имя текущего файла
EVENT(sendFilesStarted); const PIString * curFile_ptr() const { return &cur_file_string; }
EVENT1(sendFilesFinished, bool, ok);
EVENT3(receiveFilesRequest, PIStringList, files, llong, total_bytes, bool *, ok); //! \~english Get pointer to total bytes of current file
//! \~russian Получить указатель на общее количество байт текущего файла
const llong * bytesFileAll_ptr() const { return &bytes_file_all; }
//! \~english Get pointer to current bytes of current file
//! \~russian Получить указатель на текущие байты текущего файла
const llong * bytesFileCur_ptr() const { return &bytes_file_cur; }
//! \events //! \events
//! \{ //! \{
//!
//! \fn void receiveFilesStarted() //! \~\fn void receiveFilesStarted()
//! \~english Emitted when a new incoming file-transfer workflow starts. //! \~english Emitted when a new incoming file-transfer workflow starts.
//! \~russian Генерируется при запуске нового входящего процесса передачи файлов. //! \~russian Генерируется при запуске нового входящего процесса передачи файлов.
//! EVENT(receiveFilesStarted);
//! \fn void receiveFilesFinished(bool ok)
//! \~\fn void receiveFilesFinished(bool ok)
//! \~english Emitted when receiving files finishes with result "ok". //! \~english Emitted when receiving files finishes with result "ok".
//! \~russian Генерируется, когда прием файлов завершается с результатом "ok". //! \~russian Генерируется, когда прием файлов завершается с результатом "ok".
//! EVENT1(receiveFilesFinished, bool, ok);
//! \fn void sendFilesStarted()
//! \~\fn void sendFilesStarted()
//! \~english Emitted when preparing and sending files starts. //! \~english Emitted when preparing and sending files starts.
//! \~russian Генерируется при начале подготовки и отправки файлов. //! \~russian Генерируется при начале подготовки и отправки файлов.
//! EVENT(sendFilesStarted);
//! \fn void sendFilesFinished(bool ok)
//! \~\fn void sendFilesFinished(bool ok)
//! \~english Emitted when sending files finishes with result "ok". //! \~english Emitted when sending files finishes with result "ok".
//! \~russian Генерируется, когда отправка файлов завершается с результатом "ok". //! \~russian Генерируется, когда отправка файлов завершается с результатом "ok".
//! EVENT1(sendFilesFinished, bool, ok);
//! \fn void receiveFilesRequest(PIStringList files, llong total_bytes, bool * ok)
//! \~english //! \~\fn void receiveFilesRequest(PIStringList files, llong total_bytes, bool * ok)
//! Emitted after the description phase so user code can accept or reject the incoming file set. //! \~english Emitted after the description phase so user code can accept or reject the incoming file set.
//! \~russian //! \~russian Генерируется после фазы описания, чтобы пользовательский код мог принять или отклонить входящий набор файлов.
//! Генерируется после фазы описания, чтобы пользовательский код мог принять или отклонить входящий набор файлов. EVENT3(receiveFilesRequest, PIStringList, files, llong, total_bytes, bool *, ok);
//!
//! \} //! \}
private: private:
@@ -213,26 +223,37 @@ private:
EVENT_HANDLER1(void, receive_finished, bool, ok); EVENT_HANDLER1(void, receive_finished, bool, ok);
}; };
//! \~english Binary stream write operator for PFTHeader
//! \~russian Оператор записи в бинарный поток для PFTHeader
BINARY_STREAM_WRITE(PIFileTransfer::PFTHeader) { BINARY_STREAM_WRITE(PIFileTransfer::PFTHeader) {
s << v.raw_sig << v.step << v.session_id; s << v.raw_sig << v.step << v.session_id;
return s; return s;
} }
//! \~english Binary stream read operator for PFTHeader
//! \~russian Оператор чтения из бинарного потока для PFTHeader
BINARY_STREAM_READ(PIFileTransfer::PFTHeader) { BINARY_STREAM_READ(PIFileTransfer::PFTHeader) {
s >> v.raw_sig >> v.step >> v.session_id; s >> v.raw_sig >> v.step >> v.session_id;
return s; return s;
} }
//! \~english Binary stream write operator for PFTFileInfo
//! \~russian Оператор записи в бинарный поток для PFTFileInfo
BINARY_STREAM_WRITE(PIFileTransfer::PFTFileInfo) { BINARY_STREAM_WRITE(PIFileTransfer::PFTFileInfo) {
s << v.dest_path << v.size << v.time_access << v.time_modification << v.flags << v.id_user << v.id_group << v.perm_user.raw s << v.dest_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;
return s; return s;
} }
//! \~english Binary stream read operator for PFTFileInfo
//! \~russian Оператор чтения из бинарного потока для PFTFileInfo
BINARY_STREAM_READ(PIFileTransfer::PFTFileInfo) { BINARY_STREAM_READ(PIFileTransfer::PFTFileInfo) {
s >> v.dest_path >> v.size >> v.time_access >> v.time_modification >> v.flags >> v.id_user >> v.id_group >> v.perm_user.raw >> s >> v.dest_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;
return s; return s;
} }
//! \~\relatesalso PICout
//! \~english Output \a PICout operator for PFTFileInfo
//! \~russian Оператор вывода в \a PICout для PFTFileInfo
inline PICout operator<<(PICout s, const PIFileTransfer::PFTFileInfo & v) { inline PICout operator<<(PICout s, const PIFileTransfer::PFTFileInfo & v) {
s.saveAndSetControls(0); s.saveAndSetControls(0);
s << "FileInfo(\"" << v.dest_path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " " s << "FileInfo(\"" << v.dest_path << "\", " << PIString::readableSize(v.size) << ", " << v.perm_user.toString() << " "

View File

@@ -1,13 +1,12 @@
/*! \file piioutilsmodule.h //! \~\file piioutilsmodule.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Public include header for the IO-Utils module //! \~english Public include header for the IO-Utils module
* \~russian Публичный заголовок подключения модуля IO-Utils //! \~russian Публичный заголовок подключения модуля IO-Utils
* //!
* \~\details //! \~\details
* \~english Includes the public connection, transfer, packing, and parsing utility headers. //! \~english Includes the public connection, transfer, packing, and parsing utility headers.
* \~russian Подключает публичные заголовки соединений, передачи данных, упаковки и утилит разбора. //! \~russian Подключает публичные заголовки соединений, передачи данных, упаковки и утилит разбора.
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Module includes Module includes
@@ -42,14 +41,18 @@
//! //!
//! \~english \par Common //! \~english \par Common
//! \~russian \par Общее //! \~russian \par Общее
//!
//! \~english //! \~english
//! The module combines packet framing, connection helpers, transfer helpers //! The module combines packet framing, connection helpers, transfer helpers
//! and parsing utilities built on top of PIP I/O devices. //! and parsing utilities built on top of PIP I/O devices.
//!
//! \~russian //! \~russian
//! Модуль объединяет пакетирование потока, вспомогательные классы соединений, //! Модуль объединяет пакетирование потока, вспомогательные классы соединений,
//! передачи данных и утилиты разбора поверх устройств ввода-вывода PIP. //! передачи данных и утилиты разбора поверх устройств ввода-вывода PIP.
//! \~russian Заголовочный файл модуля утилит ввода-вывода
//! \details
//! \~english This module provides comprehensive I/O utilities including file transfer, connection management, packet extraction, and
//! diagnostics.
//! \~russian Этот модуль предоставляет комплексные утилиты ввода-вывода, включая передачу файлов, управление подключениями, извлечение
//! пакетов и диагностику.
//! //!
//! \~\authors //! \~\authors
//! \~english //! \~english

View File

@@ -1,9 +1,8 @@
/*! \file pipackedtcp.h //! \~\file pipackedtcp.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Packet-oriented TCP device built on top of %PIStreamPacker //! \~english Packet-oriented TCP device built on top of %PIStreamPacker
* \~russian Пакетно-ориентированное TCP-устройство на основе %PIStreamPacker //! \~russian Пакетно-ориентированное TCP-устройство на основе %PIStreamPacker
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Ethernet, UDP/TCP Broadcast/Multicast Ethernet, UDP/TCP Broadcast/Multicast
@@ -34,10 +33,17 @@
class PIEthernet; class PIEthernet;
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english TCP device wrapper that exposes framed packets through the %PIIODevice API. //! \~english TCP device wrapper that exposes framed packets through the %PIIODevice API.
//! \~russian Обертка над TCP-устройством, предоставляющая кадрированные пакеты через API %PIIODevice. //! \~russian Обертка над TCP-устройством, предоставляющая кадрированные пакеты через API %PIIODevice.
//! \details
//! \~english
//! The %PIPackedTCP class provides a TCP client/server device with automatic data packing/unpacking using PIStreamPacker. It
//! supports both client and server roles with reliable byte-stream transmission over TCP connections.
//! \~russian
//! Класс %PIPackedTCP предоставляет устройство TCP клиент/сервер с автоматической упаковкой/распаковкой данных с использованием
//! PIStreamPacker. Поддерживает обе роли: клиент и сервер с надежной передачей байтовых потоков по TCP соединениям.
class PIP_IO_UTILS_EXPORT PIPackedTCP: public PIIODevice { class PIP_IO_UTILS_EXPORT PIPackedTCP: public PIIODevice {
PIIODEVICE(PIPackedTCP, "ptcp"); PIIODEVICE(PIPackedTCP, "ptcp");
@@ -61,12 +67,12 @@ public:
//! \~russian Устанавливает адрес прослушивания для режима сервера или удаленный адрес для режима клиента. //! \~russian Устанавливает адрес прослушивания для режима сервера или удаленный адрес для режима клиента.
void setAddress(const PINetworkAddress & addr); void setAddress(const PINetworkAddress & addr);
//! \~english Returns whether the underlying TCP side is connected. //! \~english Returns true if the TCP connection is established and active
//! \~russian Возвращает, подключена ли нижележащая TCP-сторона. //! \~russian Возвращает true если TCP соединение установлено и активно
bool isConnected() const; bool isConnected() const;
//! \~english Returns whether the underlying TCP side is establishing connection. //! \~english Returns true if the device is currently attempting to establish a TCP connection
//! \~russian Возвращает, находится ли нижележащая TCP-сторона в процессе подключения. //! \~russian Возвращает true если устройство в данный момент пытается установить TCP соединение
bool isConnecting() const; bool isConnecting() const;
//! \~english Returns configured endpoint address. //! \~english Returns configured endpoint address.
@@ -77,8 +83,6 @@ public:
//! \~russian Возвращает текущую рабочую роль. //! \~russian Возвращает текущую рабочую роль.
Role role() const { return m_role; } Role role() const { return m_role; }
EVENT0(connected);
EVENT0(disconnected);
//! \events //! \events
//! \{ //! \{
@@ -86,10 +90,12 @@ public:
//! \fn void connected() //! \fn void connected()
//! \~english Emitted when client connection becomes ready or a server accepts a client. //! \~english Emitted when client connection becomes ready or a server accepts a client.
//! \~russian Генерируется, когда клиентское подключение готово или сервер принимает клиента. //! \~russian Генерируется, когда клиентское подключение готово или сервер принимает клиента.
EVENT0(connected);
//! \fn void disconnected() //! \fn void disconnected()
//! \~english Emitted when active TCP connection is lost or closed. //! \~english Emitted when active TCP connection is lost or closed.
//! \~russian Генерируется при потере или закрытии активного TCP-соединения. //! \~russian Генерируется при потере или закрытии активного TCP-соединения.
EVENT0(disconnected);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file pipacketextractor.h //! \~\file pipacketextractor.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Packet extraction helper for byte-stream devices //! \~english Packet extraction helper for byte-stream devices
* \~russian Вспомогательный класс выделения пакетов для потоковых устройств //! \~russian Вспомогательный класс выделения пакетов для потоковых устройств
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Packets extractor Packets extractor
@@ -28,32 +27,33 @@
#include "piiodevice.h" #include "piiodevice.h"
//! \~english Callback for header validation and payload size detection. Receives source header, received header and header size. Returns payload size or -1 when the header does not match.
//! \~russian Callback для проверки заголовка и определения размера полезной нагрузки. Принимает ожидаемый заголовок, полученный заголовок и размер заголовка. Возвращает размер полезной нагрузки или -1, если заголовок не совпал. //! \~english Callback for header validation and payload size detection. Receives source header, received header and header size. Returns
//! payload size or -1 when the header does not match.
//! \~russian Callback для проверки заголовка и определения размера полезной нагрузки. Принимает ожидаемый заголовок, полученный заголовок и
//! размер заголовка. Возвращает размер полезной нагрузки или -1, если заголовок не совпал.
typedef std::function<int(const uchar *, const uchar *, int)> PacketExtractorHeaderFunc; typedef std::function<int(const uchar *, const uchar *, int)> PacketExtractorHeaderFunc;
//! \~english Callback for payload validation. Receives payload pointer and payload size. Returns \b true when the payload should be accepted. //! \~english Callback for payload validation. Receives payload pointer and payload size. Returns \b true when the payload should be
//! \~russian Callback для проверки полезной нагрузки. Принимает указатель на полезную нагрузку и ее размер. Возвращает \b true, если нагрузка должна быть принята. //! accepted.
//! \~russian Callback для проверки полезной нагрузки. Принимает указатель на полезную нагрузку и ее размер. Возвращает \b true, если
//! нагрузка должна быть принята.
typedef std::function<bool(const uchar *, int)> PacketExtractorPayloadFunc; typedef std::function<bool(const uchar *, int)> PacketExtractorPayloadFunc;
//! \~english Callback for footer validation. Receives source footer, received footer and footer size. Returns \b true when the footer matches. //! \~english Callback for footer validation. Receives source footer, received footer and footer size. Returns \b true when the footer
//! \~russian Callback для проверки конца пакета. Принимает ожидаемое окончание пакета, полученное окончание и размер окончания. Возвращает \b true, если окончание совпало. //! matches.
//! \~russian Callback для проверки конца пакета. Принимает ожидаемое окончание пакета, полученное окончание и размер окончания. Возвращает
//! \b true, если окончание совпало.
typedef std::function<bool(const uchar *, const uchar *, int)> PacketExtractorFooterFunc; typedef std::function<bool(const uchar *, const uchar *, int)> PacketExtractorFooterFunc;
//! \ingroup IO-Utils
//! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Extracts packets from data produced by a child %PIIODevice. //! \~english Extracts packets from data produced by a child %PIIODevice.
//! \~russian Выделяет пакеты из данных, поступающих от дочернего %PIIODevice. //! \~russian Выделяет пакеты из данных, поступающих от дочернего %PIIODevice.
//! //! \details
//! \~\details //! \~english The PIPacketExtractor class provides packet recognition from data stream using various algorithms.
//! \~english //! \~russian Класс PIPacketExtractor предоставляет распознавание пакетов из потока данных с использованием различных алгоритмов.
//! The extractor forwards read and write operations to the assigned child
//! device and applies one of several packet-splitting strategies to incoming
//! bytes before emitting \a packetReceived().
//! \~russian
//! Извлекатель перенаправляет операции чтения и записи назначенному дочернему
//! устройству и применяет одну из стратегий разбиения к входящему потоку байтов
//! перед генерацией \a packetReceived().
class PIP_EXPORT PIPacketExtractor: public PIIODevice { class PIP_EXPORT PIPacketExtractor: public PIIODevice {
PIIODEVICE(PIPacketExtractor, "pckext"); PIIODEVICE(PIPacketExtractor, "pckext");
friend class PIConnection; friend class PIConnection;
@@ -64,11 +64,18 @@ public:
//! \~russian Режимы выделения пакетов. //! \~russian Режимы выделения пакетов.
enum SplitMode { enum SplitMode {
None /** \~english Accept every read chunk as a packet \~russian Считать каждый прочитанный блок отдельным пакетом */, None /** \~english Accept every read chunk as a packet \~russian Считать каждый прочитанный блок отдельным пакетом */,
Header /** \~english Search for \a header() and use configured payload size or callback result \~russian Искать \a header() и использовать настроенный размер полезной нагрузки или результат callback */, Header /** \~english Search for \a header() and use configured payload size or callback result \~russian Искать \a header() и
Footer /** \~english Use fixed payload size and validate trailing \a footer() \~russian Использовать фиксированный размер полезной нагрузки и проверять завершающий \a footer() */, использовать настроенный размер полезной нагрузки или результат callback */
HeaderAndFooter /** \~english Search for packets bounded by \a header() and \a footer() \~russian Искать пакеты, ограниченные \a header() и \a footer() */, ,
Footer /** \~english Use fixed payload size and validate trailing \a footer() \~russian Использовать фиксированный размер полезной
нагрузки и проверять завершающий \a footer() */
,
HeaderAndFooter /** \~english Search for packets bounded by \a header() and \a footer() \~russian Искать пакеты, ограниченные \a
header() и \a footer() */
,
Size /** \~english Treat \a payloadSize() as full packet size \~russian Использовать \a payloadSize() как полный размер пакета */, Size /** \~english Treat \a payloadSize() as full packet size \~russian Использовать \a payloadSize() как полный размер пакета */,
Timeout /** \~english Collect bytes until \a timeout() expires after the first read \~russian Накопить байты до истечения \a timeout() после первого чтения */ Timeout /** \~english Collect bytes until \a timeout() expires after the first read \~russian Накопить байты до истечения \a
timeout() после первого чтения */
}; };
@@ -96,15 +103,15 @@ public:
//! \~english Sets custom header validation callback. //! \~english Sets custom header validation callback.
//! \~russian Устанавливает пользовательский callback проверки заголовка. //! \~russian Устанавливает пользовательский callback проверки заголовка.
void setHeaderCheckSlot(PacketExtractorHeaderFunc f) { func_header = f; } void setHeaderCheckSlot(PacketExtractorHeaderFunc f) { func_header = std::move(f); }
//! \~english Sets custom payload validation callback. //! \~english Sets custom payload validation callback.
//! \~russian Устанавливает пользовательский callback проверки полезной нагрузки. //! \~russian Устанавливает пользовательский callback проверки полезной нагрузки.
void setPayloadCheckSlot(PacketExtractorPayloadFunc f) { func_payload = f; } void setPayloadCheckSlot(PacketExtractorPayloadFunc f) { func_payload = std::move(f); }
//! \~english Sets custom footer validation callback. //! \~english Sets custom footer validation callback.
//! \~russian Устанавливает пользовательский callback проверки окончания пакета. //! \~russian Устанавливает пользовательский callback проверки окончания пакета.
void setFooterCheckSlot(PacketExtractorFooterFunc f) { func_footer = f; } void setFooterCheckSlot(PacketExtractorFooterFunc f) { func_footer = std::move(f); }
//! \~english Switches packet extraction to mode "mode". //! \~english Switches packet extraction to mode "mode".
@@ -165,7 +172,6 @@ public:
//! \~russian Генерирует \a packetReceived(), когда распознан полный пакет. //! \~russian Генерирует \a packetReceived(), когда распознан полный пакет.
void appendData(const PIByteArray & data) { threadedRead(data.data(), data.size_s()); } void appendData(const PIByteArray & data) { threadedRead(data.data(), data.size_s()); }
EVENT2(packetReceived, const uchar *, data, int, size);
//! \events //! \events
//! \{ //! \{
@@ -173,6 +179,7 @@ public:
//! \fn void packetReceived(const uchar * data, int size) //! \fn void packetReceived(const uchar * data, int size)
//! \~english Emitted when the current input chunk passes the configured extraction rules. //! \~english Emitted when the current input chunk passes the configured extraction rules.
//! \~russian Генерируется, когда текущие входные данные проходят настроенные правила выделения. //! \~russian Генерируется, когда текущие входные данные проходят настроенные правила выделения.
EVENT2(packetReceived, const uchar *, data, int, size);
//! \} //! \}

View File

@@ -1,9 +1,8 @@
/*! \file piparsehelper.h //! \~\file piparsehelper.h
* \ingroup IO-Utils //! \~\ingroup IO-Utils
* \~\brief //! \~\brief
* \~english Key-dispatch helper for deserializing packets into callbacks //! \~english Key-dispatch helper for deserializing packets into callbacks
* \~russian Вспомогательный класс диспетчеризации по ключу для десериализации пакетов в обработчики //! \~russian Вспомогательный класс диспетчеризации по ключу для десериализации пакетов в обработчики
*/
/* /*
PIP - Platform Independent Primitives PIP - Platform Independent Primitives
Helper class to automate structs receive Helper class to automate structs receive
@@ -30,7 +29,7 @@
#include "pip_io_utils_export.h" #include "pip_io_utils_export.h"
//! \ingroup IO-Utils //! \~\ingroup IO-Utils
//! \~\brief //! \~\brief
//! \~english Maps packet keys to handlers and deserializes payloads before invocation. //! \~english Maps packet keys to handlers and deserializes payloads before invocation.
//! \~russian Связывает ключи пакетов с обработчиками и десериализует полезную нагрузку перед вызовом. //! \~russian Связывает ключи пакетов с обработчиками и десериализует полезную нагрузку перед вызовом.
@@ -41,8 +40,6 @@
//! Payload types are restored from %PIByteArray by the selected handler signature. //! Payload types are restored from %PIByteArray by the selected handler signature.
//! \n //! \n
//! \n Example: //! \n Example:
//! \snippet piparsehelper.cpp 0
//! \snippet piparsehelper.cpp 1
//! \~russian //! \~russian
//! %PIParseHelper помогает заменить ручную диспетчеризацию пакетов через switch //! %PIParseHelper помогает заменить ручную диспетчеризацию пакетов через switch
//! набором вызовов \a assign(). Обработчиками могут быть обычные callback-функции, //! набором вызовов \a assign(). Обработчиками могут быть обычные callback-функции,
@@ -50,8 +47,9 @@
//! по сигнатуре выбранного обработчика. //! по сигнатуре выбранного обработчика.
//! \n //! \n
//! \n Пример: //! \n Пример:
//! \snippet piparsehelper.cpp 0 //!
//! \snippet piparsehelper.cpp 1 //! \~\snippet piparsehelper.cpp 0
//! \~\snippet piparsehelper.cpp 1
template<typename Key> template<typename Key>
class PIParseHelper { class PIParseHelper {
public: public:
@@ -64,7 +62,7 @@ public:
//! \~russian Связывает ключ "key" с callback-функцией "func" без аргументов полезной нагрузки. //! \~russian Связывает ключ "key" с callback-функцией "func" без аргументов полезной нагрузки.
void assign(Key key, std::function<void()> func) { void assign(Key key, std::function<void()> func) {
auto lf = [func](PIByteArray) { func(); }; auto lf = [func](PIByteArray) { func(); };
functions[key] << lf; functions[key] << std::move(lf);
} }
@@ -79,7 +77,7 @@ public:
func(v); func(v);
} }
}; };
functions[key] << lf; functions[key] << std::move(lf);
} }

Some files were not shown because too many files have changed in this diff Show More