merged AI doc, some new pages

This commit is contained in:
2026-03-12 14:46:57 +03:00
parent 07ae277f9e
commit ed13838237
206 changed files with 14088 additions and 5152 deletions

View File

@@ -1,3 +1,12 @@
//! \~\file piconsolemodule.h
//! \~\ingroup Console
//! \~\brief
//! \~english Console module headers
//! \~russian Заголовочные файлы модуля консоли
//! \~\details
//! \~english This file includes all Console module headers providing keyboard input, screen management, and tile-based UI.
//! \~russian Этот файл включает все заголовочные файлы модуля консоли, обеспечивающие ввод с клавиатуры, управление экраном и UI на основе
//! тайлов.
/*
PIP - Platform Independent Primitives
Module includes
@@ -18,8 +27,8 @@
*/
//! \defgroup Console Console
//! \~\brief
//! \~english Console graphic
//! \~russian Графика в консоли
//! \~english Console screen, input, and terminal utilities
//! \~russian Средства консольного экрана, ввода и терминала
//!
//! \~\details
//! \~english \section cmake_module_Console Building with CMake
@@ -34,10 +43,10 @@
//! \~russian \par Общее
//!
//! \~english
//! These files provides grab keyboard from console, simple tiling manager and virtual terminal.
//! These files provide keyboard capture from the console, a simple tile-based screen API and a virtual terminal.
//!
//! \~russian
//! Эти файлы обеспечивают захват клавиатуры в консоли, простой тайловый менеджер и виртуальный терминал.
//! Эти файлы предоставляют захват клавиатуры из консоли, простой экранный API на тайлах и виртуальный терминал.
//!
//! \~\authors
//! \~english

View File

@@ -1,9 +1,8 @@
/*! \file pikbdlistener.h
* \ingroup Console
* \~\brief
* \~english Keyboard console input listener
* \~russian Консольный захват клавиатуры
*/
//! \~\file pikbdlistener.h
//! \~\ingroup Console
//! \~\brief
//! \~english Console keyboard and mouse input listener
//! \~russian Слушатель клавиатурного и мышиного консольного ввода
/*
PIP - Platform Independent Primitives
Keyboard grabber for console
@@ -29,6 +28,10 @@
#include "pithread.h"
#include "pitime.h"
//! \relatesalso PIKbdListener
//! \~\brief
//! \~english Waits until the active listener captures the configured exit key and then stops it.
//! \~russian Ожидает, пока активный слушатель перехватит настроенную клавишу выхода, и затем останавливает его.
#define WAIT_FOR_EXIT \
while (!PIKbdListener::exiting) \
piMSleep(PIP_MIN_MSLEEP * 5); \
@@ -37,87 +40,107 @@
}
//! \~\ingroup Console
//! \~\brief
//! \~english Console input listener for keyboard and mouse events.
//! \~russian Слушатель консольного ввода для событий клавиатуры и мыши.
class PIP_EXPORT PIKbdListener: public PIThread {
PIOBJECT_SUBCLASS(PIKbdListener, PIThread);
friend class PIConsole;
friend class PITerminal;
public:
//! Special keyboard keys
//! \~english Keyboard keys reported as non-character codes.
//! \~russian Клавиши, передаваемые как несимвольные коды.
enum SpecialKey {
Tab /** Tab key */ = 0x09,
Return /** Enter key */ = 0x0a,
Esc /** Escape key */ = 0x1b,
Space /** Space key */ = 0x20,
Backspace /** Backspace key */ = 0x7f,
UpArrow /** Up arrow key */ = -1,
DownArrow /** Down arrow key */ = -2,
RightArrow /** Right arrow key */ = -3,
LeftArrow /** Left arrow key */ = -4,
Home /** Home key */ = -5,
End /** End key */ = -6,
PageUp /** Page up key */ = -7,
PageDown /** Page down key */ = -8,
Insert /** Delete key */ = -9,
Delete /** Delete key */ = -10,
F1 /** F1 key */ = -11,
F2 /** F2 key */ = -12,
F3 /** F3 key */ = -13,
F4 /** F4 key */ = -14,
F5 /** F5 key */ = -15,
F6 /** F6 key */ = -16,
F7 /** F7 key */ = -17,
F8 /** F8 key */ = -18,
F9 /** F9 key */ = -19,
F10 /** F10 key */ = -20,
F11 /** F11 key */ = -21,
F12 /** F12 key */ = -22
Tab = 0x09 /** \~english Tab key \~russian Клавиша Tab */,
Return = 0x0a /** \~english Enter key \~russian Клавиша Enter */,
Esc = 0x1b /** \~english Escape key \~russian Клавиша Escape */,
Space = 0x20 /** \~english Space key \~russian Клавиша пробела */,
Backspace = 0x7f /** \~english Backspace key \~russian Клавиша Backspace */,
UpArrow = -1 /** \~english Up arrow key \~russian Стрелка вверх */,
DownArrow = -2 /** \~english Down arrow key \~russian Стрелка вниз */,
RightArrow = -3 /** \~english Right arrow key \~russian Стрелка вправо */,
LeftArrow = -4 /** \~english Left arrow key \~russian Стрелка влево */,
Home = -5 /** \~english Home key \~russian Клавиша Home */,
End = -6 /** \~english End key \~russian Клавиша End */,
PageUp = -7 /** \~english Page Up key \~russian Клавиша Page Up */,
PageDown = -8 /** \~english Page Down key \~russian Клавиша Page Down */,
Insert = -9 /** \~english Insert key \~russian Клавиша Insert */,
Delete = -10 /** \~english Delete key \~russian Клавиша Delete */,
F1 = -11 /** \~english F1 key \~russian Клавиша F1 */,
F2 = -12 /** \~english F2 key \~russian Клавиша F2 */,
F3 = -13 /** \~english F3 key \~russian Клавиша F3 */,
F4 = -14 /** \~english F4 key \~russian Клавиша F4 */,
F5 = -15 /** \~english F5 key \~russian Клавиша F5 */,
F6 = -16 /** \~english F6 key \~russian Клавиша F6 */,
F7 = -17 /** \~english F7 key \~russian Клавиша F7 */,
F8 = -18 /** \~english F8 key \~russian Клавиша F8 */,
F9 = -19 /** \~english F9 key \~russian Клавиша F9 */,
F10 = -20 /** \~english F10 key \~russian Клавиша F10 */,
F11 = -21 /** \~english F11 key \~russian Клавиша F11 */,
F12 = -22 /** \~english F12 key \~russian Клавиша F12 */
};
//! Keyboard modifiers
//! \~english Keyboard modifier bit flags.
//! \~russian Битовые флаги модификаторов клавиатуры.
enum KeyModifier {
Ctrl /** Control key */ = 0x1,
Shift /** Shift key */ = 0x2,
Alt /** Alt key */ = 0x4
// Meta /** Meta (windows) key */ = 0x8
Ctrl = 0x1 /** \~english Control key \~russian Клавиша Control */,
Shift = 0x2 /** \~english Shift key \~russian Клавиша Shift */,
Alt = 0x4 /** \~english Alt key \~russian Клавиша Alt */,
// Meta = 0x8 /** Meta (windows) key */
};
//! \~english Combination of \a KeyModifier flags.
//! \~russian Комбинация флагов \a KeyModifier.
typedef PIFlags<KeyModifier> KeyModifiers;
//! This struct contains information about pressed keyboard key
//! \~english Information about one keyboard event.
//! \~russian Информация об одном событии клавиатуры.
struct PIP_EXPORT KeyEvent {
//! \~english Constructs an empty event or initializes it with key and modifiers.
//! \~russian Создает пустое событие или инициализирует его клавишей и модификаторами.
KeyEvent(int k = 0, KeyModifiers m = 0) {
key = k;
modifiers = m;
}
//! Pressed key. It can be simple \b char or special key (see PIKbdListener::SpecialKey)
//! \~english Pressed key code. It can be a character code or one of \a SpecialKey values.
//! \~russian Код нажатой клавиши. Это может быть код символа или одно из значений \a SpecialKey.
int key;
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
KeyModifiers modifiers;
};
//! Mouse buttons
//! \~english Mouse button bit flags.
//! \~russian Битовые флаги кнопок мыши.
enum MouseButton {
MouseLeft /** Left button */ = 0x01,
MouseRight /** Right button */ = 0x02,
MouseMiddle /** Middle button */ = 0x04
MouseLeft = 0x01 /** \~english Left button \~russian Левая кнопка */,
MouseRight = 0x02 /** \~english Right button \~russian Правая кнопка */,
MouseMiddle = 0x04 /** \~english Middle button \~russian Средняя кнопка */
};
//! Mouse actions
//! \~english Mouse action kind.
//! \~russian Вид действия мыши.
enum MouseAction {
MouseButtonPress /** Mouse button pressed */,
MouseButtonRelease /** Mouse button released */,
MouseButtonDblClick /** Mouse button double click */,
MouseMove /** Mouse moved */,
MouseWheel /** Mouse wheel rotated */
MouseButtonPress /** \~english Mouse button pressed \~russian Нажатие кнопки мыши */,
MouseButtonRelease /** \~english Mouse button released \~russian Отпускание кнопки мыши */,
MouseButtonDblClick /** \~english Mouse button double-click \~russian Двойной щелчок кнопкой мыши */,
MouseMove /** \~english Mouse moved \~russian Перемещение мыши */,
MouseWheel /** \~english Mouse wheel rotated \~russian Прокрутка колеса мыши */
};
//! \~english Combination of pressed \a MouseButton flags.
//! \~russian Комбинация нажатых флагов \a MouseButton.
typedef PIFlags<MouseButton> MouseButtons;
//! This struct contains information about mouse action
//! \~english Information about one mouse event.
//! \~russian Информация об одном событии мыши.
struct PIP_EXPORT MouseEvent {
//! \~english Constructs an event with coordinates at the origin.
//! \~russian Создает событие с координатами в начале области.
MouseEvent(MouseAction a = MouseButtonPress, MouseButtons b = 0, KeyModifiers m = 0) {
x = y = 0;
action = a;
@@ -125,107 +148,156 @@ public:
modifiers = m;
}
//! Event X coordinate in view-space, from 0
//! \~english Event X coordinate in screen space, starting from zero.
//! \~russian Координата X события в экранном пространстве, начиная с нуля.
int x;
//! Event Y coordinate in view-space, from 0
//! \~english Event Y coordinate in screen space, starting from zero.
//! \~russian Координата Y события в экранном пространстве, начиная с нуля.
int y;
//! Mouse action type
//! \~english Mouse action kind.
//! \~russian Вид действия мыши.
MouseAction action;
//! Pressed buttons. It contains PIKbdListener::MouseButton bitfields
//! \~english Pressed mouse buttons as a combination of \a MouseButton flags.
//! \~russian Нажатые кнопки мыши как комбинация флагов \a MouseButton.
MouseButtons buttons;
//! Active keyboard modifiers. It contains PIKbdListener::KeyModifier bitfields
//! \~english Active keyboard modifiers as a combination of \a KeyModifier flags.
//! \~russian Активные модификаторы клавиатуры как комбинация флагов \a KeyModifier.
KeyModifiers modifiers;
};
//! This struct contains information about mouse wheel action
//! \~english Information about one mouse wheel event.
//! \~russian Информация об одном событии колеса мыши.
struct PIP_EXPORT WheelEvent: public MouseEvent {
//! \~english Constructs a wheel event with downward direction by default.
//! \~russian Создает событие колеса мыши; по умолчанию направление вниз.
WheelEvent(): MouseEvent() { direction = false; }
//! Wheel direction, /b true - up, /b fasle - down
//! \~english Wheel direction: \b true for up, \b false for down.
//! \~russian Направление прокрутки: \b true вверх, \b false вниз.
bool direction;
};
//! \~english Callback receiving a key event and user data.
//! \~russian Обратный вызов, принимающий событие клавиши и пользовательские данные.
typedef std::function<void(KeyEvent, void *)> KBFunc;
//! Constructs keyboard listener with external function "slot" and custom data "data"
//! \~english Constructs a listener with optional callback, user data, and auto-start mode.
//! \~russian Создает слушатель с необязательным обратным вызовом, пользовательскими данными и автозапуском.
explicit PIKbdListener(KBFunc slot = 0, void * data = 0, bool startNow = true);
//! \~english Stops the listener and restores the console state.
//! \~russian Останавливает слушатель и восстанавливает состояние консоли.
~PIKbdListener();
//! Returns custom data
//! \~english Returns the user data passed back with callbacks and events.
//! \~russian Возвращает пользовательские данные, передаваемые обратно в обратные вызовы и события.
void * data() { return kbddata_; }
//! Set custom data to "_data"
//! \~english Sets the user data passed back with callbacks and events.
//! \~russian Задает пользовательские данные, возвращаемые в обратных вызовах и событиях.
void setData(void * _data) { kbddata_ = _data; }
//! Set external function to "slot"
//! \~english Sets the callback receiving both key event and user data.
//! \~russian Устанавливает обратный вызов, получающий событие клавиши и пользовательские данные.
void setSlot(KBFunc slot) { ret_func = slot; }
//! Set external function to "slot"
//! \~english Sets the callback that only receives the key event and ignores user data.
//! \~russian Устанавливает обратный вызов, получающий только событие клавиши и игнорирующий пользовательские данные.
void setSlot(std::function<void(KeyEvent)> slot) {
ret_func = [slot](KeyEvent e, void *) { slot(e); };
}
//! Returns if exit key if awaiting
//! \~english Returns whether the exit key is currently being captured.
//! \~russian Возвращает, включен ли сейчас перехват клавиши выхода.
bool exitCaptured() const { return exit_enabled; }
//! Returns exit key, default 'Q'
//! \~english Returns the configured exit key. The default is \c 'Q'.
//! \~russian Возвращает настроенную клавишу выхода. По умолчанию это \c 'Q'.
int exitKey() const { return exit_key; }
//! \~english Returns the double-click interval in milliseconds.
//! \~russian Возвращает интервал двойного щелчка в миллисекундах.
double doubleClickInterval() const { return dbl_interval; }
//! \~english Sets the mouse double-click interval in milliseconds.
//! \~russian Задает интервал двойного щелчка мыши в миллисекундах.
void setDoubleClickInterval(double v) { dbl_interval = v; }
//! \~english Performs one low-level polling cycle and dispatches decoded input events.
//! \~russian Выполняет один цикл низкоуровневого опроса и отправляет декодированные события ввода.
void readKeyboard();
//! \~english Requests listener shutdown and interrupts a pending wait for console input.
//! \~russian Запрашивает остановку слушателя и прерывает текущее ожидание консольного ввода.
void stop();
//! \~english Requests shutdown and waits until console capture is restored or the timeout expires.
//! \~russian Запрашивает остановку и ждет восстановления режима консоли до истечения таймаута.
bool stopAndWait(PISystemTime timeout = {});
//! Returns if keyboard listening is active (not running!)
//! \~english Returns whether low-level console capture is currently enabled.
//! \~russian Возвращает, включен ли сейчас низкоуровневый захват консольного ввода.
bool isActive() { return is_active; }
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
//! \{
//! \fn void enableExitCapture(int key = 'Q')
//! \brief Enable exit key "key" awaiting
//! \~english Enables capture of exit key \a key.
//! \~russian Включает перехват клавиши выхода \a key.
EVENT_HANDLER(void, enableExitCapture) { enableExitCapture('Q'); }
EVENT_HANDLER1(void, enableExitCapture, int, key) {
exit_enabled = true;
exit_key = key;
}
//! \fn void disableExitCapture()
//! \brief Disable exit key awaiting
//! \~english Disables exit key capture.
//! \~russian Выключает перехват клавиши выхода.
EVENT_HANDLER(void, disableExitCapture) { exit_enabled = false; }
//! \fn void setActive(bool yes = true)
//! \brief Set keyboard listening is active or not
//! \~english Enables or disables low-level console input capture.
//! \~russian Включает или выключает низкоуровневый захват консольного ввода.
EVENT_HANDLER(void, setActive) { setActive(true); }
EVENT_HANDLER1(void, setActive, bool, yes);
//! \}
//! \events
//! \{
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \brief Raise on key "key" pressed, "data" is custom data
//! \~english Raised when a key event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие клавиши. \a data содержит указатель на пользовательские данные.
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
//! \fn void mouseEvent(PIKbdListener::MouseEvent mouse, void * data)
//! \~english Raised when a mouse button or move event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие кнопки мыши или перемещения. \a data содержит указатель на пользовательские данные.
EVENT2(mouseEvent, PIKbdListener::MouseEvent, mouse, void *, data);
//! \fn void wheelEvent(PIKbdListener::WheelEvent wheel, void * data)
//! \~english Raised when a mouse wheel event is decoded. \a data is the user data pointer.
//! \~russian Вызывается, когда декодировано событие колеса мыши. \a data содержит указатель на пользовательские данные.
EVENT2(wheelEvent, PIKbdListener::WheelEvent, wheel, void *, data);
//! \}
static bool exiting;
//! \~english Returns the listener instance currently registered by the console subsystem.
//! \~russian Возвращает экземпляр слушателя, который сейчас зарегистрирован консольной подсистемой.
static PIKbdListener * instance() { return _object; }
//! \~english Becomes \b true after the configured exit key is captured.
//! \~russian Становится \b true после перехвата настроенной клавиши выхода.
static bool exiting;
private:
void begin() override;
void run() override { readKeyboard(); }
@@ -268,16 +340,16 @@ private:
//! \relatesalso PIBinaryStream
//! \~english Store operator
//! \~russian Оператор сохранения
//! \~english Store operator for MouseEvent.
//! \~russian Оператор сохранения для MouseEvent.
BINARY_STREAM_WRITE(PIKbdListener::MouseEvent) {
s << v.x << v.y << v.action << v.buttons << v.modifiers;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator
//! \~russian Оператор извлечения
//! \~english Restore operator for MouseEvent.
//! \~russian Оператор извлечения для MouseEvent.
BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
s >> v.x >> v.y >> v.action >> v.buttons >> v.modifiers;
return s;
@@ -285,16 +357,16 @@ BINARY_STREAM_READ(PIKbdListener::MouseEvent) {
//! \relatesalso PIBinaryStream
//! \~english Store operator
//! \~russian Оператор сохранения
//! \~english Store operator for WheelEvent.
//! \~russian Оператор сохранения для WheelEvent.
BINARY_STREAM_WRITE(PIKbdListener::WheelEvent) {
s << (*(PIKbdListener::MouseEvent *)&v) << v.direction;
return s;
}
//! \relatesalso PIBinaryStream
//! \~english Restore operator
//! \~russian Оператор извлечения
//! \~english Restore operator for WheelEvent.
//! \~russian Оператор извлечения для WheelEvent.
BINARY_STREAM_READ(PIKbdListener::WheelEvent) {
s >> (*(PIKbdListener::MouseEvent *)&v) >> v.direction;
return s;

View File

@@ -1,9 +1,8 @@
/*! \file piscreen.h
* \ingroup Console
* \~\brief
* \~english Console tiling manager
* \~russian Консольный тайловый менеджер
*/
//! \~\file piscreen.h
//! \~\ingroup Console
//! \~\brief
//! \~english Console screen manager and tile host
//! \~russian Менеджер консольного экрана и контейнер тайлов
/*
PIP - Platform Independent Primitives
Console GUI
@@ -31,6 +30,10 @@
#include "piscreentile.h"
//! \~\ingroup Console
//! \~\brief
//! \~english Console screen manager with tile layout, drawing, and input routing.
//! \~russian Менеджер консольного экрана с раскладкой тайлов, отрисовкой и маршрутизацией ввода.
class PIP_CONSOLE_EXPORT PIScreen
: public PIThread
, public PIScreenTypes::PIScreenBase {
@@ -38,69 +41,122 @@ class PIP_CONSOLE_EXPORT PIScreen
class SystemConsole;
public:
//! Constructs %PIScreen with key handler "slot" and if "startNow" start it
//! \~english Constructs a screen with an internal keyboard listener, optional callback, and auto-start mode.
//! \~russian Создает экран со встроенным слушателем клавиатуры, необязательным обратным вызовом и режимом автозапуска.
//! \~\details
//! \~english Constructs a new PIScreen instance with optional immediate start.
//! \~russian Создает новый экземпляр PIScreen с опциональным немедленным запуском.
//! \~\param startNow
//! \~english Start immediately if true.
//! \~russian Запустить немедленно, если true.
//! \~\param slot
//! \~english Keyboard handler function.
//! \~russian Функция обработчика клавиатуры.
PIScreen(bool startNow = true, PIKbdListener::KBFunc slot = 0);
//! \~english Destroys PIScreen and cleans up resources.
//! \~russian Уничтожает PIScreen и очищает ресурсы.
~PIScreen();
//! Directly call function from \a PIKbdListener
//! \~english Enables catching the exit key (default is 'Q') to stop the screen.
//! \~russian Включает захват клавиши выхода (по умолчанию 'Q') для остановки экрана.
void enableExitCapture(int key = 'Q') { listener->enableExitCapture(key); }
//! Directly call function from \a PIKbdListener
//! \~english Disables catching the exit key.
//! \~russian Отключает захват клавиши выхода.
void disableExitCapture() { listener->disableExitCapture(); }
//! Directly call function from \a PIKbdListener
//! \~english Returns whether exit key capture is enabled.
//! \~russian Возвращает, включен ли перехват клавиши выхода.
bool exitCaptured() const { return listener->exitCaptured(); }
//! Directly call function from \a PIKbdListener
//! \~english Returns the configured exit key.
//! \~russian Возвращает настроенную клавишу выхода.
int exitKey() const { return listener->exitKey(); }
//! \~english Returns the current console width in characters.
//! \~russian Возвращает текущую ширину консоли в символах.
int windowWidth() const { return console.width; }
//! \~english Returns the current console height in characters.
//! \~russian Возвращает текущую высоту консоли в символах.
int windowHeight() const { return console.height; }
//! \~english Returns whether mouse hit-testing and routing are enabled.
//! \~russian Возвращает, включены ли проверка попадания и маршрутизация событий мыши.
bool isMouseEnabled() const { return mouse_; }
//! \~english Enables or disables mouse routing and tile hit-testing.
//! \~russian Включает или выключает маршрутизацию мыши и проверку попадания по тайлам.
void setMouseEnabled(bool on);
//! \~english Returns the root tile covering the whole screen.
//! \~russian Возвращает корневой тайл, покрывающий весь экран.
PIScreenTile * rootTile() { return &root; }
//! \~english Searches the root tile subtree by object name.
//! \~russian Ищет тайл по имени объекта в поддереве корневого тайла.
//! \~\return
//! \~english Tile pointer if found, otherwise nullptr.
//! \~russian Указатель на тайл, если найден, иначе nullptr.
PIScreenTile * tileByName(const PIString & name);
//! \~english Sets a dialog tile drawn above the root tree, centered on screen, and focused first. Pass \c nullptr to remove it.
//! \~russian Задает диалоговый тайл, рисуемый поверх корневого дерева, центрируемый на экране и первым получающий фокус. Передайте \c
//! nullptr, чтобы убрать его.
void setDialogTile(PIScreenTile * t);
//! \~english Returns the currently active dialog tile or \c nullptr.
//! \~russian Возвращает активный диалоговый тайл или \c nullptr.
PIScreenTile * dialogTile() const { return tile_dialog; }
//! \~english Returns the drawer used to fill the off-screen cell buffer for the next frame.
//! \~russian Возвращает рисовальщик, используемый для заполнения внеэкранного буфера ячеек следующего кадра.
PIScreenDrawer * drawer() { return &drawer_; }
//! \~english Clears the off-screen cell buffer. The terminal is updated on the next draw cycle.
//! \~russian Очищает внеэкранный буфер ячеек. Терминал обновится на следующем цикле отрисовки.
void clear() { drawer_.clear(); }
//! \~english Resizes the internal console buffers used for subsequent frames.
//! \~russian Изменяет размер внутренних консольных буферов, используемых в следующих кадрах.
void resize(int w, int h) { console.resize(w, h); }
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
//! \{
//! \fn void waitForFinish()
//! \brief block until finished (exit key will be pressed)
//! \~english Blocks until the captured exit key is pressed and then stops the screen.
//! \~russian Блокирует выполнение, пока не будет нажата перехватываемая клавиша выхода, затем останавливает экран.
EVENT_HANDLER0(void, waitForFinish);
//! \fn void start(bool wait = false)
//! \brief Start console output and if "wait" block until finished (exit key will be pressed)
//! \~english Starts the screen thread and optionally waits until the configured exit key is captured.
//! \~russian Запускает поток экрана и при необходимости ждет, пока не будет перехвачена настроенная клавиша выхода.
EVENT_HANDLER0(void, start) { start(false); }
EVENT_HANDLER1(void, start, bool, wait);
//! \fn void stop(bool clear = false)
//! \brief Stop console output and if "clear" clear the screen
//! \~english Stops the screen thread, restores console state, and optionally clears the terminal.
//! \~russian Останавливает поток экрана, восстанавливает состояние консоли и при необходимости очищает терминал.
EVENT_HANDLER0(void, stop) { stop(false); }
EVENT_HANDLER1(void, stop, bool, clear);
//! \}
//! \events
//! \{
//! \fn void keyPressed(PIKbdListener::KeyEvent key, void * data)
//! \brief Raise on key "key" pressed, "data" is pointer to %PIConsole object
//! \~english Raised when a key was not consumed by focus navigation or the focused tile. \a data is the screen user data pointer.
//! \~russian Вызывается, когда клавиша не была поглощена навигацией фокуса или тайлом с фокусом. \a data содержит пользовательский
//! указатель экрана.
EVENT2(keyPressed, PIKbdListener::KeyEvent, key, void *, data);
//! \fn void tileEvent(PIScreenTile * tile, PIScreenTypes::TileEvent e)
//! \brief Raise on some event "e" from tile "tile"
//! \~english Raised when a tile reports a custom event \a e.
//! \~russian Вызывается, когда тайл сообщает пользовательское событие \a e.
EVENT2(tileEvent, PIScreenTile *, tile, PIScreenTypes::TileEvent, e);
//! \}

View File

@@ -1,82 +0,0 @@
/*! \file piscreenconsole.h
* \ingroup Console
* \~\brief
* \~english Tile for PIScreen with PIConsole API
* \~russian Тайл для PIScreen с API PIConsole
*/
/*
PIP - Platform Independent Primitives
Tile for PIScreen with PIConsole API
Andrey Bychkov work.a.b@yandex.ru
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef PISCREENCONSOLE_H
#define PISCREENCONSOLE_H
#include "pip_console_export.h"
#include "piscreentiles.h"
/// NOTE: incomplete class
/// TODO: write TileVars
class PIP_CONSOLE_EXPORT TileVars: public PIScreenTile {
public:
TileVars(const PIString & n = PIString());
protected:
struct PIP_CONSOLE_EXPORT Variable {
Variable() {
nx = ny = type = offset = bitFrom = bitCount = size = 0;
format = PIScreenTypes::CellFormat();
ptr = 0;
}
bool isEmpty() const { return (ptr == 0); }
PIString name;
PIScreenTypes::CellFormat format;
int nx;
int ny;
int type;
int offset;
int bitFrom;
int bitCount;
int size;
const void * ptr;
/*void operator =(const Variable & src) {
name = src.name;
format = src.format;
nx = src.nx;
ny = src.ny;
type = src.type;
offset = src.offset;
bitFrom = src.bitFrom;
bitCount = src.bitCount;
size = src.size;
ptr = src.ptr;
}*/
};
PIVector<Variable> variables;
PIScreenTypes::Alignment alignment;
void sizeHint(int & w, int & h) const override;
void drawEvent(PIScreenDrawer * d) override;
};
class PIP_CONSOLE_EXPORT PIScreenConsoleTile: public PIScreenTile {
public:
PIScreenConsoleTile();
};
#endif // PISCREENCONSOLE_H

View File

@@ -1,9 +1,8 @@
/*! \file piscreendrawer.h
* \ingroup Console
* \~\brief
* \~english Drawer for PIScreen
* \~russian Отрисовщик для PIScreen
*/
//! \~\file piscreendrawer.h
//! \~\ingroup Console
//! \~\brief
//! \~english Drawing helpers for %PIScreen cell buffers
//! \~russian Вспомогательные средства рисования для буферов ячеек %PIScreen
/*
PIP - Platform Independent Primitives
Drawer for PIScreen
@@ -30,31 +29,54 @@
#include "piscreentypes.h"
#include "pistring.h"
//! \~\ingroup Console
//! \~\brief
//! \~english Helper that draws primitives and text into a %PIScreen cell buffer.
//! \~russian Вспомогательный класс для рисования примитивов и текста в буфере ячеек %PIScreen.
//! \~\details
//! \~english Provides methods for drawing primitives such as pixels, lines, rectangles, and text on console screen.
//! \~russian Предоставляет методы для рисования примитивов, таких как пиксели, линии, прямоугольники и текст на консольном экране.
class PIP_CONSOLE_EXPORT PIScreenDrawer {
friend class PIScreen;
PIScreenDrawer(PIVector<PIVector<PIScreenTypes::Cell>> & c);
public:
//! \~english Predefined pseudographic and widget-state symbols.
//! \~russian Предопределенные псевдографические символы и символы состояний виджетов.
//! \~\details
//! \~english Defines available characters for drawing ASCII art primitives.
//! \~russian Определяет доступные символы для рисования ASCII-арта примитивов.
enum ArtChar {
LineVertical = 1,
LineHorizontal,
Cross,
CornerTopLeft,
CornerTopRight,
CornerBottomLeft,
CornerBottomRight,
Unchecked,
Checked
LineVertical = 1 /** \~english Vertical line symbol. \~russian Символ вертикальной линии. */,
LineHorizontal /** \~english Horizontal line symbol. \~russian Символ горизонтальной линии. */,
Cross /** \~english Line intersection symbol. \~russian Символ пересечения линий. */,
CornerTopLeft /** \~english Top-left frame corner. \~russian Левый верхний угол рамки. */,
CornerTopRight /** \~english Top-right frame corner. \~russian Правый верхний угол рамки. */,
CornerBottomLeft /** \~english Bottom-left frame corner. \~russian Левый нижний угол рамки. */,
CornerBottomRight /** \~english Bottom-right frame corner. \~russian Правый нижний угол рамки. */,
Unchecked /** \~english Unchecked box symbol. \~russian Символ неотмеченного флажка. */,
Checked /** \~english Checked box symbol. \~russian Символ отмеченного флажка. */
};
//! \~english Clears the whole target buffer.
//! \~russian Очищает весь целевой буфер.
void clear();
//! \~english Clears a rectangular area in the target buffer with spaces.
//! \~russian Очищает прямоугольную область целевого буфера пробелами.
void clearRect(int x0, int y0, int x1, int y1) { fillRect(x0, y0, x1, y1, ' '); }
//! \~english Draws one cell at position `(x, y)`.
//! \~russian Рисует одну ячейку в позиции `(x, y)`.
void drawPixel(int x,
int y,
const PIChar & c,
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Default,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Draws a line between two points.
//! \~russian Рисует линию между двумя точками.
void drawLine(int x0,
int y0,
int x1,
@@ -63,6 +85,9 @@ public:
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Default,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Draws a rectangular outline with the specified symbol.
//! \~russian Рисует контур прямоугольника указанным символом.
void drawRect(int x0,
int y0,
int x1,
@@ -71,6 +96,9 @@ public:
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Default,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Draws a frame using predefined art symbols.
//! \~russian Рисует рамку предопределенными псевдографическими символами.
void drawFrame(int x0,
int y0,
int x1,
@@ -78,12 +106,18 @@ public:
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Default,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Draws text starting at `(x, y)`.
//! \~russian Рисует текст, начиная с позиции `(x, y)`.
void drawText(int x,
int y,
const PIString & s,
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Transparent,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Fills a rectangular area with one symbol and cell format.
//! \~russian Заполняет прямоугольную область одним символом и форматом ячейки.
void fillRect(int x0,
int y0,
int x1,
@@ -92,10 +126,17 @@ public:
PIScreenTypes::Color col_char = PIScreenTypes::Default,
PIScreenTypes::Color col_back = PIScreenTypes::Default,
PIScreenTypes::CharFlags flags_char = 0);
//! \~english Copies a cell matrix into a rectangular area.
//! \~russian Копирует матрицу ячеек в прямоугольную область.
void fillRect(int x0, int y0, int x1, int y1, PIVector<PIVector<PIScreenTypes::Cell>> & content);
//! \~english Returns a predefined art symbol.
//! \~russian Возвращает предопределенный псевдографический символ.
PIChar artChar(const ArtChar type) const { return arts_.value(type, PIChar(' ')); }
//! \~english Fills an arbitrary cell buffer with default cells.
//! \~russian Заполняет произвольный буфер ячеек значениями по умолчанию.
static void clear(PIVector<PIVector<PIScreenTypes::Cell>> & cells);
private:

View File

@@ -1,9 +1,8 @@
/*! \file piscreentile.h
* \ingroup Console
* \~\brief
* \~english Basic PIScreen tile
* \~russian Базовый тайл для PIScreen
*/
//! \~\file piscreentile.h
//! \~\ingroup Console
//! \brief
//! \~english Basic PIScreen tile
//! \~russian Базовый тайл для PIScreen
/*
PIP - Platform Independent Primitives
Basic PIScreen tile
@@ -32,27 +31,74 @@
class PIScreenDrawer;
//! \~\ingroup Console
//! \~\brief
//! \~english Base tile in the console screen tree.
//! \~russian Базовый тайл в дереве консольного экрана.
//! \details
//! \~english Base class for all screen tiles providing layout and event handling.
//! \~russian Базовый класс для всех экранных тайлов, обеспечивающий компоновку и обработку событий.
class PIP_CONSOLE_EXPORT PIScreenTile: public PIObject {
friend class PIScreen;
PIOBJECT_SUBCLASS(PIScreenTile, PIObject);
public:
//! \~english Constructs a tile with name, child layout direction, and size policy.
//! \~russian Создает тайл с именем, направлением раскладки дочерних элементов и политикой размера.
PIScreenTile(const PIString & n = PIString(),
PIScreenTypes::Direction d = PIScreenTypes::Vertical,
PIScreenTypes::SizePolicy p = PIScreenTypes::Preferred);
//! \~english Destroys the tile and its owned child tiles.
//! \~russian Уничтожает тайл и принадлежащие ему дочерние тайлы.
virtual ~PIScreenTile();
//! \~english Adds child tile \a t, makes this tile its parent, and attaches the subtree to the same screen bridge.
//! \~russian Добавляет дочерний тайл \a t, делает этот тайл его родителем и подключает поддерево к тому же экранному мосту.
void addTile(PIScreenTile * t);
//! \~english Detaches child tile \a t without deleting it and removes its screen association.
//! \~russian Отсоединяет дочерний тайл \a t без удаления и снимает его связь с экраном.
void takeTile(PIScreenTile * t);
//! \~english Removes and deletes child tile \a t.
//! \~russian Удаляет дочерний тайл \a t и уничтожает его.
void removeTile(PIScreenTile * t);
//! \~english Returns the parent tile or \c nullptr for the root.
//! \~russian Возвращает родительский тайл или \c nullptr для корня.
PIScreenTile * parentTile() const { return parent; }
//! \~english Returns all descendant tiles. Hidden tiles can be skipped with \a only_visible.
//! \~russian Возвращает все дочерние тайлы по дереву. Скрытые тайлы можно пропустить через \a only_visible.
PIVector<PIScreenTile *> children(bool only_visible = false);
//! \~english Returns the first visible direct child covering screen point \a x, \a y.
//! \~russian Возвращает первый видимый прямой дочерний тайл, покрывающий экранную точку \a x, \a y.
PIScreenTile * childUnderMouse(int x, int y);
//! \~english Makes the tile visible for subsequent layout, hit-testing, and drawing passes.
//! \~russian Делает тайл видимым для последующих проходов компоновки, проверки попадания и отрисовки.
void show() { visible = true; }
//! \~english Hides the tile from layout, hit-testing, and drawing passes.
//! \~russian Скрывает тайл из проходов компоновки, проверки попадания и отрисовки.
void hide() { visible = false; }
//! \~english Requests focus for this tile if it is attached to a screen and allows focus.
//! \~russian Запрашивает фокус для этого тайла, если он подключен к экрану и допускает получение фокуса.
void setFocus();
//! \~english Returns whether this tile currently owns focus.
//! \~russian Возвращает, принадлежит ли этому тайлу текущий фокус.
bool hasFocus() const { return has_focus; }
//! \~english Sets all margins to \a m cells.
//! \~russian Устанавливает все отступы в \a m ячеек.
void setMargins(int m) { marginLeft = marginRight = marginTop = marginBottom = m; }
//! \~english Sets left, right, top, and bottom margins in cells.
//! \~russian Устанавливает левый, правый, верхний и нижний отступы в ячейках.
void setMargins(int l, int r, int t, int b) {
marginLeft = l;
marginRight = r;
@@ -60,52 +106,129 @@ public:
marginBottom = b;
}
//! \~english Returns the tile X coordinate in screen space.
//! \~russian Возвращает координату X тайла в экранном пространстве.
int x() const { return x_; }
//! \~english Returns the tile Y coordinate in screen space.
//! \~russian Возвращает координату Y тайла в экранном пространстве.
int y() const { return y_; }
//! \~english Returns the current tile width in cells.
//! \~russian Возвращает текущую ширину тайла в ячейках.
int width() const { return width_; }
//! \~english Returns the current tile height in cells.
//! \~russian Возвращает текущую высоту тайла в ячейках.
int height() const { return height_; }
//! \~english Direction used to lay out child tiles.
//! \~russian Направление раскладки дочерних тайлов.
PIScreenTypes::Direction direction;
//! \~english Size policy used by the parent during layout.
//! \~russian Политика размера, используемая родителем при компоновке.
PIScreenTypes::SizePolicy size_policy;
//! \~english Focus and navigation flags for the tile.
//! \~russian Флаги фокуса и навигации для тайла.
PIScreenTypes::FocusFlags focus_flags;
//! \~english Background format used to prefill the tile area before drawing.
//! \~russian Формат фона, которым предварительно заполняется область тайла перед отрисовкой.
PIScreenTypes::CellFormat back_format;
//! \~english Background symbol used to prefill the tile area before drawing.
//! \~russian Символ фона, которым предварительно заполняется область тайла перед отрисовкой.
PIChar back_symbol;
//! \~english Minimum size limits accepted during layout.
//! \~russian Минимальные ограничения размера, допускаемые при компоновке.
int minimumWidth, minimumHeight;
//! \~english Maximum size limits accepted during layout.
//! \~russian Максимальные ограничения размера, допускаемые при компоновке.
int maximumWidth, maximumHeight;
//! \~english Outer margins in cells.
//! \~russian Внешние отступы в ячейках.
int marginLeft, marginRight, marginTop, marginBottom;
//! \~english Spacing between visible child tiles in cells.
//! \~russian Интервал между видимыми дочерними тайлами в ячейках.
int spacing;
//! \~english Whether the tile participates in layout, hit-testing, and drawing.
//! \~russian Участвует ли тайл в компоновке, проверке попадания и отрисовке.
bool visible;
protected:
//! Returns desired tile size in "w" and "h"
//! \~english Returns the preferred tile size in \a w and \a h. The base implementation derives it from visible children, spacing, and margins.
//! \~russian Возвращает предпочтительный размер тайла в \a w и \a h. Базовая реализация вычисляет его по видимым дочерним тайлам, интервалам и отступам.
virtual void sizeHint(int & w, int & h) const;
//! Tile has been resized to "w"x"h"
//! \~english Called after the tile size changes to \a w by \a h during layout.
//! \~russian Вызывается после изменения размера тайла до \a w на \a h во время компоновки.
virtual void resizeEvent(int w, int h) {}
//! Draw tile with drawer "d" in world-space coordinates
//! \~english Draws the tile with drawer \a d in screen coordinates.
//! \~russian Отрисовывает тайл через рисовальщик \a d в экранных координатах.
virtual void drawEvent(PIScreenDrawer * d) {}
//! Return "true" if you process key
//! \~english Handles keyboard input and returns \b true when the event is consumed.
//! \~russian Обрабатывает клавиатурный ввод и возвращает \b true, если событие поглощено.
virtual bool keyEvent(PIKbdListener::KeyEvent key) { return false; }
//! Return "true" if you process event
//! \~english Handles mouse input and returns \b true when the event is consumed.
//! \~russian Обрабатывает событие мыши и возвращает \b true, если событие поглощено.
virtual bool mouseEvent(PIKbdListener::MouseEvent me) { return false; }
//! Return "true" if you process wheel
//! \~english Handles mouse wheel input and returns \b true when the event is consumed.
//! \~russian Обрабатывает колесо мыши и возвращает \b true, если событие поглощено.
virtual bool wheelEvent(PIKbdListener::WheelEvent we) { return false; }
//! \~english Raises tile event
//! \~russian Вызывает событие тайла
void raiseEvent(PIScreenTypes::TileEvent e);
//! \~english Sets screen reference
//! \~russian Устанавливает ссылку на экран
void setScreen(PIScreenTypes::PIScreenBase * s);
//! \~english Deletes all owned child tiles.
//! \~russian Удаляет все принадлежащие дочерние тайлы.
void deleteChildren();
//! \~english Draws background, tile contents, and then child tiles.
//! \~russian Отрисовывает фон, содержимое тайла и затем дочерние тайлы.
void drawEventInternal(PIScreenDrawer * d);
//! \~english Recomputes child geometry according to size hints, margins, and policies.
//! \~russian Пересчитывает геометрию дочерних тайлов по предпочтительным размерам, отступам и политикам.
void layout();
//! \~english Returns whether this tile should participate in automatic layout. Tiles with policy \a PIScreenTypes::Ignore are skipped.
//! \~russian Возвращает, должен ли тайл участвовать в автоматической компоновке. Тайлы с политикой \a PIScreenTypes::Ignore пропускаются.
bool needLayout() { return size_policy != PIScreenTypes::Ignore; }
//! \~english Owned direct child tiles.
//! \~russian Принадлежащие прямые дочерние тайлы.
PIVector<PIScreenTile *> tiles;
//! \~english Parent tile or \c nullptr for the root or detached tiles.
//! \~russian Родительский тайл или \c nullptr для корня и отсоединенных тайлов.
PIScreenTile * parent;
//! \~english Screen pointer, receiving tile notifications.
//! \~russian Ссылка на экран, принимающий уведомления от тайла.
PIScreenTypes::PIScreenBase * screen;
//! \~english Tile position and size in screen cells.
//! \~russian Положение и размер тайла в экранных ячейках.
int x_, y_, width_, height_;
//! \~english Whether this tile currently owns focus.
//! \~russian Принадлежит ли этому тайлу текущий фокус.
bool has_focus;
private:

View File

@@ -1,9 +1,11 @@
/*! \file piscreentiles.h
* \ingroup Console
* \~\brief
* \~english Various tiles for PIScreen
* \~russian Различные тайлы для PIScreen
*/
//! \~\file piscreentiles.h
//! \~\ingroup Console
//! \brief
//! \~english Various tiles for PIScreen
//! \~russian Различные тайлы для PIScreen
//! \details
//! \~english Provides ready-to-use tile implementations for common UI elements.
//! \~russian Обеспечивает готовые к использованию реализации тайлов для общих элементов UI.
/*
PIP - Platform Independent Primitives
Various tiles for PIScreen
@@ -30,15 +32,36 @@
#include "piscreentile.h"
//! \~\ingroup Console
//! \~\brief
//! \~english Simple text tile with per-row formatting.
//! \~russian Простой текстовый тайл с форматированием по строкам.
class PIP_CONSOLE_EXPORT TileSimple: public PIScreenTile {
PIOBJECT_SUBCLASS(TileSimple, PIScreenTile);
public:
//! \~english Row text with cell format.
//! \~russian Текст строки с форматом ячеек.
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
//! \~english Constructs an empty text tile.
//! \~russian Создает пустой текстовый тайл.
TileSimple(const PIString & n = PIString());
//! \~english Constructs a text tile with one row.
//! \~russian Создает текстовый тайл с одной строкой.
TileSimple(const Row & r);
//! \~english Destroys the text tile.
//! \~russian Уничтожает текстовый тайл.
virtual ~TileSimple() {}
//! \~english Rows displayed by the tile.
//! \~russian Строки, отображаемые тайлом.
PIVector<Row> content;
//! \~english Horizontal text alignment inside the tile.
//! \~russian Горизонтальное выравнивание текста внутри тайла.
PIScreenTypes::Alignment alignment;
protected:
@@ -49,19 +72,49 @@ protected:
class TileList;
//! \~\ingroup Console
//! \~\brief
//! \~english Scroll bar tile used by list-like widgets.
//! \~russian Тайловая полоса прокрутки для списковых виджетов.
class PIP_CONSOLE_EXPORT TileScrollBar: public PIScreenTile {
PIOBJECT_SUBCLASS(TileScrollBar, PIScreenTile);
friend class TileList;
public:
//! \~english Constructs a scroll bar tile.
//! \~russian Создает тайл полосы прокрутки.
TileScrollBar(const PIString & n = PIString());
//! \~english Destroys the scroll bar tile.
//! \~russian Уничтожает тайл полосы прокрутки.
virtual ~TileScrollBar() {}
//! \~english Sets the minimum scroll value.
//! \~russian Устанавливает минимальное значение прокрутки.
void setMinimum(int v);
//! \~english Sets the maximum scroll value.
//! \~russian Устанавливает максимальное значение прокрутки.
void setMaximum(int v);
//! \~english Sets the current scroll value.
//! \~russian Устанавливает текущее значение прокрутки.
void setValue(int v);
//! \~english Returns the minimum scroll value.
//! \~russian Возвращает минимальное значение прокрутки.
int minimum() const { return minimum_; }
//! \~english Returns the maximum scroll value.
//! \~russian Возвращает максимальное значение прокрутки.
int maximum() const { return maximum_; }
//! \~english Returns the current scroll value.
//! \~russian Возвращает текущее значение прокрутки.
int value() const { return value_; }
//! \~english Thickness of the drawn bar in cells, perpendicular to the scroll direction.
//! \~russian Толщина отрисовываемой полосы в ячейках поперек направления прокрутки.
int thickness;
protected:
@@ -74,29 +127,68 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Scrollable list tile with optional row selection.
//! \~russian Прокручиваемый тайл списка с необязательным выбором строк.
class PIP_CONSOLE_EXPORT TileList: public PIScreenTile {
PIOBJECT_SUBCLASS(TileList, PIScreenTile);
public:
//! \~english Selection policy for list rows.
//! \~russian Режим выбора строк списка.
enum SelectionMode {
NoSelection,
SingleSelection,
MultiSelection
};
enum EventType {
SelectionChanged,
RowPressed
NoSelection /** \~english Rows are not selectable. \~russian Выбор строк отключен. */,
SingleSelection /** \~english At most one row can be selected. \~russian Можно выбрать не более одной строки. */,
MultiSelection /** \~english Multiple rows can be selected. \~russian Можно выбрать несколько строк. */
};
//! \~english Events emitted by the list tile.
//! \~russian События, генерируемые тайлом списка.
enum EventType {
SelectionChanged /** \~english Selection set changed. \~russian Изменился набор выбранных строк. */,
RowPressed /** \~english Current row was activated; event data stores the row index. \~russian Текущая строка была активирована; данные события содержат индекс строки. */
};
//! \~english Constructs a list tile with the specified selection mode.
//! \~russian Создает тайл списка с указанным режимом выбора.
TileList(const PIString & n = PIString(), SelectionMode sm = NoSelection);
//! \~english Destroys the list tile.
//! \~russian Уничтожает тайл списка.
virtual ~TileList() {}
//! \~english Row text with cell format.
//! \~russian Текст строки с форматом ячеек.
typedef PIPair<PIString, PIScreenTypes::CellFormat> Row;
//! \~english Rows displayed by the list.
//! \~russian Строки, отображаемые списком.
PIDeque<Row> content;
//! \~english Alignment used to draw row text.
//! \~russian Выравнивание, используемое при рисовании текста строк.
PIScreenTypes::Alignment alignment;
//! \~english Active row selection mode.
//! \~russian Текущий режим выбора строк.
SelectionMode selection_mode;
//! \~english Indexes of selected rows.
//! \~russian Индексы выбранных строк.
PISet<int> selected;
int lhei, cur, offset;
//! \~english Cached count of visible content rows between the top and bottom scroll markers.
//! \~russian Кэшированное количество видимых строк содержимого между верхней и нижней метками прокрутки.
int lhei;
//! \~english Index of the current row used for focus and activation.
//! \~russian Индекс текущей строки, используемой для фокуса и активации.
int cur;
//! \~english Index of the first row currently visible in the viewport.
//! \~russian Индекс первой строки, видимой в текущей области просмотра.
int offset;
protected:
void sizeHint(int & w, int & h) const override;
@@ -110,16 +202,34 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Push button tile.
//! \~russian Тайл кнопки.
class PIP_CONSOLE_EXPORT TileButton: public PIScreenTile {
PIOBJECT_SUBCLASS(TileButton, PIScreenTile);
public:
//! \~english Constructs a button tile.
//! \~russian Создает тайл кнопки.
TileButton(const PIString & n = PIString());
//! \~english Destroys the button tile.
//! \~russian Уничтожает тайл кнопки.
virtual ~TileButton() {}
//! \~english Events emitted by the button.
//! \~russian События, генерируемые кнопкой.
enum EventType {
ButtonClicked
ButtonClicked /** \~english Button was activated. \~russian Кнопка была активирована. */
};
//! \~english Text format of the button label.
//! \~russian Формат текста надписи кнопки.
PIScreenTypes::CellFormat format;
//! \~english Button caption.
//! \~russian Подпись кнопки.
PIString text;
protected:
@@ -130,18 +240,42 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Group of selectable buttons arranged in one tile.
//! \~russian Группа выбираемых кнопок, размещенных в одном тайле.
class PIP_CONSOLE_EXPORT TileButtons: public PIScreenTile {
PIOBJECT_SUBCLASS(TileButtons, PIScreenTile);
public:
//! \~english Constructs a button group tile.
//! \~russian Создает тайл группы кнопок.
TileButtons(const PIString & n = PIString());
//! \~english Destroys the button group tile.
//! \~russian Уничтожает тайл группы кнопок.
virtual ~TileButtons() {}
//! \~english Events emitted by the button group.
//! \~russian События, генерируемые группой кнопок.
enum EventType {
ButtonSelected
ButtonSelected /** \~english A button was selected; event data stores the button index. \~russian Кнопка была выбрана; данные события содержат индекс кнопки. */
};
//! \~english Button caption with cell format.
//! \~russian Подпись кнопки с форматом ячеек.
typedef PIPair<PIString, PIScreenTypes::CellFormat> Button;
//! \~english Alignment of the whole button group inside the tile bounds.
//! \~russian Выравнивание всей группы кнопок внутри границ тайла.
PIScreenTypes::Alignment alignment;
//! \~english Button definitions shown by the tile.
//! \~russian Описания кнопок, отображаемых тайлом.
PIVector<Button> content;
//! \~english Index of the currently highlighted button.
//! \~russian Индекс текущей подсвеченной кнопки.
int cur;
protected:
@@ -157,17 +291,38 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Check box tile.
//! \~russian Тайл флажка.
class PIP_CONSOLE_EXPORT TileCheck: public PIScreenTile {
PIOBJECT_SUBCLASS(TileCheck, PIScreenTile);
public:
//! \~english Constructs a check box tile.
//! \~russian Создает тайл флажка.
TileCheck(const PIString & n = PIString());
//! \~english Destroys the check box tile.
//! \~russian Уничтожает тайл флажка.
virtual ~TileCheck() {}
//! \~english Events emitted by the check box.
//! \~russian События, генерируемые флажком.
enum EventType {
Toggled
Toggled /** \~english Check state changed; event data stores the new boolean value. \~russian Состояние флажка изменилось; данные события содержат новое логическое значение. */
};
//! \~english Text format of the caption.
//! \~russian Формат текста подписи.
PIScreenTypes::CellFormat format;
//! \~english Caption displayed after the check mark.
//! \~russian Подпись, отображаемая после флажка.
PIString text;
//! \~english Current check state.
//! \~russian Текущее состояние флажка.
bool toggled;
protected:
@@ -178,16 +333,40 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Progress indicator tile.
//! \~russian Тайл индикатора прогресса.
class PIP_CONSOLE_EXPORT TileProgress: public PIScreenTile {
PIOBJECT_SUBCLASS(TileProgress, PIScreenTile);
public:
//! \~english Constructs a progress tile.
//! \~russian Создает тайл прогресса.
TileProgress(const PIString & n = PIString());
//! \~english Destroys the progress tile.
//! \~russian Уничтожает тайл прогресса.
virtual ~TileProgress() {}
//! \~english Text format used for the overlaid label.
//! \~russian Формат текста, используемый для наложенной подписи.
PIScreenTypes::CellFormat format;
//! \~english Text shown before the numeric value.
//! \~russian Текст, отображаемый перед числовым значением.
PIString prefix;
//! \~english Text shown after the numeric value.
//! \~russian Текст, отображаемый после числового значения.
PIString suffix;
//! \~english Value treated as 100 percent.
//! \~russian Значение, принимаемое за 100 процентов.
double maximum;
//! \~english Current progress value.
//! \~russian Текущее значение прогресса.
double value;
protected:
@@ -196,13 +375,28 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Log view tile backed by the global %PICout buffer.
//! \~russian Тайл журнала, использующий глобальный буфер %PICout.
class PIP_CONSOLE_EXPORT TilePICout: public TileList {
PIOBJECT_SUBCLASS(TilePICout, PIScreenTile);
public:
//! \~english Constructs a %PICout viewer tile.
//! \~russian Создает тайл просмотра %PICout.
TilePICout(const PIString & n = PIString());
//! \~english Destroys the %PICout viewer tile.
//! \~russian Уничтожает тайл просмотра %PICout.
virtual ~TilePICout() {}
//! \~english Format applied to appended log lines.
//! \~russian Формат, применяемый к добавляемым строкам журнала.
PIScreenTypes::CellFormat format;
//! \~english Maximum number of lines retained from the %PICout buffer.
//! \~russian Максимальное количество строк, сохраняемых из буфера %PICout.
int max_lines;
protected:
@@ -211,14 +405,32 @@ protected:
};
//! \~\ingroup Console
//! \~\brief
//! \~english Single-line editable text input tile.
//! \~russian Однострочный тайл редактируемого текстового ввода.
class PIP_CONSOLE_EXPORT TileInput: public PIScreenTile {
PIOBJECT_SUBCLASS(TileInput, PIScreenTile);
public:
//! \~english Constructs an input tile.
//! \~russian Создает тайл ввода.
TileInput(const PIString & n = PIString());
//! \~english Destroys the input tile.
//! \~russian Уничтожает тайл ввода.
virtual ~TileInput() {}
//! \~english Format of the entered text.
//! \~russian Формат вводимого текста.
PIScreenTypes::CellFormat format;
//! \~english Current input text.
//! \~russian Текущий введенный текст.
PIString text;
//! \~english Maximum input length setting reserved for the tile logic.
//! \~russian Параметр максимальной длины ввода, зарезервированный для логики тайла.
int max_length;
protected:

View File

@@ -1,9 +1,11 @@
/*! \file piscreentypes.h
* \ingroup Console
* \~\brief
* \~english Types for PIScreen
* \~russian Типы для PIScreen
*/
//! \~\file piscreentypes.h
//! \~\ingroup Console
//! \brief
//! \~english Types for PIScreen
//! \~russian Типы для PIScreen
//! \details
//! \~english Provides common types used by screen tiles and drawer.
//! \~russian Обеспечивает общие типы, используемые тайлами и отрисовщиком экрана.
/*
PIP - Platform Independent Primitives
Types for PIScreen
@@ -32,92 +34,160 @@
class PIScreenTile;
//! \relatesalso PIScreenTile
//! \~english Namespace with shared screen cells, layout flags, and tile event types.
//! \~russian Пространство имен с общими типами экранных ячеек, флагами компоновки и событиями тайлов.
namespace PIScreenTypes {
//! Color for chars or background
//! \~english Color for a character or its background.
//! \~russian Цвет символа или его фона.
enum Color {
Default /** Default */,
Black /** Black */,
Red /** Red */,
Green /** Green */,
Blue /** Blue */,
Cyan /** Cyan */,
Magenta /** Magenta */,
Yellow /** Yellow */,
White /** White */,
Transparent /** Save previous color */
Default /** \~english Terminal default color \~russian Цвет терминала по умолчанию */,
Black /** \~english Black \~russian Черный */,
Red /** \~english Red \~russian Красный */,
Green /** \~english Green \~russian Зеленый */,
Blue /** \~english Blue \~russian Синий */,
Cyan /** \~english Cyan \~russian Голубой */,
Magenta /** \~english Magenta \~russian Пурпурный */,
Yellow /** \~english Yellow \~russian Желтый */,
White /** \~english White \~russian Белый */,
Transparent /** \~english Preserve the background already stored in the target cell \~russian Сохранить фон, уже записанный в целевой
ячейке */
};
//! Flags for chars
//! \~english Character formatting flags.
//! \~russian Флаги оформления символа.
enum CharFlag {
Bold /** Bold or bright */ = 0x1,
Blink /** Blink text */ = 0x2,
Underline /** Underline text */ = 0x4,
Inverse = 0x08
Bold = 0x1 /** \~english Bold or bright text \~russian Жирный или яркий текст */,
Blink = 0x2 /** \~english Blinking text \~russian Мигание текста */,
Underline = 0x4 /** \~english Underlined text \~russian Подчеркнутый текст */,
Inverse = 0x08 /** \~english Inverted foreground and background \~russian Инвертированные цвета текста и фона */
};
//! Alignment
//! \~english Horizontal text alignment inside a tile.
//! \~russian Горизонтальное выравнивание текста внутри тайла.
enum Alignment {
Left /** Left */,
Center /** Center */,
Right /** Right */
Left /** \~english Left alignment \~russian Выравнивание влево */,
Center /** \~english Center alignment \~russian Выравнивание по центру */,
Right /** \~english Right alignment \~russian Выравнивание вправо */
};
//! Size policy
//! \~english Layout policy used by parent tiles.
//! \~russian Политика размера, используемая родительскими тайлами при компоновке.
enum SizePolicy {
Fixed /** Fixed size */,
Preferred /** Preferred size */,
Expanding /** Maximum available size */,
Ignore /** Ignore layout logic */
Fixed /** \~english Keep the requested size \~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 Не участвовать в автоматической компоновке;
геометрию нужно задавать вручную */
};
//! Direction
//! \~english Child layout direction.
//! \~russian Направление раскладки дочерних тайлов.
enum Direction {
Horizontal /** Horizontal */,
Vertical /** Vertical */
Horizontal /** \~english Horizontal layout \~russian Горизонтальная раскладка */,
Vertical /** \~english Vertical layout \~russian Вертикальная раскладка */
};
//! Focus flags
//! \~english Focus and navigation flags for tiles.
//! \~russian Флаги фокуса и навигации для тайлов.
enum FocusFlag {
CanHasFocus /** Tile can has focus */ = 0x1,
NextByTab /** Focus passed to next tile by tab key */ = 0x2,
NextByArrowsHorizontal /** Focus passed to next tile by arrow keys left or right */ = 0x4,
NextByArrowsVertical /** Focus passed to next tile by arrow keys up or down */ = 0x8,
NextByArrowsAll /** Focus passed to next tile by any arrow key */ = NextByArrowsHorizontal | NextByArrowsVertical,
FocusOnMouse /** Tile focused on mouse press */ = 0x10,
FocusOnWheel /** Tile focused on wheel */ = 0x20,
FocusOnMouseOrWheel /** Tile focused on mouse press or wheel */ = FocusOnMouse | FocusOnWheel
CanHasFocus = 0x1 /** \~english Tile can receive focus \~russian Тайл может получать фокус */,
NextByTab = 0x2 /** \~english Tab moves focus to the next tile \~russian Клавиша Tab переводит фокус к следующему тайлу */,
NextByArrowsHorizontal = 0x4 /** \~english Left and right arrows move focus \~russian Стрелки влево и вправо переводят фокус */,
NextByArrowsVertical = 0x8 /** \~english Up and down arrows move focus \~russian Стрелки вверх и вниз переводят фокус */,
NextByArrowsAll /** \~english Any arrow key moves focus \~russian Любая стрелка переводит фокус */ =
NextByArrowsHorizontal | NextByArrowsVertical,
FocusOnMouse = 0x10 /** \~english Mouse press gives focus to the tile \~russian Нажатие мышью переводит фокус на тайл */,
FocusOnWheel = 0x20 /** \~english Mouse wheel gives focus to the tile \~russian Колесо мыши переводит фокус на тайл */,
FocusOnMouseOrWheel /** \~english Mouse press or wheel gives focus to the tile \~russian Нажатие мышью или колесо переводят фокус на
тайл */
= FocusOnMouse | FocusOnWheel
};
//! \~english Combination of \a CharFlag values.
//! \~russian Комбинация значений \a CharFlag.
typedef PIFlags<CharFlag> CharFlags;
//! \~english Combination of \a FocusFlag values.
//! \~russian Комбинация значений \a FocusFlag.
typedef PIFlags<FocusFlag> FocusFlags;
//! \~\brief
//! \~english Packed character formatting used by screen cells.
//! \~russian Упакованное описание оформления символа, используемое экранными ячейками.
union PIP_CONSOLE_EXPORT CellFormat {
//! \~english Constructs a format from the raw packed value.
//! \~russian Создает формат из упакованного сырого значения.
CellFormat(ushort f = 0) { raw_format = f; }
//! \~english Constructs a format from foreground color, background color, and character flags.
//! \~russian Создает формат из цвета символа, цвета фона и флагов оформления.
CellFormat(Color col_char, Color col_back = Default, CharFlags flags_ = 0) {
color_char = col_char;
color_back = col_back;
flags = flags_;
}
//! \~english Raw packed representation of the format.
//! \~russian Сырое упакованное представление формата.
ushort raw_format;
struct {
//! \~english Foreground color from \a Color.
//! \~russian Цвет символа из \a Color.
ushort color_char: 4;
//! \~english Background color from \a Color.
//! \~russian Цвет фона из \a Color.
ushort color_back: 4;
ushort flags : 8;
//! \~english Combination of \a CharFlag values.
//! \~russian Комбинация значений \a CharFlag.
ushort flags: 8;
};
//! \~english Returns \b true when two formats are identical.
//! \~russian Возвращает \b true, если два формата совпадают.
bool operator==(const CellFormat & c) const { return raw_format == c.raw_format; }
//! \~english Returns \b true when two formats differ.
//! \~russian Возвращает \b true, если форматы различаются.
bool operator!=(const CellFormat & c) const { return raw_format != c.raw_format; }
};
//! \~\brief
//! \~english One character cell of the console screen.
//! \~russian Одна символьная ячейка консольного экрана.
struct PIP_CONSOLE_EXPORT Cell {
//! \~english Constructs a cell from a symbol and its format.
//! \~russian Создает ячейку из символа и его формата.
Cell(PIChar c = PIChar(' '), CellFormat f = CellFormat()) {
symbol = c;
format = f;
}
//! \~english Cell formatting.
//! \~russian Формат ячейки.
CellFormat format;
//! \~english Character stored in the cell.
//! \~russian Символ, хранимый в ячейке.
PIChar symbol;
//! \~english Returns \b true when symbol and format match.
//! \~russian Возвращает \b true, если совпадают символ и формат.
bool operator==(const Cell & c) const { return format == c.format && symbol == c.symbol; }
//! \~english Returns \b true when symbol or format differs.
//! \~russian Возвращает \b true, если символ или формат различаются.
bool operator!=(const Cell & c) const { return format != c.format || symbol != c.symbol; }
//! \~english Assigns a cell, preserving the current background when source background is \a Transparent.
//! \~russian Присваивает ячейку, сохраняя текущий фон, если у источника фон равен \a Transparent.
Cell & operator=(const Cell & c) {
symbol = c.symbol;
if (c.format.color_back == Transparent) {
@@ -129,18 +199,46 @@ struct PIP_CONSOLE_EXPORT Cell {
}
};
//! \~\brief
//! \~english User-defined event raised by a tile.
//! \~russian Пользовательское событие, поднимаемое тайлом.
struct PIP_CONSOLE_EXPORT TileEvent {
//! \~english Constructs an event with numeric type and optional payload.
//! \~russian Создает событие с числовым типом и необязательными данными.
TileEvent(int t = -1, const PIVariant & d = PIVariant()): type(t), data(d) {}
//! \~english Event type chosen by the tile implementation.
//! \~russian Тип события, выбираемый реализацией тайла.
int type;
//! \~english Optional event payload.
//! \~russian Необязательные данные события.
PIVariant data;
};
//! \~\brief
//! \~english Base interface used by tiles to notify the owning screen about focus, removal, and custom events.
//! \~russian Базовый интерфейс, через который тайлы уведомляют владеющий экран о фокусе, удалении и пользовательских событиях.
class PIP_CONSOLE_EXPORT PIScreenBase {
public:
//! \~english Constructs an empty screen bridge.
//! \~russian Создает пустой мост к экрану.
PIScreenBase() {}
//! \~english Destroys the screen bridge.
//! \~russian Уничтожает мост к экрану.
virtual ~PIScreenBase() {}
//! \~english Called when a tile raises a custom event.
//! \~russian Вызывается, когда тайл поднимает пользовательское событие.
virtual void tileEventInternal(PIScreenTile *, TileEvent) {}
//! \~english Called when a tile is removed from the screen tree.
//! \~russian Вызывается при удалении тайла из дерева экрана.
virtual void tileRemovedInternal(PIScreenTile *) {}
//! \~english Called when a tile requests focus.
//! \~russian Вызывается, когда тайл запрашивает фокус.
virtual void tileSetFocusInternal(PIScreenTile *) {}
};

View File

@@ -1,9 +1,8 @@
/*! \file piterminal.h
* \ingroup Console
* \~\brief
* \~english Virtual terminal
* \~russian Виртуальный терминал
*/
//! \~\file piterminal.h
//! \~\ingroup Console
//! \brief
//! \~english Virtual terminal
//! \~russian Виртуальный терминал
/*
PIP - Platform Independent Primitives
Virtual terminal
@@ -31,26 +30,65 @@
#include "piscreentypes.h"
//! \~\ingroup Console
//! \~\brief
//! \~english Virtual terminal that runs a shell and mirrors its screen into a cell buffer.
//! \~russian Виртуальный терминал, который запускает оболочку и отражает ее экран в буфер ячеек.
//! \details
//! \~english Provides terminal emulation for reading console input and output. Supports ANSI escape sequences for cursor movement, colors,
//! and text formatting.
//! \~russian Обеспечивает эмуляцию терминала для чтения ввода и вывода консоли. Поддерживает ANSI escape-последовательности для перемещения
//! курсора, цветов и форматирования текста.
class PIP_CONSOLE_EXPORT PITerminal: public PIThread {
PIOBJECT_SUBCLASS(PITerminal, PIThread);
public:
//! Constructs %PITerminal
//! \~english Constructs %PITerminal.
//! \~russian Создает %PITerminal.
PITerminal();
//! \~english Destroys the terminal and releases backend resources.
//! \~russian Уничтожает терминал и освобождает внутренние ресурсы.
~PITerminal();
//! \~english Returns terminal width in columns.
//! \~russian Возвращает ширину терминала в столбцах.
int columns() const { return size_x; }
//! \~english Returns terminal height in rows.
//! \~russian Возвращает высоту терминала в строках.
int rows() const { return size_y; }
//! \~english Resizes the terminal viewport and backing cell buffer.
//! \~russian Изменяет размер области терминала и связанного буфера ячеек.
bool resize(int cols, int rows);
//! \~english Sends raw byte data to the terminal input.
//! \~russian Отправляет необработанные байты во входной поток терминала.
void write(const PIByteArray & d);
//! \~english Sends a special key with modifiers to the terminal.
//! \~russian Отправляет в терминал специальную клавишу с модификаторами.
void write(PIKbdListener::SpecialKey k, PIKbdListener::KeyModifiers m);
//! \~english Sends a keyboard event to the terminal.
//! \~russian Отправляет событие клавиатуры в терминал.
void write(PIKbdListener::KeyEvent ke);
//! \~english Returns the current terminal screen snapshot, including cursor blink state.
//! \~russian Возвращает текущий снимок экрана терминала с учетом состояния мигания курсора.
PIVector<PIVector<PIScreenTypes::Cell>> content();
//! \~english Returns whether key code `k` is handled as a special terminal key.
//! \~russian Возвращает, обрабатывается ли код `k` как специальная клавиша терминала.
static bool isSpecialKey(int k);
//! \~english Initializes the terminal backend and starts the polling thread.
//! \~russian Инициализирует внутренний терминал и запускает поток опроса.
bool initialize();
//! \~english Stops the terminal and destroys the internal terminal backend instance.
//! \~russian Останавливает терминал и уничтожает внутреннюю реализацию терминала.
void destroy();
private: