From 69acefba56c460aecd55a7982a37f5aa36fa9d09 Mon Sep 17 00:00:00 2001 From: Muse Date: Wed, 25 Nov 2026 21:26:02 -0500 Subject: [PATCH] Instrumentation Group G: 14/16-segment alphanumeric LED displays (12 widgets) + docs + icons + tests --- docs/instrumentation-segments.md | 434 ++++++++ .../InstSeg14Display1/CMakeLists.txt | 13 + .../InstSeg14Display1/InstSeg14Display1.h | 355 +++++++ .../InstSeg14Display1/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display1.cpp | 54 + .../InstSeg14Display2/CMakeLists.txt | 13 + .../InstSeg14Display2/InstSeg14Display2.h | 355 +++++++ .../InstSeg14Display2/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display2.cpp | 54 + .../InstSeg14Display3/CMakeLists.txt | 13 + .../InstSeg14Display3/InstSeg14Display3.h | 355 +++++++ .../InstSeg14Display3/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display3.cpp | 54 + .../InstSeg14Display4/CMakeLists.txt | 13 + .../InstSeg14Display4/InstSeg14Display4.h | 355 +++++++ .../InstSeg14Display4/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display4.cpp | 54 + .../InstSeg14Display5/CMakeLists.txt | 13 + .../InstSeg14Display5/InstSeg14Display5.h | 355 +++++++ .../InstSeg14Display5/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display5.cpp | 54 + .../InstSeg14Display6/CMakeLists.txt | 13 + .../InstSeg14Display6/InstSeg14Display6.h | 355 +++++++ .../InstSeg14Display6/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg14Display6.cpp | 54 + .../InstSeg16Display1/CMakeLists.txt | 13 + .../InstSeg16Display1/InstSeg16Display1.h | 355 +++++++ .../InstSeg16Display1/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display1.cpp | 54 + .../InstSeg16Display2/CMakeLists.txt | 13 + .../InstSeg16Display2/InstSeg16Display2.h | 355 +++++++ .../InstSeg16Display2/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display2.cpp | 54 + .../InstSeg16Display3/CMakeLists.txt | 13 + .../InstSeg16Display3/InstSeg16Display3.h | 355 +++++++ .../InstSeg16Display3/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display3.cpp | 54 + .../InstSeg16Display4/CMakeLists.txt | 13 + .../InstSeg16Display4/InstSeg16Display4.h | 355 +++++++ .../InstSeg16Display4/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display4.cpp | 54 + .../InstSeg16Display5/CMakeLists.txt | 13 + .../InstSeg16Display5/InstSeg16Display5.h | 355 +++++++ .../InstSeg16Display5/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display5.cpp | 54 + .../InstSeg16Display6/CMakeLists.txt | 13 + .../InstSeg16Display6/InstSeg16Display6.h | 355 +++++++ .../InstSeg16Display6/core/xframe_core.h | 988 ++++++++++++++++++ .../main_InstSeg16Display6.cpp | 54 + widgets/icons/InstSeg14Display1.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg14Display2.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg14Display3.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg14Display4.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg14Display5.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg14Display6.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display1.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display2.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display3.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display4.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display5.ico | Bin 0 -> 862 bytes widgets/icons/InstSeg16Display6.ico | Bin 0 -> 862 bytes widgets/tests/test_inst_group_g.cpp | 259 +++++ widgets/tests/test_inst_group_g.py | 188 ++++ widgets/tools/glyphs_inst.py | 97 +- 64 files changed, 17892 insertions(+), 6 deletions(-) create mode 100644 docs/instrumentation-segments.md create mode 100644 widgets/components/InstSeg14Display1/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display1/InstSeg14Display1.h create mode 100644 widgets/components/InstSeg14Display1/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display1/main_InstSeg14Display1.cpp create mode 100644 widgets/components/InstSeg14Display2/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display2/InstSeg14Display2.h create mode 100644 widgets/components/InstSeg14Display2/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display2/main_InstSeg14Display2.cpp create mode 100644 widgets/components/InstSeg14Display3/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display3/InstSeg14Display3.h create mode 100644 widgets/components/InstSeg14Display3/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display3/main_InstSeg14Display3.cpp create mode 100644 widgets/components/InstSeg14Display4/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display4/InstSeg14Display4.h create mode 100644 widgets/components/InstSeg14Display4/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display4/main_InstSeg14Display4.cpp create mode 100644 widgets/components/InstSeg14Display5/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display5/InstSeg14Display5.h create mode 100644 widgets/components/InstSeg14Display5/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display5/main_InstSeg14Display5.cpp create mode 100644 widgets/components/InstSeg14Display6/CMakeLists.txt create mode 100644 widgets/components/InstSeg14Display6/InstSeg14Display6.h create mode 100644 widgets/components/InstSeg14Display6/core/xframe_core.h create mode 100644 widgets/components/InstSeg14Display6/main_InstSeg14Display6.cpp create mode 100644 widgets/components/InstSeg16Display1/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display1/InstSeg16Display1.h create mode 100644 widgets/components/InstSeg16Display1/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display1/main_InstSeg16Display1.cpp create mode 100644 widgets/components/InstSeg16Display2/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display2/InstSeg16Display2.h create mode 100644 widgets/components/InstSeg16Display2/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display2/main_InstSeg16Display2.cpp create mode 100644 widgets/components/InstSeg16Display3/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display3/InstSeg16Display3.h create mode 100644 widgets/components/InstSeg16Display3/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display3/main_InstSeg16Display3.cpp create mode 100644 widgets/components/InstSeg16Display4/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display4/InstSeg16Display4.h create mode 100644 widgets/components/InstSeg16Display4/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display4/main_InstSeg16Display4.cpp create mode 100644 widgets/components/InstSeg16Display5/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display5/InstSeg16Display5.h create mode 100644 widgets/components/InstSeg16Display5/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display5/main_InstSeg16Display5.cpp create mode 100644 widgets/components/InstSeg16Display6/CMakeLists.txt create mode 100644 widgets/components/InstSeg16Display6/InstSeg16Display6.h create mode 100644 widgets/components/InstSeg16Display6/core/xframe_core.h create mode 100644 widgets/components/InstSeg16Display6/main_InstSeg16Display6.cpp create mode 100644 widgets/icons/InstSeg14Display1.ico create mode 100644 widgets/icons/InstSeg14Display2.ico create mode 100644 widgets/icons/InstSeg14Display3.ico create mode 100644 widgets/icons/InstSeg14Display4.ico create mode 100644 widgets/icons/InstSeg14Display5.ico create mode 100644 widgets/icons/InstSeg14Display6.ico create mode 100644 widgets/icons/InstSeg16Display1.ico create mode 100644 widgets/icons/InstSeg16Display2.ico create mode 100644 widgets/icons/InstSeg16Display3.ico create mode 100644 widgets/icons/InstSeg16Display4.ico create mode 100644 widgets/icons/InstSeg16Display5.ico create mode 100644 widgets/icons/InstSeg16Display6.ico create mode 100644 widgets/tests/test_inst_group_g.cpp create mode 100644 widgets/tests/test_inst_group_g.py diff --git a/docs/instrumentation-segments.md b/docs/instrumentation-segments.md new file mode 100644 index 0000000..0fe1a96 --- /dev/null +++ b/docs/instrumentation-segments.md @@ -0,0 +1,434 @@ +# Instrumentation widgets — higher-segment alphanumeric LED displays (Group G) + +Twelve widgets in `widgets/components/`, one per directory. Each directory +contains exactly `.h`, `main_.cpp`, `CMakeLists.txt`, and +`core/xframe_core.h` (byte-identical to `widgets/core/xframe_core.h`). +Attribution: XFrame. + +Group G extends the Instrumentation section (see `docs/instrumentation.md` +for the plan): the higher-segment displays that can roughly show +alphanumeric text — 14-segment in 1–6 digit variants, and 16-segment in +1–6 digit variants. The honest word is "roughly": a segment display is +not a dot matrix, and the tables below say exactly which characters each +type shows well, which it only approximates, and which it cannot show at +all. Standard XFrame hand-drawn style, no photorealism. Demos use +deterministic strings ("HELLO", "ABC123", "42.5"). + +## Common API (all twelve) + +Constructor (all widgets): + +```cpp +Name(Display* display, int screen, Window window, GC gc, + SStyle_Manager* styles, int x, int y, int width, int height); +``` + +Key methods, identical on every widget: + +- `void set_value(const std::string& v)` / `std::string get_value() const` — the displayed string; normalised to uppercase, truncated to the digit count, characters with no approximation dropped, `.`/`:` become a decimal-point dot after the previous digit. +- `std::string shown_text() const` — the string actually shown, padded with spaces to the digit count. +- `int cell_count() const`, `char char_at(int i) const`. +- `static bool segment_on(char ch, const std::string& seg)` — is that segment lit for that character? +- `static bool renders_clean(char ch)` / `renders_approx(char ch)` / `renders_blank(char ch)`; `static std::string clean_repertoire()` / `approx_repertoire()` / `cannot_repertoire()`. +- `static constexpr int kDigits`, `static constexpr int kSegments` (14 or 16), `static const char* default_value()`. +- `void draw()` — redraws the widget. +- `bool on_button_press(int x, int y, unsigned int button)` — click focuses the widget and fires `on_click`; `bool on_button_release(...)`, `bool on_motion(int x, int y)` — hover tracking. +- `bool on_key(KeySym key, const char* str)` — only when focused: Up/Right steps the last displayed character (digit wraps 9→0, letter wraps Z→A), Down/Left steps it down, Home restores the default demo string, Return/Space fires `on_click`. +- `std::function on_click`, `void set_bounds(...)`, `width()`, `height()`, `contains(x, y)`, `set_visible`/`get_visible`, `set_enabled`/`get_enabled`, `set_style_name`, `set_text`/`get_text`, `style()`. + +Build one widget (from the repo root, on the server): + +``` +cmake -S widgets/components/InstSeg14Display4 -B /tmp/b-seg14-4 -DCMAKE_CXX_FLAGS="-Wall -Wextra" +cmake --build /tmp/b-seg14-4 # 0 warnings +``` + +Run the whole group (build + harness + demos + doc examples): + +``` +python3 widgets/tests/test_inst_group_g.py # ALL PASS, 12/12 widgets +``` + +## InstSeg14Display1 + + +14-segment alphanumeric LED display, 1 digit. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `A`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display1 w(display, screen, window, gc, &styles, 20, 20, 90, 110); +w.set_value("A"); +w.draw(); +``` + + +## InstSeg14Display2 + + +14-segment alphanumeric LED display, 2 digits. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `42`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display2 w(display, screen, window, gc, &styles, 20, 20, 140, 110); +w.set_value("42"); +w.draw(); +``` + + +## InstSeg14Display3 + + +14-segment alphanumeric LED display, 3 digits. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `ABC`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display3 w(display, screen, window, gc, &styles, 20, 20, 190, 110); +w.set_value("ABC"); +w.draw(); +``` + + +## InstSeg14Display4 + + +14-segment alphanumeric LED display, 4 digits. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `HELL`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display4 w(display, screen, window, gc, &styles, 20, 20, 240, 110); +w.set_value("HELL"); +w.draw(); +``` + + +## InstSeg14Display5 + + +14-segment alphanumeric LED display, 5 digits. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `HELLO`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display5 w(display, screen, window, gc, &styles, 20, 20, 290, 110); +w.set_value("HELLO"); +w.draw(); +``` + + +## InstSeg14Display6 + + +14-segment alphanumeric LED display, 6 digits. The classic +14-segment font: the seven bars plus two half middle bars, two centre +verticals and four diagonals. Shows A–Z, 0–9 and common punctuation +roughly — M and W are poor (no centre peak), and K, Q, R, V, Y and Z +are approximations. Demo string: `ABC123`. + + +Repertoire (14-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L O P S T U X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K M N Q R V W Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +M and W have no centre peak on 14 segments, so they read as rough approximations; K, Q, R, V, Y and Z need diagonals the font only hints at. + + +Example: + +```cpp +InstSeg14Display6 w(display, screen, window, gc, &styles, 20, 20, 340, 110); +w.set_value("ABC123"); +w.draw(); +``` + + +## InstSeg16Display1 + + +16-segment alphanumeric LED display, 1 digit. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `M`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display1 w(display, screen, window, gc, &styles, 20, 20, 90, 110); +w.set_value("M"); +w.draw(); +``` + + +## InstSeg16Display2 + + +16-segment alphanumeric LED display, 2 digits. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `MW`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display2 w(display, screen, window, gc, &styles, 20, 20, 140, 110); +w.set_value("MW"); +w.draw(); +``` + + +## InstSeg16Display3 + + +16-segment alphanumeric LED display, 3 digits. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `MWM`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display3 w(display, screen, window, gc, &styles, 20, 20, 190, 110); +w.set_value("MWM"); +w.draw(); +``` + + +## InstSeg16Display4 + + +16-segment alphanumeric LED display, 4 digits. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `MWMW`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display4 w(display, screen, window, gc, &styles, 20, 20, 240, 110); +w.set_value("MWMW"); +w.draw(); +``` + + +## InstSeg16Display5 + + +16-segment alphanumeric LED display, 5 digits. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `MWMWM`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display5 w(display, screen, window, gc, &styles, 20, 20, 290, 110); +w.set_value("MWMWM"); +w.draw(); +``` + + +## InstSeg16Display6 + + +16-segment alphanumeric LED display, 6 digits. The 14-segment +font with the top and bottom bars split in two, which — together with +the centre verticals — gives M and W a real middle peak and handles +more punctuation better. K, Q, R, V, Y and Z are still approximations. +Demo string: `MWMWMW`. + + +Repertoire (16-segment): + + +| Class | Characters | Notes | +|---|---|---| +| Clean | 0–9, A B C D E F G H I J L M O P S T U W X, - _ = + / | Render distinctly; verified pixel-distinct in the harness, except the look-alikes below. | +| Approximate | K N Q R V Y Z ' " : | Renders something recognisable, but only roughly. | +| Cannot show | ; , ? ! @ # $ % & * ( ) [ ] { } < > \ | ^ ` ~ | Renders blank (no lit segments). | +| Look-alikes | 0/O, 5/S, 6/G, J/U | Each pair renders identically on segment displays. | + +The split top/bottom bars plus the centre verticals give M and W a real middle peak, so they read cleanly here. K, Q, R, V, Y and Z are still only approximate. + + +Example: + +```cpp +InstSeg16Display6 w(display, screen, window, gc, &styles, 20, 20, 340, 110); +w.set_value("MWMWMW"); +w.draw(); +``` + diff --git a/widgets/components/InstSeg14Display1/CMakeLists.txt b/widgets/components/InstSeg14Display1/CMakeLists.txt new file mode 100644 index 0000000..08fe942 --- /dev/null +++ b/widgets/components/InstSeg14Display1/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display1 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display1 main_InstSeg14Display1.cpp) + +target_link_libraries(InstSeg14Display1 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display1/InstSeg14Display1.h b/widgets/components/InstSeg14Display1/InstSeg14Display1.h new file mode 100644 index 0000000..ae66164 --- /dev/null +++ b/widgets/components/InstSeg14Display1/InstSeg14Display1.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display1 - old 14-segment LED alphanumeric display, 1 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display1 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "A"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 1; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display1(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display1"; text_ = "InstSeg14Display1"; + } + ~InstSeg14Display1() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "A"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display1::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display1/core/xframe_core.h b/widgets/components/InstSeg14Display1/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display1/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display1/main_InstSeg14Display1.cpp b/widgets/components/InstSeg14Display1/main_InstSeg14Display1.cpp new file mode 100644 index 0000000..98d4273 --- /dev/null +++ b/widgets/components/InstSeg14Display1/main_InstSeg14Display1.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display1.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display1 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display1 widget(display, screen, window, gc, &styles, 20, 20, 90, 110); + widget.set_value("A"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg14Display2/CMakeLists.txt b/widgets/components/InstSeg14Display2/CMakeLists.txt new file mode 100644 index 0000000..518203b --- /dev/null +++ b/widgets/components/InstSeg14Display2/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display2 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display2 main_InstSeg14Display2.cpp) + +target_link_libraries(InstSeg14Display2 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display2/InstSeg14Display2.h b/widgets/components/InstSeg14Display2/InstSeg14Display2.h new file mode 100644 index 0000000..0548607 --- /dev/null +++ b/widgets/components/InstSeg14Display2/InstSeg14Display2.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display2 - old 14-segment LED alphanumeric display, 2 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display2 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "42"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 2; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display2(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display2"; text_ = "InstSeg14Display2"; + } + ~InstSeg14Display2() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "42"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display2::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display2/core/xframe_core.h b/widgets/components/InstSeg14Display2/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display2/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display2/main_InstSeg14Display2.cpp b/widgets/components/InstSeg14Display2/main_InstSeg14Display2.cpp new file mode 100644 index 0000000..d8ec58e --- /dev/null +++ b/widgets/components/InstSeg14Display2/main_InstSeg14Display2.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display2.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display2 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display2 widget(display, screen, window, gc, &styles, 20, 20, 140, 110); + widget.set_value("42"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg14Display3/CMakeLists.txt b/widgets/components/InstSeg14Display3/CMakeLists.txt new file mode 100644 index 0000000..a7ea98a --- /dev/null +++ b/widgets/components/InstSeg14Display3/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display3 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display3 main_InstSeg14Display3.cpp) + +target_link_libraries(InstSeg14Display3 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display3/InstSeg14Display3.h b/widgets/components/InstSeg14Display3/InstSeg14Display3.h new file mode 100644 index 0000000..c05565b --- /dev/null +++ b/widgets/components/InstSeg14Display3/InstSeg14Display3.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display3 - old 14-segment LED alphanumeric display, 3 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display3 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "ABC"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 3; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display3(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display3"; text_ = "InstSeg14Display3"; + } + ~InstSeg14Display3() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "ABC"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display3::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display3/core/xframe_core.h b/widgets/components/InstSeg14Display3/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display3/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display3/main_InstSeg14Display3.cpp b/widgets/components/InstSeg14Display3/main_InstSeg14Display3.cpp new file mode 100644 index 0000000..bbda606 --- /dev/null +++ b/widgets/components/InstSeg14Display3/main_InstSeg14Display3.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display3.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display3 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display3 widget(display, screen, window, gc, &styles, 20, 20, 190, 110); + widget.set_value("ABC"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg14Display4/CMakeLists.txt b/widgets/components/InstSeg14Display4/CMakeLists.txt new file mode 100644 index 0000000..d75c644 --- /dev/null +++ b/widgets/components/InstSeg14Display4/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display4 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display4 main_InstSeg14Display4.cpp) + +target_link_libraries(InstSeg14Display4 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display4/InstSeg14Display4.h b/widgets/components/InstSeg14Display4/InstSeg14Display4.h new file mode 100644 index 0000000..70cb6fe --- /dev/null +++ b/widgets/components/InstSeg14Display4/InstSeg14Display4.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display4 - old 14-segment LED alphanumeric display, 4 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display4 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "HELL"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 4; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display4(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display4"; text_ = "InstSeg14Display4"; + } + ~InstSeg14Display4() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "HELL"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display4::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display4/core/xframe_core.h b/widgets/components/InstSeg14Display4/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display4/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display4/main_InstSeg14Display4.cpp b/widgets/components/InstSeg14Display4/main_InstSeg14Display4.cpp new file mode 100644 index 0000000..1d90ed7 --- /dev/null +++ b/widgets/components/InstSeg14Display4/main_InstSeg14Display4.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display4.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display4 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display4 widget(display, screen, window, gc, &styles, 20, 20, 240, 110); + widget.set_value("HELL"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg14Display5/CMakeLists.txt b/widgets/components/InstSeg14Display5/CMakeLists.txt new file mode 100644 index 0000000..77c9166 --- /dev/null +++ b/widgets/components/InstSeg14Display5/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display5 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display5 main_InstSeg14Display5.cpp) + +target_link_libraries(InstSeg14Display5 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display5/InstSeg14Display5.h b/widgets/components/InstSeg14Display5/InstSeg14Display5.h new file mode 100644 index 0000000..63f806c --- /dev/null +++ b/widgets/components/InstSeg14Display5/InstSeg14Display5.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display5 - old 14-segment LED alphanumeric display, 5 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display5 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "HELLO"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 5; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display5(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display5"; text_ = "InstSeg14Display5"; + } + ~InstSeg14Display5() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "HELLO"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display5::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display5/core/xframe_core.h b/widgets/components/InstSeg14Display5/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display5/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display5/main_InstSeg14Display5.cpp b/widgets/components/InstSeg14Display5/main_InstSeg14Display5.cpp new file mode 100644 index 0000000..10d5c5a --- /dev/null +++ b/widgets/components/InstSeg14Display5/main_InstSeg14Display5.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display5.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display5 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display5 widget(display, screen, window, gc, &styles, 20, 20, 290, 110); + widget.set_value("HELLO"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg14Display6/CMakeLists.txt b/widgets/components/InstSeg14Display6/CMakeLists.txt new file mode 100644 index 0000000..2574971 --- /dev/null +++ b/widgets/components/InstSeg14Display6/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg14Display6 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg14Display6 main_InstSeg14Display6.cpp) + +target_link_libraries(InstSeg14Display6 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg14Display6/InstSeg14Display6.h b/widgets/components/InstSeg14Display6/InstSeg14Display6.h new file mode 100644 index 0000000..aabc550 --- /dev/null +++ b/widgets/components/InstSeg14Display6/InstSeg14Display6.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg14Display6 - old 14-segment LED alphanumeric display, 6 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 14-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (14-segment): +// Clean: 0123456789ABCDEFGHIJLOPSTUX +// Approximate (renders, but only roughly): KMNQRVWYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg14Display6 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "ABC123"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a b c d e f"}, + {'1', "b c"}, + {'2', "a b d e g1 g2"}, + {'3', "a b c d g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a c d f g1 g2"}, + {'6', "a c d e f g1 g2"}, + {'7', "a b c"}, + {'8', "a b c d e f g1 g2"}, + {'9', "a b c d f g1 g2"}, + {'=', "d g1 g2"}, + {'A', "a b c e f g1 g2"}, + {'B', "a b c d g1 g2 i l"}, + {'C', "a d e f"}, + {'D', "a b c d i l"}, + {'E', "a d e f g1 g2"}, + {'F', "a e f g1 g2"}, + {'G', "a c d e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d e"}, + {'K', "e f g1 j k"}, + {'L', "d e f"}, + {'M', "b c e f h j"}, + {'N', "b c e f h m"}, + {'O', "a b c d e f"}, + {'P', "a b e f g1 g2"}, + {'Q', "a b c d e f m"}, + {'R', "a b e f g1 g2 m"}, + {'S', "a c d f g1 g2"}, + {'T', "a i l"}, + {'U', "b c d e"}, + {'V', "c e j k"}, + {'W', "b c e f k m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a d j k"}, + {'_', "d"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 6; + static constexpr int kSegments = 14; + static const std::vector kSegIds; + std::function on_click; + + InstSeg14Display6(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg14Display6"; text_ = "InstSeg14Display6"; + } + ~InstSeg14Display6() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLOPSTUX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KMNQRVWYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLOPSTUX"; } + static std::string approx_repertoire() { return "KMNQRVWYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "ABC123"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg14Display6::kSegIds = {"a", "b", "c", "d", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg14Display6/core/xframe_core.h b/widgets/components/InstSeg14Display6/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg14Display6/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg14Display6/main_InstSeg14Display6.cpp b/widgets/components/InstSeg14Display6/main_InstSeg14Display6.cpp new file mode 100644 index 0000000..e07f516 --- /dev/null +++ b/widgets/components/InstSeg14Display6/main_InstSeg14Display6.cpp @@ -0,0 +1,54 @@ +#include "InstSeg14Display6.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg14Display6 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg14Display6 widget(display, screen, window, gc, &styles, 20, 20, 340, 110); + widget.set_value("ABC123"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display1/CMakeLists.txt b/widgets/components/InstSeg16Display1/CMakeLists.txt new file mode 100644 index 0000000..4bb9155 --- /dev/null +++ b/widgets/components/InstSeg16Display1/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display1 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display1 main_InstSeg16Display1.cpp) + +target_link_libraries(InstSeg16Display1 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display1/InstSeg16Display1.h b/widgets/components/InstSeg16Display1/InstSeg16Display1.h new file mode 100644 index 0000000..54e55bb --- /dev/null +++ b/widgets/components/InstSeg16Display1/InstSeg16Display1.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display1 - old 16-segment LED alphanumeric display, 1 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display1 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "M"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 1; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display1(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display1"; text_ = "InstSeg16Display1"; + } + ~InstSeg16Display1() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "M"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display1::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display1/core/xframe_core.h b/widgets/components/InstSeg16Display1/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display1/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display1/main_InstSeg16Display1.cpp b/widgets/components/InstSeg16Display1/main_InstSeg16Display1.cpp new file mode 100644 index 0000000..4eea4b9 --- /dev/null +++ b/widgets/components/InstSeg16Display1/main_InstSeg16Display1.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display1.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display1 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display1 widget(display, screen, window, gc, &styles, 20, 20, 90, 110); + widget.set_value("M"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display2/CMakeLists.txt b/widgets/components/InstSeg16Display2/CMakeLists.txt new file mode 100644 index 0000000..a68dc1d --- /dev/null +++ b/widgets/components/InstSeg16Display2/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display2 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display2 main_InstSeg16Display2.cpp) + +target_link_libraries(InstSeg16Display2 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display2/InstSeg16Display2.h b/widgets/components/InstSeg16Display2/InstSeg16Display2.h new file mode 100644 index 0000000..c3113f2 --- /dev/null +++ b/widgets/components/InstSeg16Display2/InstSeg16Display2.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display2 - old 16-segment LED alphanumeric display, 2 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display2 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "MW"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 2; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display2(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display2"; text_ = "InstSeg16Display2"; + } + ~InstSeg16Display2() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "MW"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display2::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display2/core/xframe_core.h b/widgets/components/InstSeg16Display2/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display2/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display2/main_InstSeg16Display2.cpp b/widgets/components/InstSeg16Display2/main_InstSeg16Display2.cpp new file mode 100644 index 0000000..c34c46c --- /dev/null +++ b/widgets/components/InstSeg16Display2/main_InstSeg16Display2.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display2.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display2 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display2 widget(display, screen, window, gc, &styles, 20, 20, 140, 110); + widget.set_value("MW"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display3/CMakeLists.txt b/widgets/components/InstSeg16Display3/CMakeLists.txt new file mode 100644 index 0000000..f1aada3 --- /dev/null +++ b/widgets/components/InstSeg16Display3/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display3 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display3 main_InstSeg16Display3.cpp) + +target_link_libraries(InstSeg16Display3 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display3/InstSeg16Display3.h b/widgets/components/InstSeg16Display3/InstSeg16Display3.h new file mode 100644 index 0000000..fffd933 --- /dev/null +++ b/widgets/components/InstSeg16Display3/InstSeg16Display3.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display3 - old 16-segment LED alphanumeric display, 3 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display3 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "MWM"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 3; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display3(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display3"; text_ = "InstSeg16Display3"; + } + ~InstSeg16Display3() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "MWM"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display3::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display3/core/xframe_core.h b/widgets/components/InstSeg16Display3/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display3/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display3/main_InstSeg16Display3.cpp b/widgets/components/InstSeg16Display3/main_InstSeg16Display3.cpp new file mode 100644 index 0000000..32badbe --- /dev/null +++ b/widgets/components/InstSeg16Display3/main_InstSeg16Display3.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display3.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display3 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display3 widget(display, screen, window, gc, &styles, 20, 20, 190, 110); + widget.set_value("MWM"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display4/CMakeLists.txt b/widgets/components/InstSeg16Display4/CMakeLists.txt new file mode 100644 index 0000000..acaa272 --- /dev/null +++ b/widgets/components/InstSeg16Display4/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display4 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display4 main_InstSeg16Display4.cpp) + +target_link_libraries(InstSeg16Display4 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display4/InstSeg16Display4.h b/widgets/components/InstSeg16Display4/InstSeg16Display4.h new file mode 100644 index 0000000..d9bd023 --- /dev/null +++ b/widgets/components/InstSeg16Display4/InstSeg16Display4.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display4 - old 16-segment LED alphanumeric display, 4 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display4 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "MWMW"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 4; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display4(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display4"; text_ = "InstSeg16Display4"; + } + ~InstSeg16Display4() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "MWMW"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display4::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display4/core/xframe_core.h b/widgets/components/InstSeg16Display4/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display4/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display4/main_InstSeg16Display4.cpp b/widgets/components/InstSeg16Display4/main_InstSeg16Display4.cpp new file mode 100644 index 0000000..cad76b7 --- /dev/null +++ b/widgets/components/InstSeg16Display4/main_InstSeg16Display4.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display4.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display4 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display4 widget(display, screen, window, gc, &styles, 20, 20, 240, 110); + widget.set_value("MWMW"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display5/CMakeLists.txt b/widgets/components/InstSeg16Display5/CMakeLists.txt new file mode 100644 index 0000000..3b097ae --- /dev/null +++ b/widgets/components/InstSeg16Display5/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display5 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display5 main_InstSeg16Display5.cpp) + +target_link_libraries(InstSeg16Display5 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display5/InstSeg16Display5.h b/widgets/components/InstSeg16Display5/InstSeg16Display5.h new file mode 100644 index 0000000..7d74ffd --- /dev/null +++ b/widgets/components/InstSeg16Display5/InstSeg16Display5.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display5 - old 16-segment LED alphanumeric display, 5 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display5 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "MWMWM"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 5; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display5(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display5"; text_ = "InstSeg16Display5"; + } + ~InstSeg16Display5() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "MWMWM"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display5::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display5/core/xframe_core.h b/widgets/components/InstSeg16Display5/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display5/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display5/main_InstSeg16Display5.cpp b/widgets/components/InstSeg16Display5/main_InstSeg16Display5.cpp new file mode 100644 index 0000000..4bfdceb --- /dev/null +++ b/widgets/components/InstSeg16Display5/main_InstSeg16Display5.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display5.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display5 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display5 widget(display, screen, window, gc, &styles, 20, 20, 290, 110); + widget.set_value("MWMWM"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/components/InstSeg16Display6/CMakeLists.txt b/widgets/components/InstSeg16Display6/CMakeLists.txt new file mode 100644 index 0000000..0ecd894 --- /dev/null +++ b/widgets/components/InstSeg16Display6/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(InstSeg16Display6 LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(InstSeg16Display6 main_InstSeg16Display6.cpp) + +target_link_libraries(InstSeg16Display6 PRIVATE X11::X11) diff --git a/widgets/components/InstSeg16Display6/InstSeg16Display6.h b/widgets/components/InstSeg16Display6/InstSeg16Display6.h new file mode 100644 index 0000000..4d19ba0 --- /dev/null +++ b/widgets/components/InstSeg16Display6/InstSeg16Display6.h @@ -0,0 +1,355 @@ +#pragma once + +#include "core/xframe_core.h" +#include "../InstData.h" + +#include +#include +#include +#include +#include +#include + +// InstSeg16Display6 - old 16-segment LED alphanumeric display, 6 digit(s), +// vintage amber LED style: dark bezel, lit segments bright amber, unlit +// segments faint. Shows a string value (set_value/get_value); characters +// outside the 16-segment repertoire render as their closest +// approximation, or blank when no approximation exists. +// Repertoire (16-segment): +// Clean: 0123456789ABCDEFGHIJLMOPSTUWX +// Approximate (renders, but only roughly): KNQRVYZ'": +// Cannot show (renders blank): ;,?!@#$%&*()[]{}<>\|^`~ +// Known look-alikes: '0'/'O', '5'/'S', '6'/'G', 'J'/'U' render identically. +// Lowercase is shown as uppercase. +// Attribution: XFrame. +class InstSeg16Display6 { +private: + Display* display_; + int screen_; + Window window_; + GC gc_; + SStyle_Manager* styles_; + int x1_, y1_, x2_, y2_; + std::string name_; + std::string text_; + std::string style_name_; + bool visible_ = true; + bool enabled_ = true; + bool focused_ = false; + bool pressed_ = false; + bool hover_ = false; + std::string value_ = "MWMWMW"; + + static const std::map& segment_map() { + static const std::map kMap = { + {' ', ""}, + {'\"', "h j"}, + {'\'', "j"}, + {'+', "g1 g2 i l"}, + {'-', "g1 g2"}, + {'/', "j k"}, + {'0', "a1 a2 b c d1 d2 e f"}, + {'1', "b c"}, + {'2', "a1 a2 b d1 d2 e g1 g2"}, + {'3', "a1 a2 b c d1 d2 g1 g2"}, + {'4', "b c f g1 g2"}, + {'5', "a1 a2 c d1 d2 f g1 g2"}, + {'6', "a1 a2 c d1 d2 e f g1 g2"}, + {'7', "a1 a2 b c"}, + {'8', "a1 a2 b c d1 d2 e f g1 g2"}, + {'9', "a1 a2 b c d1 d2 f g1 g2"}, + {'=', "d1 d2 g1 g2"}, + {'A', "a1 a2 b c e f g1 g2"}, + {'B', "a1 a2 b c d1 d2 g1 g2 i l"}, + {'C', "a1 a2 d1 d2 e f"}, + {'D', "a1 a2 b c d1 d2 i l"}, + {'E', "a1 a2 d1 d2 e f g1 g2"}, + {'F', "a1 a2 e f g1 g2"}, + {'G', "a1 a2 c d1 d2 e f g1 g2"}, + {'H', "b c e f g1 g2"}, + {'I', "i l"}, + {'J', "b c d1 d2 e"}, + {'K', "e f g1 j k"}, + {'L', "d1 d2 e f"}, + {'M', "b c e f h i j"}, + {'N', "b c e f h m"}, + {'O', "a1 a2 b c d1 d2 e f"}, + {'P', "a1 a2 b e f g1 g2"}, + {'Q', "a1 a2 b c d1 d2 e f m"}, + {'R', "a1 a2 b e f g1 g2 m"}, + {'S', "a1 a2 c d1 d2 f g1 g2"}, + {'T', "a1 a2 i l"}, + {'U', "b c d1 d2 e"}, + {'V', "c e j k"}, + {'W', "b c e f k l m"}, + {'X', "h j k m"}, + {'Y', "b c f g1 g2 l"}, + {'Z', "a1 a2 d1 d2 j k"}, + {'_', "d1 d2"}, + }; + return kMap; + } + + // Normalise a raw string to the displayable value: uppercase, drop + // characters with no approximation, keep at most kDigits display cells; + // '.' and ':' become a decimal-point dot after the previous cell. + std::string normalize(const std::string& raw) const { + std::string out; + int cells = 0; + for (char rc : raw) { + char c = rc; + if (c >= 'a' && c <= 'z') c = (char)(c - 'a' + 'A'); + if (c == '.' || c == ':') { + if (cells > 0 && (out.empty() || out.back() != '.')) out += '.'; + continue; + } + if (cells >= kDigits) break; + auto it = segment_map().find(c); + if (it == segment_map().end()) continue; + out += c; + ++cells; + } + return out; + } + // Display cells (characters excluding '.' dots). + std::vector cells() const { + std::vector v; + for (char c : value_) if (c != '.') v.push_back(c); + return v; + } + // Decimal-point dot after cell i? + bool dp_after(int i) const { + int cell = -1; + for (char c : value_) { + if (c == '.') { + if (cell == i) return true; + } else { + ++cell; + } + } + return false; + } + void draw_diag(int x1, int y1, int x2, int y2, int t, unsigned long col) { + double dx = (double)(x2 - x1), dy = (double)(y2 - y1); + double len = std::sqrt(dx * dx + dy * dy); + if (len < 1.0) return; + double px = -dy / len * t / 2.0, py = dx / len * t / 2.0; + XPoint pts[4] = { + {(short)std::lround(x1 + px), (short)std::lround(y1 + py)}, + {(short)std::lround(x2 + px), (short)std::lround(y2 + py)}, + {(short)std::lround(x2 - px), (short)std::lround(y2 - py)}, + {(short)std::lround(x1 - px), (short)std::lround(y1 - py)}}; + XSetForeground(display_, gc_, col); + XFillPolygon(display_, window_, gc_, pts, 4, Convex, CoordModeOrigin); + } + void draw_segment(int x, int y, int w, int h, int t, const std::string& seg, + unsigned long lit, unsigned long dim) { + unsigned long col = segment_on(cur_, seg) ? lit : dim; + int midx = x + w / 2, midy = y + h / 2; + int hh = std::max(1, h / 2 - t); + int hw = std::max(1, w / 2 - t); + if (seg == "a") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, std::max(1, w - 2 * t), t); } + else if (seg == "a1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y, hw, t); } + else if (seg == "a2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y, hw, t); } + else if (seg == "b") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, y + t, t, hh); } + else if (seg == "c") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + w - t, midy, t, hh); } + else if (seg == "d") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, std::max(1, w - 2 * t), t); } + else if (seg == "d1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, y + h - t, hw, t); } + else if (seg == "d2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, y + h - t, hw, t); } + else if (seg == "e") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, midy, t, hh); } + else if (seg == "f") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x, y + t, t, hh); } + else if (seg == "g1") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, x + t, midy - t / 2, hw, t); } + else if (seg == "g2") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx, midy - t / 2, hw, t); } + else if (seg == "i") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, y + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "l") { XSetForeground(display_, gc_, col); XFillRectangle(display_, window_, gc_, midx - t / 2, midy + t, t, std::max(1, h / 2 - 2 * t)); } + else if (seg == "h") draw_diag(x + t, y + t, midx, midy - t, t, col); + else if (seg == "j") draw_diag(x + w - t, y + t, midx, midy - t, t, col); + else if (seg == "k") draw_diag(x + t, y + h - t, midx, midy + t, t, col); + else if (seg == "m") draw_diag(x + w - t, y + h - t, midx, midy + t, t, col); + } + void draw_digit(int x, int y, int w, int h, int t, char ch, + unsigned long lit, unsigned long dim) { + cur_ = ch; + for (const std::string& seg : kSegIds) draw_segment(x, y, w, h, t, seg, lit, dim); + } + char cur_ = ' '; + +public: + static constexpr int kDigits = 6; + static constexpr int kSegments = 16; + static const std::vector kSegIds; + std::function on_click; + + InstSeg16Display6(Display* display, int screen, Window window, GC gc, SStyle_Manager* styles, + int x, int y, int width, int height) { + display_ = display; screen_ = screen; window_ = window; gc_ = gc; styles_ = styles; + x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; + name_ = "InstSeg16Display6"; text_ = "InstSeg16Display6"; + } + ~InstSeg16Display6() {} + void set_bounds(int x, int y, int width, int height) { x1_ = x; y1_ = y; x2_ = x + width; y2_ = y + height; } + int width() const { return x2_ - x1_; } + int height() const { return y2_ - y1_; } + bool contains(int x, int y) { return visible_ && x >= x1_ && x <= x2_ && y >= y1_ && y <= y2_; } + void set_visible(bool v) { visible_ = v; } + bool get_visible() { return visible_; } + void set_enabled(bool e) { enabled_ = e; } + bool get_enabled() { return enabled_; } + bool get_focused() { return focused_; } + bool get_pressed() { return pressed_; } + void set_style_name(std::string s) { style_name_ = s; } + void set_text(std::string t) { text_ = t; } + std::string get_text() { return text_; } + SStyle style() { return styles_->resolve(style_name_); } + + void set_value(const std::string& v) { value_ = normalize(v); } + std::string get_value() const { return value_; } + // The string actually shown, padded with spaces to kDigits cells. + std::string shown_text() const { + std::string s = value_; + int n = 0; + for (char c : s) if (c != '.') ++n; + while (n < kDigits) { s += ' '; ++n; } + return s; + } + int cell_count() const { + int n = 0; + for (char c : value_) if (c != '.') ++n; + return n; + } + char char_at(int i) const { + std::vector v = cells(); + if (i < 0 || i >= (int)v.size()) return ' '; + return v[i]; + } + static bool segment_on(char ch, const std::string& seg) { + if (ch >= 'a' && ch <= 'z') ch = (char)(ch - 'a' + 'A'); + auto it = segment_map().find(ch); + if (it == segment_map().end()) return false; + const std::string& s = it->second; + size_t pos = 0; + while (pos < s.size()) { + size_t sp = s.find(' ', pos); + std::string tok = s.substr(pos, sp == std::string::npos ? sp : sp - pos); + if (tok == seg) return true; + if (sp == std::string::npos) break; + pos = sp + 1; + } + return false; + } + static bool renders_clean(char ch) { + return std::string("0123456789ABCDEFGHIJLMOPSTUWX").find(ch) != std::string::npos; + } + static bool renders_approx(char ch) { + return std::string("KNQRVYZ'\":").find(ch) != std::string::npos; + } + static bool renders_blank(char ch) { + return std::string(";,?!@#$%&*()[]{}<>\\|^`~").find(ch) != std::string::npos; + } + static std::string clean_repertoire() { return "0123456789ABCDEFGHIJLMOPSTUWX"; } + static std::string approx_repertoire() { return "KNQRVYZ'\":"; } + static std::string cannot_repertoire() { return ";,?!@#$%&*()[]{}<>\\|^`~"; } + static const char* default_value() { return "MWMWMW"; } + + void draw() { + if (!visible_) return; + SStyle st = style(); + unsigned long bg = styles_->get_color_rgb(12, 12, 14); + unsigned long bezel = styles_->get_color_rgb(58, 58, 62); + unsigned long lit = styles_->get_color_rgb(255, 176, 0); + unsigned long dim = styles_->get_color_rgb(60, 42, 8); + unsigned long label_col = styles_->get_color_rgb(170, 170, 170); + XSetForeground(display_, gc_, bg); + XFillRectangle(display_, window_, gc_, x1_, y1_, width(), height()); + XSetForeground(display_, gc_, bezel); + XDrawRectangle(display_, window_, gc_, x1_, y1_, width() - 1, height() - 1); + XDrawRectangle(display_, window_, gc_, x1_ + 2, y1_ + 2, width() - 5, height() - 5); + XSetForeground(display_, gc_, label_col); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 6, y1_ + 12, text_); + int label_h = 16; + int ax = x1_ + 6, ay = y1_ + label_h + 4, aw = width() - 12, ah = height() - label_h - 10; + if (aw >= 10 && ah >= 10) { + int gap = 4; + bool has_dp = value_.find('.') != std::string::npos; + int dp_w = has_dp ? 8 : 0; + int cell_w = (aw - gap * (kDigits - 1) - dp_w) / kDigits; + int cell_h = ah; + int t = std::max(2, cell_w / 6); + std::vector v = cells(); + int cx = ax; + for (int i = 0; i < kDigits; ++i) { + char ch = (i < (int)v.size()) ? v[i] : ' '; + draw_digit(cx, ay, cell_w, cell_h, t, ch, lit, dim); + cx += cell_w + gap; + if (dp_after(i)) { + XSetForeground(display_, gc_, lit); + XFillRectangle(display_, window_, gc_, cx - gap + 1, ay + cell_h - t - 1, t + 1, t + 1); + cx += dp_w; + } + } + } + if (focused_) { + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_ + 1, y1_ + 1, width() - 3, height() - 3); + } + XFlush(display_); + } + bool on_button_press(int x, int y, unsigned int button) { + (void)button; + if (!contains(x, y) || !enabled_) return false; + focused_ = true; pressed_ = true; + if (on_click) on_click(); + return true; + } + bool on_button_release(int x, int y, unsigned int button) { + (void)x; (void)y; (void)button; + if (!pressed_) return false; + pressed_ = false; + return true; + } + bool on_motion(int x, int y) { + hover_ = contains(x, y); + return hover_; + } + // Up/Down step the last displayed character (digit wraps 9->0, letter + // wraps Z->A); Home restores the default demo string. + bool on_key(KeySym key, const char* str) { + (void)str; + if (!focused_ || !enabled_) return false; + switch (key) { + case XK_Up: case XK_Right: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 1) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 1) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Down: case XK_Left: { + std::vector v = cells(); + if (v.empty()) return false; + char c = v.back(); + if (c >= '0' && c <= '9') c = (char)('0' + (c - '0' + 9) % 10); + else if (c >= 'A' && c <= 'Z') c = (char)('A' + (c - 'A' + 25) % 26); + else return false; + v.back() = c; + std::string s; + for (char ch : v) s += ch; + set_value(s); + return true; + } + case XK_Home: set_value(default_value()); return true; + case XK_Return: case XK_space: + if (on_click) on_click(); + return true; + } + return false; + } +}; + +const std::vector InstSeg16Display6::kSegIds = {"a1", "a2", "b", "c", "d1", "d2", "e", "f", "g1", "g2", "h", "i", "j", "k", "l", "m"}; diff --git a/widgets/components/InstSeg16Display6/core/xframe_core.h b/widgets/components/InstSeg16Display6/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/InstSeg16Display6/core/xframe_core.h @@ -0,0 +1,988 @@ +#pragma once +#ifndef XFRAME_CORE_H +#define XFRAME_CORE_H + +// +// xframe_core.h - shared core for the XFrame widget library. +// +// Everything in here follows the format of the "Writing Your Own +// X-11 Framework Basics" articles (hotconfig.com): +// +// Part 1 - Display / Screen / Window boilerplate, the GC as a +// "pen", the drawing primitives, and the Canvas class. +// Part 2 - widgets are standalone classes that record display_, +// screen_, window_ and gc_ at construction time. +// Part 3 - SStyle_Manager tracks named styles in a vector. +// Part 4 - a polished widget is built from primitives: two fill +// rectangles + four fill arcs make a rounded body, four +// lines + four draw arcs make its outline, and text is +// centred with XTextWidth + font ascent / descent. +// +// Two small completions versus the articles, needed by Part 4's own +// draw code: SStyle gains lineColor_ and text_color_, and the style +// manager gains the delete_style() function Part 3 left as a reader +// challenge, plus bounds-safe getters. +// + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +#include + +//region SStyle + +struct Srgb + +{ + + int r; + + int g; + + int b; + +}; + +struct SStyle + +{ + + unsigned long fillColor_ = 0; + + unsigned long outlineColor_ = 0; + + unsigned long lineColor_ = 0; + + unsigned long text_color_ = 0; + + unsigned long radius_ = 0; + + unsigned long lineWidth_ = 1; + + XFontStruct *font_ = nullptr; + + std::string style_name_; + +}; + +//endregion + +//region SStyle_Manager + +class SStyle_Manager + +{ + +private: + + std::vector styles_; + + Display *display_; + + Window window_; + + int screen_; + + GC gc_; + + int active_style = 0; // just set the default to first passed. + +public: + + SStyle_Manager(Display *display, Window window, int screen, GC gc) + + { + + display_ = display; + + window_ = window; + + screen_ = screen; + + gc_ = gc; + + } + + // NOTE (test agent, Nov 26 2026): do NOT XFreeFont here. Every demo + // main calls XCloseDisplay() before this destructor runs (stack + // unwinding after main returns), so XFreeFont would operate on a + // closed Display and corrupt the heap (SIGSEGV/SIGABRT inside + // XFreeFont on every clean exit). The fonts are process-lifetime + // resources; the X server reclaims them when the client disconnects. + // Use delete_style() to free a single style while the display is + // still open. + ~SStyle_Manager() + + { + + styles_.clear(); + + } + + int add_style(std::string styleName, Srgb fillColor, Srgb outlineColor, int radius, int linewidth, std::string fontName) + + { + + return add_style_ex(styleName, fillColor, outlineColor, outlineColor, Srgb{0, 0, 0}, radius, linewidth, fontName); + + } + + int add_style_ex(std::string styleName, Srgb fillColor, Srgb outlineColor, Srgb lineColor, Srgb textColor, int radius, int linewidth, std::string fontName) + + { + + SStyle nstyle; + + nstyle.style_name_ = std::move(styleName); + + nstyle.fillColor_ = get_color_Srgb(fillColor); + + nstyle.outlineColor_ = get_color_Srgb(outlineColor); + + nstyle.lineColor_ = get_color_Srgb(lineColor); + + nstyle.text_color_ = get_color_Srgb(textColor); + + nstyle.radius_ = radius; + + nstyle.lineWidth_ = linewidth; + + // Define fallback fonts to try if the requested font fails + + const char* fallbackFonts[] = { "fixed", "helvetica" }; + + size_t numFallbacks = sizeof(fallbackFonts) / sizeof(*fallbackFonts); + + nstyle.font_ = nullptr; + + // Attempt to load the primary font (if provided and not empty) + + if (!fontName.empty()) { + + nstyle.font_ = XLoadQueryFont(display_, fontName.c_str()); + + } + + // If the primary failed, iterate through fallback fonts until one succeeds or all are exhausted + + if (!nstyle.font_) { + + for (size_t i = 0; i < numFallbacks && !nstyle.font_; ++i) { + + nstyle.font_ = XLoadQueryFont(display_, fallbackFonts[i]); + + } + + } + + // Final validation: if no font loaded, report which fonts were attempted and exit + + if (!nstyle.font_) + + { + + printf("Failed to load any font (tried: "); + + if (!fontName.empty()) printf("%s", fontName.c_str()); + + for (size_t i = 0; i < numFallbacks; ++i) { + + if (!fontName.empty() || i > 0) printf(", "); + + printf("%s", fallbackFonts[i]); + + } + + printf(")\n"); + + return -1; + + } + + styles_.push_back(nstyle); + + return 0; + + } + + // The delete function Part 3 left as a challenge: remove a style + // by name, freeing its font, and keep active_style in range. + + int delete_style(std::string styleName) + + { + + for (size_t i = 0; i < styles_.size(); ++i) + + { + + if (styles_[i].style_name_ == styleName) + + { + + if (styles_[i].font_) + + { + + XFreeFont(display_, styles_[i].font_); + + } + + styles_.erase(styles_.begin() + static_cast(i)); + + if (active_style >= (int)styles_.size()) + + { + + active_style = styles_.empty() ? 0 : (int)styles_.size() - 1; + + } + + return 0; + + } + + } + + return -1; // Not found + + } + + int style_count() + + { + + return (int)styles_.size(); + + } + + unsigned long get_color_Srgb(Srgb color) + + { + + XColor xcolor; + + xcolor.red = color.r << 8; + + xcolor.green = color.g << 8; + + xcolor.blue = color.b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", color.r, color.g, color.b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + unsigned long get_color_rgb(unsigned char r, unsigned char g, unsigned char b) + + { + + XColor xcolor; + + xcolor.red = r << 8; + + xcolor.green = g << 8; + + xcolor.blue = b << 8; + + if (XAllocColor(display_, DefaultColormap(display_, screen_), &xcolor)) + + { + + return xcolor.pixel; + + } else { + + printf("Failed to allocate color! RGB(%d,%d,%d)\n", r, g, b); + + return BlackPixel(display_, screen_); // Fallback + + } + + } + + int set_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + active_style = static_cast(std::distance(styles_.begin(), it)); + + return active_style; + + } + + return -1; // Not found + + } + + SStyle get_active_style_byName(std::string styleName) + + { + + auto it = std::find_if(styles_.begin(), styles_.end(), + + [&](const SStyle& s) { return s.style_name_ == styleName; }); + + if (it != styles_.end()) + + { + + return *it; + + } + + return get_active_style(); + + } + + SStyle get_active_style() + + { + + if (styles_.empty()) + + { + + return SStyle{}; + + } + + if (active_style < 0 || active_style >= (int)styles_.size()) + + { + + active_style = 0; + + } + + return styles_[active_style]; + + } + + SStyle get_index_style(int index) + + { + + if (index >= 0 && index < (int)styles_.size()) + + { + + return styles_[index]; + + } + + return get_active_style(); + + } + + // Resolve the style a widget should draw with: its own named + // style when set, otherwise the manager's active style. + + SStyle resolve(const std::string& styleName) + + { + + if (!styleName.empty()) + + { + + return get_active_style_byName(styleName); + + } + + return get_active_style(); + + } + +}; + +//endregion + +//region Drawing helpers (Part 4 construction, shared by all widgets) + +namespace xf + +{ + + inline void set_line_width(Display* display, GC gc, int lineWidth) + + { + + unsigned long valuemask = GCLineWidth; + + XGCValues gc_values; + + gc_values.line_width = lineWidth; + + XChangeGC(display, gc, valuemask, &gc_values); + + } + + // The Part 4 rounded body: Rectangle A + Rectangle B + 4 fill arcs. + + inline void fill_rounded_rect(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + int w = x2 - x1; + + int h = y2 - y1; + + if (r <= 0 || w <= 2 * r || h <= 2 * r) + + { + + XFillRectangle(display, window, gc, x1, y1, w, h); + + return; + + } + + XSetForeground(display, gc, style.fillColor_); + + //Rectangle A + + XFillRectangle(display, window, gc, x1 + r, y1, w - 2 * r, h); + + //Rectangle B + + XFillRectangle(display, window, gc, x1, y1 + r, w, h - 2 * r); + + //region Arc C Top Left + + XFillArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XFillArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XFillArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XFillArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // The Part 4 outline: 4 line bars + 4 draw arcs, in lineColor_. + + inline void draw_rounded_outline(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + int r = (int)style.radius_; + + XSetForeground(display, gc, style.lineColor_); + + set_line_width(display, gc, (int)style.lineWidth_); + + if (r <= 0) + + { + + XDrawRectangle(display, window, gc, x1, y1, x2 - x1, y2 - y1); + + return; + + } + + // 4 Line Bars + + XDrawLine(display, window, gc, x1 + r, y1, x2 - r, y1); + + XDrawLine(display, window, gc, x2, y1 + r, x2, y2 - r); + + XDrawLine(display, window, gc, x1, y1 + r, x1, y2 - r); + + XDrawLine(display, window, gc, x1 + r, y2, x2 - r, y2); + + // 4 Arcs + + XDrawArc(display, window, gc, x1, y1, 2 * r, 2 * r, 90 * 64, 90 * 64); + + //region Arc D Top Right + + XDrawArc(display, window, gc, x2 - 2 * r, y1, 2 * r, 2 * r, 0, 90 * 64); + + //region Arc E Bottom Right + + XDrawArc(display, window, gc, x2 - 2 * r, y2 - 2 * r, 2 * r, 2 * r, 270 * 64, 90 * 64); + + //region Arc F Bottom Left + + XDrawArc(display, window, gc, x1, y2 - 2 * r, 2 * r, 2 * r, 180 * 64, 90 * 64); + + //endregion + + } + + // Convenience: body + outline in one call, the polished look. + + inline void draw_polished(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2) + + { + + fill_rounded_rect(display, window, gc, style, x1, y1, x2, y2); + + draw_rounded_outline(display, window, gc, style, x1, y1, x2, y2); + + } + + inline int text_width(const SStyle& style, const std::string& text) + + { + + if (!style.font_) + + { + + return (int)text.size() * 8; + + } + + return XTextWidth(style.font_, text.c_str(), (int)text.length()); + + } + + // Part 4 centred text: XTextWidth + ascent / descent. + + inline void draw_text_centered(Display* display, Window window, GC gc, const SStyle& style, int x1, int y1, int x2, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int tw = XTextWidth(style.font_, text.c_str(), (int)text.length()); + + int text_x = x1 + ((x2 - x1) - tw) / 2; + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, text_x, text_y, text.c_str(), (int)text.length()); + + } + + // Left-aligned text, vertically centred in the given band. + + inline void draw_text_left(Display* display, Window window, GC gc, const SStyle& style, int x, int y1, int y2, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + int text_y = y1 + ((y2 - y1) + style.font_->ascent - style.font_->descent) / 2; + + XDrawString(display, window, gc, x, text_y, text.c_str(), (int)text.length()); + + } + + // Baseline text at an explicit position (labels, grid cells...). + + inline void draw_text_at(Display* display, Window window, GC gc, const SStyle& style, int x, int baseline_y, const std::string& text) + + { + + if (!style.font_ || text.empty()) + + { + + return; + + } + + XSetFont(display, gc, style.font_->fid); + + XSetForeground(display, gc, style.text_color_); + + XDrawString(display, window, gc, x, baseline_y, text.c_str(), (int)text.length()); + + } + + inline void draw_checkmark(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + set_line_width(display, gc, 2); + + int s = size / 2; + + XDrawLine(display, window, gc, cx - s, cy, cx - s / 3, cy + s); + + XDrawLine(display, window, gc, cx - s / 3, cy + s, cx + s, cy - s); + + set_line_width(display, gc, 1); + + } + + inline void draw_triangle_down(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy + i, cx + (size - i), cy + i); + + } + + } + + inline void draw_triangle_up(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx - (size - i), cy - i, cx + (size - i), cy - i); + + } + + } + + inline void draw_triangle_right(Display* display, Window window, GC gc, unsigned long color, int cx, int cy, int size) + + { + + XSetForeground(display, gc, color); + + for (int i = 0; i < size; ++i) + + { + + XDrawLine(display, window, gc, cx + i, cy - (size - i), cx + i, cy + (size - i)); + + } + + } + +} + +//endregion + +//region Region Canvas (from Part 1) + +class Canvas + +{ + +private: + + Display* display = nullptr; + + Window window = 0; + + GC gc = nullptr; + + XImage* image = nullptr; + + int width = 0; + + int height = 0; + + std::vector pixels; + +public: + + Canvas(Display* display, Window window, GC graphicsContext, int width, int height) : display(display), window(window), gc(graphicsContext) + + { + + resize(width, height); + + } + + ~Canvas() { destroyImage(); } + + void resize(int newWidth, int newHeight) + + { + + width = std::max(1, newWidth); + + height = std::max(1, newHeight); + + pixels.resize(static_cast(width) * height); + + clear(0x202020); + + destroyImage(); + + Visual* visual = DefaultVisual(display, DefaultScreen(display)); + + int depth = DefaultDepth(display, DefaultScreen(display)); + + image = XCreateImage(display, visual, depth, ZPixmap, 0, nullptr, width, height, 32, 0); + + if (!image) + + { + + std::exit(1); + + } + + image->data = static_cast(std::malloc(image->bytes_per_line * height)); + + if (!image->data) + + { + + std::exit(1); + + } + + } + + int getWidth() const + + { + + return width; + + } + + int getHeight() const + + { + + return height; + + } + + // Direct access to the raw framebuffer. + + uint32_t* data() + + { + + return pixels.data(); + + } + + const uint32_t* data() const + + { + + return pixels.data(); + + } + + void clear(uint32_t rgb) + + { + + std::fill(pixels.begin(), pixels.end(), rgb); + + } + + void setPixel(int x, int y, uint32_t rgb) + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return; + + } + + pixels[static_cast(y) * width + x] = rgb; + + } + + uint32_t getPixel(int x, int y) const + + { + + if (x < 0 || x >= width || y < 0 || y >= height) + + { + + return 0; + + } + + return pixels[static_cast(y) * width + x]; + + } + + void fillRect(int x, int y, int w, int h, uint32_t rgb) + + { + + int x0 = std::max(0, x); + + int y0 = std::max(0, y); + + int x1 = std::min(width, x + w); + + int y1 = std::min(height, y + h); + + for (int py = y0; py < y1; ++py) + + { + + for (int px = x0; px < x1; ++px) + + { + + setPixel(px, py, rgb); + + } + + } + + } + + void drawGradient() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint8_t red = static_cast(255.0 * x / std::max(1, width - 1)); + + uint8_t green = static_cast(255.0 * y / std::max(1, height - 1)); + + uint8_t blue = 100; + + uint32_t color = (static_cast(red) << 16) | (static_cast(green) << 8) | blue; + + setPixel(x, y, color); + + } + + } + + } + + void present() + + { + + for (int y = 0; y < height; ++y) + + { + + for (int x = 0; x < width; ++x) + + { + + uint32_t rgb = getPixel(x, y); + + unsigned long x11Pixel = ((rgb >> 16) & 0xff) << 16 | ((rgb >> 8) & 0xff) << 8 | (rgb & 0xff); + + XPutPixel(image, x, y, x11Pixel); + + } + + } + + XPutImage(display, window, gc, image, 0, 0, 0, 0, width, height); + + XFlush(display); + + } + +private: + + void destroyImage() + + { + + if (image) + + { + + XDestroyImage(image); + + image = nullptr; + + } + + } + +}; + +//endregion +#endif // XFRAME_CORE_H diff --git a/widgets/components/InstSeg16Display6/main_InstSeg16Display6.cpp b/widgets/components/InstSeg16Display6/main_InstSeg16Display6.cpp new file mode 100644 index 0000000..4f4c16e --- /dev/null +++ b/widgets/components/InstSeg16Display6/main_InstSeg16Display6.cpp @@ -0,0 +1,54 @@ +#include "InstSeg16Display6.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + XID Xid = RootWindow(display, screen); + Window window = XCreateSimpleWindow(display, Xid, 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "InstSeg16Display6 - XFrame demo"); + XSelectInput(display, window, ExposureMask | KeyPressMask | StructureNotifyMask | ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = XInternAtom(display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(display, window, &deleteWindowMessage, 1); + XMapWindow(display, window); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.add_style_ex("dark", Srgb{45, 45, 48}, Srgb{20, 20, 22}, Srgb{200, 200, 200}, Srgb{240, 240, 240}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + InstSeg16Display6 widget(display, screen, window, gc, &styles, 20, 20, 340, 110); + widget.set_value("MWMWMW"); + widget.draw(); + bool running = true; + while (running) + { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) + { + case Expose: handled = true; break; + case ButtonPress: handled = widget.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case ButtonRelease: handled = widget.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); break; + case MotionNotify: handled = widget.on_motion(event.xmotion.x, event.xmotion.y); break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int n = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[n] = 0; + handled = widget.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + } + if (handled) { XClearWindow(display, window); widget.draw(); XFlush(display); } + } + XCloseDisplay(display); + return 0; +} diff --git a/widgets/icons/InstSeg14Display1.ico b/widgets/icons/InstSeg14Display1.ico new file mode 100644 index 0000000000000000000000000000000000000000..8444426e5964bdb865bd88c2ef56ad63c39a9c5e GIT binary patch literal 862 zcmcJOK?=e^5Cl7T4HAL`PvX&cc=8!O(MR~NwY0Gr5JPgvWOma%TRRC$B6VEDAmXUo zPMS~`#=CT8bksk=+H>#Wg48yS)A~4!%6Ll`Muq+{)`p{p1*z<8=k?aL?Lv3&g)mt7`u2#YJPLtD^LiF521r?TOyE_E z;eP<9Q!(eEeB1{TpNiZ1yK{CYP3&E`i^ZJBx62*DQZg398Kyfet${pc@V2A(%!+#nBInsfMkPwjw zVm6VAfy&_Od7Kj9x^S`K>KQit2dV**KoKAV&W4C1YloOms(OgAL)SfUmlI@=o)+Y2 MoIL--@&PUy0JVk}xc~qF literal 0 HcmV?d00001 diff --git a/widgets/icons/InstSeg14Display4.ico b/widgets/icons/InstSeg14Display4.ico new file mode 100644 index 0000000000000000000000000000000000000000..a08fa367da07d41a8c8474e0898293fda245b512 GIT binary patch literal 862 zcmZQzU<5(|0R|wDVDMmOU=RbcG=LZ+qyWT>Kyfet${pc@V2A(%!+#nBInsfMkPwjw zVm6VAfy&_Od7Kg;y6`aI>Vaw?%J48Cra{bS*zg~s9uEUqJ&+AikDmdQCC_|3&W1}- X;vR@zVn~SlNg`>SJpaS;0WKN; literal 0 HcmV?d00001 diff --git a/widgets/icons/InstSeg14Display5.ico b/widgets/icons/InstSeg14Display5.ico new file mode 100644 index 0000000000000000000000000000000000000000..e3c3f5058af90cfba1fd337ae3f296306145abaf GIT binary patch literal 862 zcmZQzU<5(|0R|wDVDMmOU=RbcG=LZ+qyWT>Kyfet${pc@V2A(%!+#nBInsfMkPwjw zVm6VAfyyB2d7KjPAY{{k>hY+ANTI2RXaNcWWwDZ2)iZ4P4^$5!(QL%39;?X^8`0FG fnTE+lQ%}&#nCg*5@UtP|PZCMvc literal 0 HcmV?d00001 diff --git a/widgets/icons/InstSeg14Display6.ico b/widgets/icons/InstSeg14Display6.ico new file mode 100644 index 0000000000000000000000000000000000000000..2bd6d9206bf4c62d8d345883ba5a126c777d7eac GIT binary patch literal 862 zcmZQzU<5(|0R|wDVDMmOU=RbcG=LZ+qyWT>Kyfet${pc@V2A(%!+#nBInsfMkPwjw zVm6VAfyyB2d7KgmB8Ztl^>CF88~(%Dm<+gjh!!9hs0I&-rXFHArWJ5;H1&8)hS&>N j4|gi2;czLq7Ba#Is0CsdF(kx%l1LgS&;PJ|fQtqID!&@Z literal 0 HcmV?d00001 diff --git a/widgets/icons/InstSeg16Display1.ico b/widgets/icons/InstSeg16Display1.ico new file mode 100644 index 0000000000000000000000000000000000000000..ad209eef698179a8a37feb67328e1f62aa19f163 GIT binary patch literal 862 zcmcJOK@NgI3`IY2OU%TDabb*0&*92ra6}K`y@sbh{!An)EGW~`-@Yjm0#e6Sim-!j z8);8=!Jnlw-cf%Uy~oz>f>c+w({elR%FN~2Ghwjs{dM@gJkz}H)o>n!Y;z<`<~v7b zm-$FqEg#arGy-_#JeCacoJ1#dorFiGm2Nwv<*854@KN#Jyid!&(fp#g^5*?C=jCL9aKDnC-MmX6$VzUA`p_VILCJOHfzU4PMTP)3ES(s zl6Igo@uE(|1phY99vg=VsV{8D`F7a0qPurdj4b-~Kyfet${pc@V2A(%!+#nBInsfQkN}Yg zVm6VAfy&_Od7Kj9x^S`K>KQit2dV**KoKAbK@c`v9AX;8d{Wf|^&-0gViCkZWO1Mf p+?^dyw6L%!a!M;#6Wth?>;76Y{NiZO+vN0RM9}->WX%%cks?GBxwFe$=X)iTQM-Ve)L`F;SZG=^Xr+guVhr tlz&PHEniw3YeZ=WKYnZ@p&#B|FLFuKyfet${pc@V2A(%!+#nBInsfQkN}Yg zVm6VAfyyB2d7KjPAY{{k>LDr_Hv9)7Og2yiO+7>lP!OmdNJ11Kv$3iNDubJk#>P~S pY#JsTO+8Qn++<8PL_1sy8Q}xe0@qHE0WqH>lE%sNKP(^Mq5-4xBP{>` literal 0 HcmV?d00001 diff --git a/widgets/icons/InstSeg16Display6.ico b/widgets/icons/InstSeg16Display6.ico new file mode 100644 index 0000000000000000000000000000000000000000..4bc6a005e4b1a397f4f9ef9c19c11e26f8d9715d GIT binary patch literal 862 zcmcJOK@LDL5JkV(iZm8tA!6wqR*vC_4&h$)`7seuN@C2^H+}P)2tdNiIWQ^=DNs^% zthLp$685*?-kht{0Q}F*C!U!3 lU+N=&@2nGzCv46kZ6hDv4@Y!X%qss^>(8I3-~WTqeE}IvEO7t; literal 0 HcmV?d00001 diff --git a/widgets/tests/test_inst_group_g.cpp b/widgets/tests/test_inst_group_g.cpp new file mode 100644 index 0000000..59d927a --- /dev/null +++ b/widgets/tests/test_inst_group_g.cpp @@ -0,0 +1,259 @@ +// Headless logic + pixel + repertoire checks for Instrumentation Group G. +// Builds with -Wall -Wextra, runs under Xvfb. Attribution: XFrame. +#include "InstSeg14Display1/InstSeg14Display1.h" +#include "InstSeg14Display2/InstSeg14Display2.h" +#include "InstSeg14Display3/InstSeg14Display3.h" +#include "InstSeg14Display4/InstSeg14Display4.h" +#include "InstSeg14Display5/InstSeg14Display5.h" +#include "InstSeg14Display6/InstSeg14Display6.h" +#include "InstSeg16Display1/InstSeg16Display1.h" +#include "InstSeg16Display2/InstSeg16Display2.h" +#include "InstSeg16Display3/InstSeg16Display3.h" +#include "InstSeg16Display4/InstSeg16Display4.h" +#include "InstSeg16Display5/InstSeg16Display5.h" +#include "InstSeg16Display6/InstSeg16Display6.h" +#include +#include +#include +#include +#include + +static Display* g_d = nullptr; +static Window g_w = 0; +static int g_fail = 0; + +static void check(bool ok, const char* what) { + std::printf(" %s %s\n", ok ? "PASS" : "FAIL", what); + if (!ok) ++g_fail; +} + +static int bright_amber(XImage* im) { + int n = 0; + for (int y = 0; y < im->height; ++y) + for (int x = 0; x < im->width; ++x) { + unsigned long p = XGetPixel(im, x, y); + int r = (p >> 16) & 0xff, g = (p >> 8) & 0xff, b = p & 0xff; + if (r > 200 && g > 120 && g < 220 && b < 80) ++n; + } + return n; +} + +static int img_diff(XImage* a, XImage* b) { + int n = 0; + int w = a->width < b->width ? a->width : b->width; + int h = a->height < b->height ? a->height : b->height; + for (int y = 0; y < h; ++y) + for (int x = 0; x < w; ++x) { + unsigned long pa = XGetPixel(a, x, y), pb = XGetPixel(b, x, y); + int dr = abs((int)((pa >> 16) & 0xff) - (int)((pb >> 16) & 0xff)); + int dg = abs((int)((pa >> 8) & 0xff) - (int)((pb >> 8) & 0xff)); + int db = abs((int)(pa & 0xff) - (int)(pb & 0xff)); + if (dr > 30 || dg > 30 || db > 30) ++n; + } + return n; +} + +static XImage* snap() { + XSync(g_d, False); + return XGetImage(g_d, g_w, 0, 0, 900, 700, AllPlanes, ZPixmap); +} + +template +static void check_seg(const char* name, W& w, int n, int seg, const char* demo) { + std::printf("[%s]\n", name); + check(W::kDigits == n, "digit count matches"); + check(W::kSegments == seg, "segment count matches"); + check(std::string(W::default_value()) == demo, "default demo string"); + w.set_value(demo); + check(w.get_value() == demo, "demo value round-trips"); + w.set_value("ABCDEFGH"); + check(w.cell_count() == n, "long value truncates to N cells"); + w.set_value("hello"); + std::string got = w.get_value(); + check((int)got.size() == (n < 5 ? n : 5) && got == std::string("HELLO").substr(0, n < 5 ? n : 5), + "lowercase shown as uppercase"); + w.set_value("???"); + check(w.cell_count() == 0, "unshowable characters dropped"); + w.set_value(""); + check(w.cell_count() == 0, "empty value is empty"); + if (n >= 3) { + w.set_value("42.5"); + check(w.cell_count() == 3 && w.char_at(1) == '2', "decimal point does not use a cell"); + } + const char* top = (seg == 14) ? "a" : "a1"; + check(W::segment_on('8', top) && W::segment_on('8', "b") && W::segment_on('8', "g1"), + "digit 8 lights top/right/middle segments"); + check(W::segment_on('1', "b") && W::segment_on('1', "c") && !W::segment_on('1', top), + "digit 1 lights only b,c"); + check(W::segment_on('A', "a1") == (seg == 16), "16-seg splits the top bar, 14-seg does not"); + check(W::segment_on('M', "i") == (seg == 16), "16-seg M has a centre stem, 14-seg does not"); + // Pixel checks: all-8s lights amber, blank is dark, renders differ. + XClearWindow(g_d, g_w); + std::string eights(n, '8'); + w.set_value(eights); + w.draw(); + XImage* im1 = snap(); + int amb1 = bright_amber(im1); + XClearWindow(g_d, g_w); + w.set_value(std::string(n, ' ')); + w.draw(); + XImage* im0 = snap(); + int amb0 = bright_amber(im0); + int d = img_diff(im0, im1); + std::printf(" amber8=%d amberBlank=%d diff=%d\n", amb1, amb0, d); + check(amb1 > 50, "all-8s renders lit amber"); + check(amb0 == 0, "blank renders no lit amber"); + check(d > 100, "screenshot differs between 8s and blank"); + XDestroyImage(im0); + XDestroyImage(im1); + // Click focuses, Up steps the last character, Home restores the demo. + bool clicked = false; + w.on_click = [&clicked]() { clicked = true; }; + w.set_value(demo); + int cx = 20 + w.width() / 2, cy = 20 + w.height() / 2; + check(w.on_button_press(cx, cy, 1) && clicked && w.get_focused(), "click focuses + fires on_click"); + std::string before = w.get_value(); + check(w.on_key(XK_Up, "") && w.get_value() != before, "Up key steps the last character"); + check(w.on_key(XK_Home, "") && w.get_value() == demo, "Home restores the demo string"); + check(w.on_button_release(cx, cy, 1), "button release handled"); + XClearWindow(g_d, g_w); +} + +template +static void check_repertoire(const char* name, W& w) { + std::printf("[repertoire %s]\n", name); + std::string clean = W::clean_repertoire(); + std::string approx = W::approx_repertoire(); + std::string cannot = W::cannot_repertoire(); + std::vector imgs; + std::vector amber; + for (char c : clean) { + XClearWindow(g_d, g_w); + w.set_value(std::string(1, c)); + w.draw(); + XImage* im = snap(); + int a = bright_amber(im); + std::printf(" clean '%c' amber=%d\n", c, a); + check(a > 20, "clean character renders lit segments"); + imgs.push_back(im); + amber.push_back(a); + } + // Clean characters render distinctly, except the documented look-alikes. + for (size_t i = 0; i < clean.size(); ++i) { + for (size_t j = i + 1; j < clean.size(); ++j) { + char a = clean[i], b = clean[j]; + if ((a == '0' && b == 'O') || (a == '5' && b == 'S') || (a == '6' && b == 'G') || (a == 'J' && b == 'U')) continue; + int d = img_diff(imgs[i], imgs[j]); + if (d <= 50) { + std::printf(" FAIL clean pair '%c'/'%c' diff=%d\n", a, b, d); + ++g_fail; + } + } + } + std::printf(" clean pairwise distinctness checked (%d chars)\n", (int)clean.size()); + for (XImage* im : imgs) XDestroyImage(im); + for (char c : approx) { + XClearWindow(g_d, g_w); + // ':' has no cell of its own; probe it as a dot after '1'. + w.set_value(c == ':' ? std::string("1:") : std::string(1, c)); + w.draw(); + XImage* im = snap(); + int a = bright_amber(im); + std::printf(" approx '%c' amber=%d\n", c, a); + check(a > 5, "approximate character renders something"); + XDestroyImage(im); + } + for (char c : cannot) { + XClearWindow(g_d, g_w); + w.set_value(std::string(1, c)); + w.draw(); + XImage* im = snap(); + int a = bright_amber(im); + check(a == 0, "unshowable character renders blank"); + XDestroyImage(im); + } + // Backslash (char 92) is also unshowable. + XClearWindow(g_d, g_w); + w.set_value(std::string(1, (char)92)); + w.draw(); + XImage* imb = snap(); + check(bright_amber(imb) == 0, "backslash renders blank"); + XDestroyImage(imb); + XClearWindow(g_d, g_w); +} + +int main() { + Display* display = XOpenDisplay(nullptr); + if (!display) { std::printf("FAIL no display\n"); return 1; } + g_d = display; + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), + 0, 0, 900, 700, 1, BlackPixel(display, screen), + WhitePixel(display, screen)); + g_w = window; + XMapWindow(display, window); + XSync(display, False); + GC gc = DefaultGC(display, screen); + SStyle_Manager styles(display, window, screen, gc); + styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*"); + styles.set_active_style_byName("default"); + + InstSeg14Display1 w_InstSeg14Display1(display, screen, window, gc, &styles, 20, 20, 90, 110); + check_seg("InstSeg14Display1", w_InstSeg14Display1, 1, 14, "A"); + InstSeg14Display2 w_InstSeg14Display2(display, screen, window, gc, &styles, 20, 20, 140, 110); + check_seg("InstSeg14Display2", w_InstSeg14Display2, 2, 14, "42"); + InstSeg14Display3 w_InstSeg14Display3(display, screen, window, gc, &styles, 20, 20, 190, 110); + check_seg("InstSeg14Display3", w_InstSeg14Display3, 3, 14, "ABC"); + InstSeg14Display4 w_InstSeg14Display4(display, screen, window, gc, &styles, 20, 20, 240, 110); + check_seg("InstSeg14Display4", w_InstSeg14Display4, 4, 14, "HELL"); + InstSeg14Display5 w_InstSeg14Display5(display, screen, window, gc, &styles, 20, 20, 290, 110); + check_seg("InstSeg14Display5", w_InstSeg14Display5, 5, 14, "HELLO"); + InstSeg14Display6 w_InstSeg14Display6(display, screen, window, gc, &styles, 20, 20, 340, 110); + check_seg("InstSeg14Display6", w_InstSeg14Display6, 6, 14, "ABC123"); + InstSeg16Display1 w_InstSeg16Display1(display, screen, window, gc, &styles, 20, 20, 90, 110); + check_seg("InstSeg16Display1", w_InstSeg16Display1, 1, 16, "M"); + InstSeg16Display2 w_InstSeg16Display2(display, screen, window, gc, &styles, 20, 20, 140, 110); + check_seg("InstSeg16Display2", w_InstSeg16Display2, 2, 16, "MW"); + InstSeg16Display3 w_InstSeg16Display3(display, screen, window, gc, &styles, 20, 20, 190, 110); + check_seg("InstSeg16Display3", w_InstSeg16Display3, 3, 16, "MWM"); + InstSeg16Display4 w_InstSeg16Display4(display, screen, window, gc, &styles, 20, 20, 240, 110); + check_seg("InstSeg16Display4", w_InstSeg16Display4, 4, 16, "MWMW"); + InstSeg16Display5 w_InstSeg16Display5(display, screen, window, gc, &styles, 20, 20, 290, 110); + check_seg("InstSeg16Display5", w_InstSeg16Display5, 5, 16, "MWMWM"); + InstSeg16Display6 w_InstSeg16Display6(display, screen, window, gc, &styles, 20, 20, 340, 110); + check_seg("InstSeg16Display6", w_InstSeg16Display6, 6, 16, "MWMWMW"); + InstSeg14Display1 r14(display, screen, window, gc, &styles, 20, 20, 90, 110); + check_repertoire("InstSeg14Display1", r14); + InstSeg16Display1 r16(display, screen, window, gc, &styles, 20, 20, 90, 110); + check_repertoire("InstSeg16Display1", r16); + + // 16-segment M/W render differently (better) than 14-segment M/W. + { + InstSeg14Display1 s14(display, screen, window, gc, &styles, 20, 20, 90, 110); + InstSeg16Display1 s16(display, screen, window, gc, &styles, 20, 20, 90, 110); + XClearWindow(g_d, g_w); + s14.set_value("M"); s14.draw(); + XImage* a = snap(); + XClearWindow(g_d, g_w); + s16.set_value("M"); s16.draw(); + XImage* b = snap(); + int dm = img_diff(a, b); + std::printf(" M 14-vs-16 diff=%d\n", dm); + check(dm > 50, "16-seg M differs from 14-seg M"); + XDestroyImage(a); XDestroyImage(b); + XClearWindow(g_d, g_w); + s14.set_value("W"); s14.draw(); + a = snap(); + XClearWindow(g_d, g_w); + s16.set_value("W"); s16.draw(); + b = snap(); + int dw = img_diff(a, b); + std::printf(" W 14-vs-16 diff=%d\n", dw); + check(dw > 50, "16-seg W differs from 14-seg W"); + XDestroyImage(a); XDestroyImage(b); + } + + XCloseDisplay(display); + std::printf(g_fail == 0 ? "ALL PASS\n" : "FAILURES: %d\n", g_fail); + return g_fail == 0 ? 0 : 1; +} diff --git a/widgets/tests/test_inst_group_g.py b/widgets/tests/test_inst_group_g.py new file mode 100644 index 0000000..25daa5d --- /dev/null +++ b/widgets/tests/test_inst_group_g.py @@ -0,0 +1,188 @@ +#!/usr/bin/env python3 +"""Instrumentation Group G driver: builds the 12 segment displays, runs the +headless harness (logic + pixel + repertoire checks), runs each demo under +Xvfb :148 (draw / click / key / clean exit), and verifies every code example +in docs/instrumentation-segments.md compiles. Re-derives every count from +fresh artifacts each round; exits non-zero on any failure. +Attribution: XFrame.""" +import os, re, subprocess, sys, time +from PIL import Image + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +COMP = os.path.join(ROOT, "components") +BUILD = os.path.join(ROOT, "build", "components") +TMP = "/tmp/inst-group-g" +ENV = dict(os.environ, DISPLAY=":148") +WIDGETS = ["InstSeg14Display1", "InstSeg14Display2", "InstSeg14Display3", "InstSeg14Display4", "InstSeg14Display5", "InstSeg14Display6", "InstSeg16Display1", "InstSeg16Display2", "InstSeg16Display3", "InstSeg16Display4", "InstSeg16Display5", "InstSeg16Display6"] +os.makedirs(TMP, exist_ok=True) +failures = [] +rows = [] + +def run(*a, timeout=30, **k): + return subprocess.run(*a, capture_output=True, text=True, timeout=timeout, env=ENV, **k) + +def nonbg(path): + im = Image.open(path).convert("L") + h = im.histogram() + modal = max(range(256), key=lambda v: h[v]) + return sum(c for v, c in enumerate(h) if abs(v - modal) > 10) + +# --- harness: compile + run --- +hsrc = os.path.join(ROOT, "tests", "test_inst_group_g.cpp") +hbin = os.path.join(TMP, "test_inst_group_g") +r = subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-I", COMP, hsrc, + "-o", hbin, "-lX11"], capture_output=True, text=True, timeout=120) +if r.returncode != 0 or "warning:" in r.stderr: + failures.append(f"harness compile failed/warnings: {r.stderr[:600]}") + print("HARNESS COMPILE FAILED") + print(r.stderr[:2000]) +else: + print("harness compiled, 0 warnings") + +xvfb = None +if not os.path.exists("/tmp/.X148-lock"): + xvfb = subprocess.Popen(["Xvfb", ":148", "-screen", "0", "1024x768x24"]) + time.sleep(1.5) + +harness_out = "" +try: + if os.path.exists(hbin): + r = run([hbin], timeout=120) + harness_out = r.stdout + r.stderr + print(harness_out) + if r.returncode != 0 or "ALL PASS" not in harness_out: + failures.append("harness checks failed") + + sd = "/tmp/send_delete" + if not os.path.exists(sd): + subprocess.run(["cc", os.path.join(ROOT, "test-driver", "send_delete.c"), + "-lX11", "-o", sd], capture_output=True, timeout=60) + + for name in WIDGETS: + row = {"name": name, "build": "FAIL", "draw": "FAIL", "click": "FAIL", + "key": "FAIL", "exit": "FAIL"} + bdir = os.path.join(BUILD, name) + r = subprocess.run(["cmake", "-S", os.path.join(COMP, name), "-B", bdir, + "-DCMAKE_CXX_FLAGS=-Wall -Wextra"], + capture_output=True, text=True, timeout=120) + out = r.stdout + r.stderr + r2 = subprocess.run(["cmake", "--build", bdir], capture_output=True, + text=True, timeout=180) if r.returncode == 0 else None + out2 = (r2.stdout + r2.stderr) if r2 else "" + binp = os.path.join(bdir, name) + if r.returncode != 0 or (r2 and r2.returncode != 0): + failures.append(f"{name}: build failed: {(out + out2)[-400:]}") + rows.append(row) + continue + if "warning:" in out2: + failures.append(f"{name}: warnings in build") + if not (os.path.exists(binp) and os.access(binp, os.X_OK)): + failures.append(f"{name}: binary missing") + rows.append(row) + continue + row["build"] = "PASS" + logf = open(os.path.join(TMP, name + ".stderr"), "wb") + p = subprocess.Popen([binp], env=ENV, stdout=subprocess.DEVNULL, stderr=logf) + wid = None + try: + for _ in range(50): + if p.poll() is not None: + break + rr = run(["xdotool", "search", "--name", f"{name} - XFrame demo"], timeout=10) + if rr.stdout.strip(): + wid = rr.stdout.strip().split()[0] + break + time.sleep(0.2) + if wid is None: + failures.append(f"{name}: window not found") + rows.append(row) + continue + time.sleep(0.5) + shot = os.path.join(TMP, name + ".png") + if run(["import", "-window", str(wid), shot], timeout=15).returncode == 0 \ + and os.path.exists(shot) and nonbg(shot) > 200: + row["draw"] = "PASS" + else: + failures.append(f"{name}: blank draw screenshot") + run(["xdotool", "mousemove", "--window", str(wid), "60", "60", + "click", "--window", str(wid), "1"], timeout=10) + time.sleep(0.3) + if p.poll() is None: + row["click"] = "PASS" + else: + failures.append(f"{name}: died on click") + run(["xdotool", "key", "--window", str(wid), "Up"], timeout=10) + time.sleep(0.3) + if p.poll() is None: + row["key"] = "PASS" + else: + failures.append(f"{name}: died on key") + run([sd, str(wid)], timeout=10) + try: + rc = p.wait(timeout=10) + if rc == 0: + row["exit"] = "PASS" + else: + failures.append(f"{name}: exit rc={rc}") + except subprocess.TimeoutExpired: + failures.append(f"{name}: no clean exit") + p.kill() + finally: + if p.poll() is None: + p.kill() + logf.close() + rows.append(row) + + # --- doc examples: extract first cpp block after each ## heading, wrap, compile --- + doc = open(os.path.join(os.path.dirname(ROOT), "docs", "instrumentation-segments.md")).read() + heads = list(re.finditer(r"^## (\w+)\n", doc, re.M)) + ex_ok = 0 + for m in heads: + nm = m.group(1) + seg = doc[m.end():] + bm = re.search(r"```cpp\n(.*?)```", seg, re.S) + if not bm: + failures.append(f"doc: no cpp example for {nm}") + continue + snippet = bm.group(1) + prog = ('#include "%s/%s.h"\n' % (nm, nm) + + "int main() {\n" + " Display* display = XOpenDisplay(nullptr);\n" + " if (!display) return 1;\n" + " int screen = DefaultScreen(display);\n" + " Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 0, 0, 800, 600, 1, 0, 0);\n" + " GC gc = DefaultGC(display, screen);\n" + " SStyle_Manager styles(display, window, screen, gc);\n" + ' styles.add_style_ex("default", Srgb{225, 225, 225}, Srgb{120, 120, 120}, Srgb{60, 60, 60}, Srgb{20, 20, 20}, 6, 1, "-misc-fixed-medium-r-normal--13-*");\n' + ' styles.set_active_style_byName("default");\n' + + snippet + + " XCloseDisplay(display);\n return 0;\n}\n") + src = os.path.join(TMP, "ex_" + nm + ".cpp") + open(src, "w").write(prog) + r = subprocess.run(["g++", "-std=c++17", "-Wall", "-Wextra", "-I", COMP, src, + "-o", os.path.join(TMP, "ex_" + nm), "-lX11"], + capture_output=True, text=True, timeout=60) + if r.returncode == 0 and "warning:" not in r.stderr: + ex_ok += 1 + else: + failures.append(f"doc example {nm} failed to compile: {r.stderr[:400]}") + print(f"doc examples compiled: {ex_ok}/{len(heads)}") + if ex_ok != len(heads): + failures.append("doc examples incomplete") +finally: + if xvfb is not None: + xvfb.terminate() + +print("\n%-22s %-6s %-6s %-6s %-6s %-6s" % ("widget", "build", "draw", "click", "key", "exit")) +for row in rows: + print("%-22s %-6s %-6s %-6s %-6s %-6s" % (row["name"], row["build"], row["draw"], + row["click"], row["key"], row["exit"])) +npass = sum(1 for row in rows if all(v == "PASS" for k, v in row.items() if k != "name")) +print(f"\nwidgets fully PASS: {npass}/{len(WIDGETS)}") +print("harness: " + ("ALL PASS" if "ALL PASS" in harness_out else "FAILED")) +if failures: + print("FAILURES:") + for f in failures: + print(" - " + f) + sys.exit(1) +print("ALL PASS") diff --git a/widgets/tools/glyphs_inst.py b/widgets/tools/glyphs_inst.py index 49e5edd..797cf95 100644 --- a/widgets/tools/glyphs_inst.py +++ b/widgets/tools/glyphs_inst.py @@ -1,12 +1,12 @@ #!/usr/bin/env python3 -"""Unique 16x16 icons for the Instrumentation section (54 widgets). +"""Unique 16x16 icons for the Instrumentation section (66 widgets). Covers the 8 tank/level widgets, 12 switches, 12 lamps/LEDs, 8 gauges, 4 panel-furniture widgets, 6 old-style 7-segment LED digit displays (1-6 digits) and 4 analog needle types. Every glyph is drawn with PIL ImageDraw in the 16x16 box, in the same base language as tools/gen_icons.py (dark ink INK + MID on white) plus the amber section -accent and 1-2 bright colours per glyph, so all 54 are visibly different +accent and 1-2 bright colours per glyph, so all 66 are visibly different from each other and from the 481 icons that came before. No photorealism, no photo textures: plain hand-drawn widget glyphs. @@ -14,10 +14,12 @@ Motifs by family: tanks with a fill line for level, tilted rockers / levers for switches, glowing dots for lamps, dials with needles for gauges, plates/bezels for panel furniture, red 7-segment digits (digit count = widget) for the LED displays, and four distinct needle shapes -(tapered, knife-edge, edgewise, VU) for needles. +(tapered, knife-edge, edgewise, VU) for needles, plus amber +14/16-segment alphanumeric displays (digit count = widget; 14-seg +shows A/B/C/H/E/L/O text, 16-seg shows M/W text on a bluer glass). Usage: python3 widgets/tools/glyphs_inst.py (run from the repo root) -Regenerates ONLY these 54 .ico files into widgets/icons/. +Regenerates ONLY these 66 .ico files into widgets/icons/. """ import colorsys import os @@ -64,9 +66,13 @@ GROUP_F = ("InstLedDigits1", "InstLedDigits2", "InstLedDigits3", "InstLedDigits4", "InstLedDigits5", "InstLedDigits6", "InstNeedleTapered", "InstNeedleKnifeEdge", "InstNeedleEdgewise", "InstNeedleVu") +GROUP_G = ("InstSeg14Display1", "InstSeg14Display2", "InstSeg14Display3", + "InstSeg14Display4", "InstSeg14Display5", "InstSeg14Display6", + "InstSeg16Display1", "InstSeg16Display2", "InstSeg16Display3", + "InstSeg16Display4", "InstSeg16Display5", "InstSeg16Display6") ALL_INST = (list(GROUP_A) + list(GROUP_B) + list(GROUP_C) - + list(GROUP_D) + list(GROUP_E) + list(GROUP_F)) -assert len(ALL_INST) == len(set(ALL_INST)) == 54 + + list(GROUP_D) + list(GROUP_E) + list(GROUP_F) + list(GROUP_G)) +assert len(ALL_INST) == len(set(ALL_INST)) == 66 # ---------------------------------------------------------------- helpers @@ -547,6 +553,73 @@ def m_needle_vu(d, c1, c2, a): d.ellipse([6, 11, 8, 13], fill=INK) + +# --- Group G: 14/16-segment alphanumeric displays ------------------------- +_SEG14_MAP = { + '0': "a b c d e f", '1': "b c", '2': "a b d e g1 g2", + '3': "a b c d g1 g2", '4': "b c f g1 g2", '5': "a c d f g1 g2", + '6': "a c d e f g1 g2", '7': "a b c", '8': "a b c d e f g1 g2", + '9': "a b c d f g1 g2", + 'A': "a b c e f g1 g2", 'B': "a b c d g1 g2 i l", 'C': "a d e f", + 'E': "a d e f g1 g2", 'H': "b c e f g1 g2", 'L': "d e f", + 'M': "b c e f h j", 'O': "a b c d e f", 'W': "b c e f k m", +} +_SEG16_MAP = { + '0': "a1 a2 b c d1 d2 e f", '1': "b c", '2': "a1 a2 b d1 d2 e g1 g2", + '3': "a1 a2 b c d1 d2 g1 g2", 'A': "a1 a2 b c e f g1 g2", + 'B': "a1 a2 b c d1 d2 g1 g2 i l", 'C': "a1 a2 d1 d2 e f", + 'E': "a1 a2 d1 d2 e f g1 g2", 'H': "b c e f g1 g2", 'L': "d1 d2 e f", + 'M': "b c e f h i j", 'O': "a1 a2 b c d1 d2 e f", 'W': "b c e f k l m", +} + + +def _seg_cell(d, x, y, cw, segs, lit, dim): + def R(rx, ry, rw, rh, on): + d.rectangle([rx, ry, rx + max(0, rw - 1), ry + max(0, rh - 1)], + fill=lit if on else dim) + def L(x1, y1, x2, y2, on): + d.line([x1, y1, x2, y2], fill=lit if on else dim) + hw = max(1, cw // 2 - 1) + R(x + 1, y, max(1, cw - 2), 1, "a" in segs) + R(x + 1, y, hw, 1, "a1" in segs) + R(x + cw // 2, y, hw, 1, "a2" in segs) + R(x + cw - 1, y + 1, 1, 2, "b" in segs) + R(x + cw - 1, y + 4, 1, 2, "c" in segs) + R(x + 1, y + 6, max(1, cw - 2), 1, "d" in segs) + R(x + 1, y + 6, hw, 1, "d1" in segs) + R(x + cw // 2, y + 6, hw, 1, "d2" in segs) + R(x, y + 4, 1, 2, "e" in segs) + R(x, y + 1, 1, 2, "f" in segs) + R(x + 1, y + 3, hw, 1, "g1" in segs) + R(x + cw // 2, y + 3, hw, 1, "g2" in segs) + R(x + cw // 2, y + 1, 1, 2, "i" in segs) + R(x + cw // 2, y + 4, 1, 2, "l" in segs) + L(x + 1, y + 1, x + cw // 2, y + 3, "h" in segs) + L(x + cw - 2, y + 1, x + cw // 2, y + 3, "j" in segs) + L(x + 1, y + 5, x + cw // 2, y + 3, "k" in segs) + L(x + cw - 2, y + 5, x + cw // 2, y + 3, "m" in segs) + + +def _seg_display(value, segmap, glass): + def draw(d, c1, c2, a): + d.rectangle([0, 2, 15, 13], outline=INK, fill=glass) + n = len(value) + step = max(2, 14 // n) + cw = max(1, step - 1) + for i, ch in enumerate(value): + _seg_cell(d, 1 + i * step, 4, cw, + set(segmap.get(ch, "").split()), + (255, 176, 0), (96, 66, 12)) + return draw + + +def _seg14_for(value): + return _seg_display(value, _SEG14_MAP, (18, 18, 20)) + + +def _seg16_for(value): + return _seg_display(value, _SEG16_MAP, (16, 18, 28)) + # ---------------------------------------------------------------- dispatch MOTIFS = { "InstVerticalTankLevel": m_vtank, @@ -603,6 +676,18 @@ MOTIFS = { "InstNeedleKnifeEdge": m_needle_knife, "InstNeedleEdgewise": m_needle_edgewise, "InstNeedleVu": m_needle_vu, + "InstSeg14Display1": _seg14_for("A"), + "InstSeg14Display2": _seg14_for("AB"), + "InstSeg14Display3": _seg14_for("ABC"), + "InstSeg14Display4": _seg14_for("HELL"), + "InstSeg14Display5": _seg14_for("HELLO"), + "InstSeg14Display6": _seg14_for("ABC123"), + "InstSeg16Display1": _seg16_for("M"), + "InstSeg16Display2": _seg16_for("MW"), + "InstSeg16Display3": _seg16_for("MWM"), + "InstSeg16Display4": _seg16_for("MWMW"), + "InstSeg16Display5": _seg16_for("MWMWM"), + "InstSeg16Display6": _seg16_for("MWMWMW"), } assert set(MOTIFS) == set(ALL_INST)