diff --git a/examples/XCoreGrid.cpp b/examples/XCoreGrid.cpp new file mode 100644 index 0000000..a3f6de0 --- /dev/null +++ b/examples/XCoreGrid.cpp @@ -0,0 +1,73 @@ +// XCoreGrid -- minimal XFrame example (C++). +// Build: g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets XCoreGrid.cpp -lX11 -o XCoreGrid +// Run under Xvfb (or a real X server); close the window to quit. +// Setup mirrors the widget's own demo in widgets/components/XCoreGrid/main_XCoreGrid.cpp. +#include "XCoreGrid/XCoreGrid.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XCoreGrid - 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"); + XCoreGrid widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/examples/XHistoryGraph.cpp b/examples/XHistoryGraph.cpp new file mode 100644 index 0000000..5565c18 --- /dev/null +++ b/examples/XHistoryGraph.cpp @@ -0,0 +1,73 @@ +// XHistoryGraph -- minimal XFrame example (C++). +// Build: g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets XHistoryGraph.cpp -lX11 -o XHistoryGraph +// Run under Xvfb (or a real X server); close the window to quit. +// Setup mirrors the widget's own demo in widgets/components/XHistoryGraph/main_XHistoryGraph.cpp. +#include "XHistoryGraph/XHistoryGraph.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XHistoryGraph - 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"); + XHistoryGraph widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/examples/XNetGraph.cpp b/examples/XNetGraph.cpp new file mode 100644 index 0000000..e6d452e --- /dev/null +++ b/examples/XNetGraph.cpp @@ -0,0 +1,73 @@ +// XNetGraph -- minimal XFrame example (C++). +// Build: g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets XNetGraph.cpp -lX11 -o XNetGraph +// Run under Xvfb (or a real X server); close the window to quit. +// Setup mirrors the widget's own demo in widgets/components/XNetGraph/main_XNetGraph.cpp. +#include "XNetGraph/XNetGraph.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XNetGraph - 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"); + XNetGraph widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/examples/XTempHistory.cpp b/examples/XTempHistory.cpp new file mode 100644 index 0000000..2324435 --- /dev/null +++ b/examples/XTempHistory.cpp @@ -0,0 +1,73 @@ +// XTempHistory -- minimal XFrame example (C++). +// Build: g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets XTempHistory.cpp -lX11 -o XTempHistory +// Run under Xvfb (or a real X server); close the window to quit. +// Setup mirrors the widget's own demo in widgets/components/XTempHistory/main_XTempHistory.cpp. +#include "XTempHistory/XTempHistory.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XTempHistory - 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"); + XTempHistory widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/XCoreGrid/CMakeLists.txt b/widgets/components/XCoreGrid/CMakeLists.txt new file mode 100644 index 0000000..42f0adc --- /dev/null +++ b/widgets/components/XCoreGrid/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(XCoreGrid LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(XCoreGrid main_XCoreGrid.cpp) + +target_link_libraries(XCoreGrid PRIVATE X11::X11) diff --git a/widgets/components/XCoreGrid/XCoreGrid.h b/widgets/components/XCoreGrid/XCoreGrid.h new file mode 100644 index 0000000..99220cc --- /dev/null +++ b/widgets/components/XCoreGrid/XCoreGrid.h @@ -0,0 +1,242 @@ +#pragma once + +#include "core/xframe_core.h" + +#include +#include +#include +#include +#include + +// region XCoreGrid +// +// A grid of mini history graphs, one per CPU core (Task Manager per-core +// view): each cell shows its core label, current % and a scrolling line +// of recent samples. Raw X11, same as the rest of the XFrame set. +// +class XCoreGrid +{ +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; + + int cores_ = 8; + int capacity_ = 60; + std::vector> history_; + std::vector current_; + + Srgb white_color_{255, 255, 255}; + Srgb grid_color_{225, 225, 225}; + Srgb axis_color_{150, 150, 150}; + + unsigned long col(Srgb c) { return styles_->get_color_Srgb(c); } + + static Srgb color_for(double pct) + { + if (pct < 50.0) return Srgb{0, 170, 70}; + if (pct < 80.0) return Srgb{200, 170, 0}; + return Srgb{210, 40, 30}; + } + + void draw_text_color(int x, int baseline_y, const std::string& s, Srgb color) + { + SStyle st = style(); + if (!st.font_ || s.empty()) return; + XSetFont(display_, gc_, st.font_->fid); + XSetForeground(display_, gc_, col(color)); + XDrawString(display_, window_, gc_, x, baseline_y, s.c_str(), (int)s.size()); + } + + void ensure_cores() + { + if ((int)history_.size() != cores_) + { + history_.assign(cores_, std::vector()); + current_.assign(cores_, 0.0); + } + } + +public: + XCoreGrid(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_ = "XCoreGrid"; + text_ = "CPU cores"; + ensure_cores(); + + // Preload a demo: 8 cores, seeded sine + noise at different phases. + unsigned int seed = 424242; + auto rnd = [&]() { + seed = seed * 1103515245 + 12345; + return ((seed >> 16) & 0x7fff) / 32767.0; + }; + for (int i = 0; i < capacity_; ++i) + { + double t = (double)i / capacity_; + for (int c = 0; c < cores_; ++c) + { + double v = 45.0 + 38.0 * std::sin(t * 7.0 + c * 1.3) + (rnd() - 0.5) * 22.0; + push(c, std::max(0.0, std::min(100.0, v))); + } + } + } + + ~XCoreGrid() {} + + // region Standard plumbing + void set_bounds(int x, int y, int width, int height) + { + x1_ = x; + y1_ = y; + x2_ = x + width; + y2_ = y + height; + } + int width() { return x2_ - x1_; } + int height() { 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_; } + 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_); } + // endregion + + // region Core API + void set_core_count(int n) + { + cores_ = n > 0 ? n : 1; + ensure_cores(); + } + int core_count() { return cores_; } + void push(int core, double pct) + { + if (core < 0 || core >= cores_) return; + ensure_cores(); + pct = std::max(0.0, std::min(100.0, pct)); + history_[core].push_back(pct); + while ((int)history_[core].size() > capacity_) history_[core].erase(history_[core].begin()); + current_[core] = pct; + } + void push_all(const std::vector& pcts) + { + for (size_t i = 0; i < pcts.size() && (int)i < cores_; ++i) push((int)i, pcts[i]); + } + double core_value(int core) + { + if (core < 0 || core >= cores_) return 0.0; + return current_[core]; + } + // endregion + + void draw() + { + if (!visible_) return; + SStyle st = style(); + int w = width(); + int h = height(); + XSetForeground(display_, gc_, col(white_color_)); + XFillRectangle(display_, window_, gc_, x1_, y1_, w, h); + ensure_cores(); + + const int title_h = 20; + int cols = (int)std::ceil(std::sqrt((double)cores_)); + int rows = (cores_ + cols - 1) / cols; + int cell_w = (w - 8) / cols; + int cell_h = (h - title_h - 8) / rows; + + xf::draw_text_at(display_, window_, gc_, st, x1_ + 8, y1_ + 15, text_); + + for (int c = 0; c < cores_; ++c) + { + int cx = x1_ + 4 + (c % cols) * cell_w; + int cy = y1_ + title_h + 4 + (c / cols) * cell_h; + int cw = cell_w - 4; + int ch = cell_h - 4; + // Cell frame. + XSetForeground(display_, gc_, col(axis_color_)); + XDrawRectangle(display_, window_, gc_, cx, cy, cw, ch); + // Label + current %. + char label[32]; + std::snprintf(label, sizeof(label), "C%d %.0f%%", c, current_[c]); + draw_text_color(cx + 5, cy + 14, label, color_for(current_[c])); + // Mini history graph. + int gx = cx + 4; + int gy = cy + 18; + int gw = std::max(10, cw - 8); + int gh = std::max(6, ch - 22); + XSetForeground(display_, gc_, col(grid_color_)); + XDrawLine(display_, window_, gc_, gx, gy + gh / 2, gx + gw, gy + gh / 2); + auto& hist = history_[c]; + if (hist.size() >= 2) + { + std::vector pts; + int n = (int)hist.size(); + for (int i = 0; i < n; ++i) + { + int px = gx + (int)((double)i / (capacity_ - 1) * gw); + int py = gy + gh - (int)(hist[i] / 100.0 * gh); + pts.push_back(XPoint{(short)px, (short)py}); + } + XSetForeground(display_, gc_, col(color_for(current_[c]))); + xf::set_line_width(display_, gc_, 2); + XDrawLines(display_, window_, gc_, pts.data(), (int)pts.size(), CoordModeOrigin); + xf::set_line_width(display_, gc_, 1); + } + } + + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_, y1_, w, h); + XFlush(display_); + } + + bool on_button_press(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_button_release(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_motion(int x, int y) + { + (void)x; + (void)y; + return false; + } + bool on_key(KeySym key, const char* str) + { + (void)key; + (void)str; + return false; + } +}; diff --git a/widgets/components/XCoreGrid/core/xframe_core.h b/widgets/components/XCoreGrid/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/XCoreGrid/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/XCoreGrid/main_XCoreGrid.cpp b/widgets/components/XCoreGrid/main_XCoreGrid.cpp new file mode 100644 index 0000000..a67a0ef --- /dev/null +++ b/widgets/components/XCoreGrid/main_XCoreGrid.cpp @@ -0,0 +1,69 @@ +#include "XCoreGrid.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XCoreGrid - 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"); + XCoreGrid widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/XHistoryGraph/CMakeLists.txt b/widgets/components/XHistoryGraph/CMakeLists.txt new file mode 100644 index 0000000..e9b51f5 --- /dev/null +++ b/widgets/components/XHistoryGraph/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(XHistoryGraph LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(XHistoryGraph main_XHistoryGraph.cpp) + +target_link_libraries(XHistoryGraph PRIVATE X11::X11) diff --git a/widgets/components/XHistoryGraph/XHistoryGraph.h b/widgets/components/XHistoryGraph/XHistoryGraph.h new file mode 100644 index 0000000..d4f7305 --- /dev/null +++ b/widgets/components/XHistoryGraph/XHistoryGraph.h @@ -0,0 +1,301 @@ +#pragma once + +#include "core/xframe_core.h" + +#include +#include +#include +#include +#include + +// region XHistoryGraph +// +// A scrolling multi-series time-series line graph in the XFrame format: +// push samples per series, keep a fixed time window (60 s default), draw +// each series in its own colour with a legend showing current / min / +// max / average. Same interaction model as XGraph, raw X11 only. +// +class XHistoryGraph +{ +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; + + struct Series + { + std::string name; + Srgb color{0, 150, 60}; + std::vector data; + }; + + std::vector series_; + int window_seconds_ = 60; // fixed time window shown + int capacity_ = 120; // samples kept per series (2 Hz) + double y_min_ = 0.0; // fixed floor; set_y_range overrides + double y_max_ = 0.0; // 0 = auto from data + bool auto_y_ = true; + + Srgb white_color_{255, 255, 255}; + Srgb grid_color_{225, 225, 225}; + Srgb axis_color_{150, 150, 150}; + + unsigned long col(Srgb c) { return styles_->get_color_Srgb(c); } + + static std::string fmt1(double v) + { + char buf[32]; + std::snprintf(buf, sizeof(buf), "%.1f", v); + return buf; + } + + void draw_text_color(int x, int baseline_y, const std::string& s, Srgb color) + { + SStyle st = style(); + if (!st.font_ || s.empty()) return; + XSetFont(display_, gc_, st.font_->fid); + XSetForeground(display_, gc_, col(color)); + XDrawString(display_, window_, gc_, x, baseline_y, s.c_str(), (int)s.size()); + } + +public: + XHistoryGraph(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_ = "XHistoryGraph"; + text_ = "History"; + + // Preload a demo: two seeded series (CPU-ish sine + noise, MEM-ish drift). + add_series("CPU", Srgb{0, 170, 70}); + add_series("MEM", Srgb{0, 100, 200}); + unsigned int seed = 987654321; + auto rnd = [&]() { + seed = seed * 1103515245 + 12345; + return ((seed >> 16) & 0x7fff) / 32767.0; + }; + for (int i = 0; i < capacity_; ++i) + { + double t = (double)i / capacity_; + push(0, 55.0 + 30.0 * std::sin(t * 9.0) + (rnd() - 0.5) * 18.0); + push(1, 38.0 + 14.0 * std::sin(t * 4.0 + 1.0) + (rnd() - 0.5) * 6.0); + } + } + + ~XHistoryGraph() {} + + // region Standard plumbing + void set_bounds(int x, int y, int width, int height) + { + x1_ = x; + y1_ = y; + x2_ = x + width; + y2_ = y + height; + } + int width() { return x2_ - x1_; } + int height() { 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_; } + 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_); } + // endregion + + // region Series API + void add_series(const std::string& name, Srgb color) + { + Series s; + s.name = name; + s.color = color; + series_.push_back(s); + } + void clear_series() { series_.clear(); } + int series_count() { return (int)series_.size(); } + void set_window_seconds(int seconds) + { + window_seconds_ = seconds > 0 ? seconds : 60; + capacity_ = window_seconds_ * 2; + for (auto& s : series_) + while ((int)s.data.size() > capacity_) s.data.erase(s.data.begin()); + } + int get_window_seconds() { return window_seconds_; } + void set_y_range(double lo, double hi) + { + auto_y_ = false; + y_min_ = lo; + y_max_ = hi; + } + void set_auto_y(bool on) { auto_y_ = on; } + void push(int series, double value) + { + if (series < 0 || series >= (int)series_.size()) return; + series_[series].data.push_back(value); + while ((int)series_[series].data.size() > capacity_) + series_[series].data.erase(series_[series].data.begin()); + } + void push_all(const std::vector& values) + { + for (size_t i = 0; i < values.size() && i < series_.size(); ++i) push((int)i, values[i]); + } + double last_value(int series) + { + if (series < 0 || series >= (int)series_.size() || series_[series].data.empty()) return 0.0; + return series_[series].data.back(); + } + // endregion + + void draw() + { + if (!visible_) return; + SStyle st = style(); + int w = width(); + int h = height(); + XSetForeground(display_, gc_, col(white_color_)); + XFillRectangle(display_, window_, gc_, x1_, y1_, w, h); + + const int title_h = 20; + const int legend_h = 18 * (int)series_.size(); + const int axis_w = 44; + const int axis_h = 16; + int px = x1_ + axis_w; + int py = y1_ + title_h + legend_h + 4; + int pw = std::max(10, x2_ - 8 - px); + int ph = std::max(10, y2_ - axis_h - py); + + // Title. + xf::draw_text_at(display_, window_, gc_, st, x1_ + 8, y1_ + 15, text_); + + // Y range. + double lo = y_min_; + double hi = y_max_; + if (auto_y_) + { + lo = 0.0; + hi = 1.0; + for (auto& s : series_) + for (double v : s.data) hi = std::max(hi, v); + hi *= 1.05; + } + if (hi <= lo) hi = lo + 1.0; + + auto y_at = [&](double v) { + return py + ph - (int)((v - lo) / (hi - lo) * ph); + }; + + // Grid + y labels. + XSetForeground(display_, gc_, col(grid_color_)); + for (int g = 0; g <= 4; ++g) + { + int gy = py + ph * g / 4; + XDrawLine(display_, window_, gc_, px, gy, px + pw, gy); + } + for (int g = 0; g <= 4; ++g) + { + double v = lo + (hi - lo) * (4 - g) / 4.0; + draw_text_color(px - 40, py + ph * g / 4 + 4, fmt1(v), Srgb{100, 100, 100}); + } + // Time labels. + draw_text_color(px, y2_ - 3, "-" + std::to_string(window_seconds_) + "s", Srgb{100, 100, 100}); + std::string now_s = "now"; + draw_text_color(px + pw - xf::text_width(st, now_s), y2_ - 3, now_s, Srgb{100, 100, 100}); + + // Series lines. + for (auto& s : series_) + { + if (s.data.size() < 2) continue; + std::vector pts; + int n = (int)s.data.size(); + for (int i = 0; i < n; ++i) + { + int cx = px + (int)((double)i / (capacity_ - 1) * pw); + pts.push_back(XPoint{(short)cx, (short)y_at(s.data[i])}); + } + XSetForeground(display_, gc_, col(s.color)); + xf::set_line_width(display_, gc_, 2); + XDrawLines(display_, window_, gc_, pts.data(), (int)pts.size(), CoordModeOrigin); + xf::set_line_width(display_, gc_, 1); + } + + // Legend: swatch + name + current / min / max / avg. + int ly = y1_ + title_h + 4; + for (auto& s : series_) + { + double cur = 0.0, mn = 0.0, mx = 0.0, sum = 0.0; + if (!s.data.empty()) + { + cur = s.data.back(); + mn = mx = s.data[0]; + for (double v : s.data) + { + mn = std::min(mn, v); + mx = std::max(mx, v); + sum += v; + } + sum /= (double)s.data.size(); + } + XSetForeground(display_, gc_, col(s.color)); + XFillRectangle(display_, window_, gc_, x1_ + 8, ly - 2, 18, 4); + std::string leg = s.name + " cur " + fmt1(cur) + " min " + fmt1(mn) + + " max " + fmt1(mx) + " avg " + fmt1(sum); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 32, ly + 8, leg); + ly += 18; + } + + // Plot frame + outer frame. + XSetForeground(display_, gc_, col(axis_color_)); + XDrawRectangle(display_, window_, gc_, px, py, pw, ph); + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_, y1_, w, h); + XFlush(display_); + } + + bool on_button_press(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_button_release(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_motion(int x, int y) + { + (void)x; + (void)y; + return false; + } + bool on_key(KeySym key, const char* str) + { + (void)key; + (void)str; + return false; + } +}; diff --git a/widgets/components/XHistoryGraph/core/xframe_core.h b/widgets/components/XHistoryGraph/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/XHistoryGraph/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/XHistoryGraph/main_XHistoryGraph.cpp b/widgets/components/XHistoryGraph/main_XHistoryGraph.cpp new file mode 100644 index 0000000..3c62749 --- /dev/null +++ b/widgets/components/XHistoryGraph/main_XHistoryGraph.cpp @@ -0,0 +1,69 @@ +#include "XHistoryGraph.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XHistoryGraph - 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"); + XHistoryGraph widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/XNetGraph/CMakeLists.txt b/widgets/components/XNetGraph/CMakeLists.txt new file mode 100644 index 0000000..e5afde0 --- /dev/null +++ b/widgets/components/XNetGraph/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(XNetGraph LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(XNetGraph main_XNetGraph.cpp) + +target_link_libraries(XNetGraph PRIVATE X11::X11) diff --git a/widgets/components/XNetGraph/XNetGraph.h b/widgets/components/XNetGraph/XNetGraph.h new file mode 100644 index 0000000..5e1cae4 --- /dev/null +++ b/widgets/components/XNetGraph/XNetGraph.h @@ -0,0 +1,258 @@ +#pragma once + +#include "core/xframe_core.h" + +#include +#include +#include +#include +#include + +// region XNetGraph +// +// Dual up/down scrolling network graph (btop net box): two overlaid +// series in bytes/s, current rates plus running totals in the legend. +// Raw X11, same as the rest of the XFrame set. +// +class XNetGraph +{ +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; + + int capacity_ = 120; + std::vector down_; // bytes/s + std::vector up_; // bytes/s + double down_total_ = 0.0; // bytes + double up_total_ = 0.0; // bytes + double y_max_ = 0.0; // 0 = auto + + Srgb white_color_{255, 255, 255}; + Srgb grid_color_{225, 225, 225}; + Srgb axis_color_{150, 150, 150}; + Srgb down_color_{0, 170, 70}; + Srgb up_color_{220, 80, 40}; + + unsigned long col(Srgb c) { return styles_->get_color_Srgb(c); } + + static std::string fmt_rate(double bps) + { + char buf[40]; + if (bps < 1024.0) std::snprintf(buf, sizeof(buf), "%.0f B/s", bps); + else if (bps < 1024.0 * 1024.0) std::snprintf(buf, sizeof(buf), "%.1f KiB/s", bps / 1024.0); + else std::snprintf(buf, sizeof(buf), "%.2f MiB/s", bps / (1024.0 * 1024.0)); + return buf; + } + + static std::string fmt_total(double bytes) + { + char buf[40]; + if (bytes < 1024.0) std::snprintf(buf, sizeof(buf), "%.0f B", bytes); + else if (bytes < 1024.0 * 1024.0) std::snprintf(buf, sizeof(buf), "%.1f KiB", bytes / 1024.0); + else if (bytes < 1024.0 * 1024.0 * 1024.0) std::snprintf(buf, sizeof(buf), "%.2f MiB", bytes / (1024.0 * 1024.0)); + else std::snprintf(buf, sizeof(buf), "%.2f GiB", bytes / (1024.0 * 1024.0 * 1024.0)); + return buf; + } + + void draw_text_color(int x, int baseline_y, const std::string& s, Srgb color) + { + SStyle st = style(); + if (!st.font_ || s.empty()) return; + XSetFont(display_, gc_, st.font_->fid); + XSetForeground(display_, gc_, col(color)); + XDrawString(display_, window_, gc_, x, baseline_y, s.c_str(), (int)s.size()); + } + + void draw_series(const std::vector& data, int px, int py, int pw, int ph, double hi, Srgb color) + { + if (data.size() < 2) return; + std::vector pts; + int n = (int)data.size(); + for (int i = 0; i < n; ++i) + { + int cx = px + (int)((double)i / (capacity_ - 1) * pw); + int cy = py + ph - (int)(data[i] / hi * ph); + pts.push_back(XPoint{(short)cx, (short)cy}); + } + XSetForeground(display_, gc_, col(color)); + xf::set_line_width(display_, gc_, 2); + XDrawLines(display_, window_, gc_, pts.data(), (int)pts.size(), CoordModeOrigin); + xf::set_line_width(display_, gc_, 1); + } + +public: + XNetGraph(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_ = "XNetGraph"; + text_ = "Network"; + + // Preload a demo: bursty download, steadier upload (bytes/s). + unsigned int seed = 13579; + auto rnd = [&]() { + seed = seed * 1103515245 + 12345; + return ((seed >> 16) & 0x7fff) / 32767.0; + }; + for (int i = 0; i < capacity_; ++i) + { + double t = (double)i / capacity_; + double burst = (std::sin(t * 12.0) > 0.2) ? 1.0 : 0.15; + push(180000.0 * burst * (0.5 + rnd()), 24000.0 * (0.6 + rnd() * 0.7)); + } + } + + ~XNetGraph() {} + + // region Standard plumbing + void set_bounds(int x, int y, int width, int height) + { + x1_ = x; + y1_ = y; + x2_ = x + width; + y2_ = y + height; + } + int width() { return x2_ - x1_; } + int height() { 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_; } + 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_); } + // endregion + + // region Net API + // Rates are bytes/s; each push counts as a 0.5 s sample for totals. + void push(double down_bps, double up_bps) + { + down_.push_back(std::max(0.0, down_bps)); + up_.push_back(std::max(0.0, up_bps)); + down_total_ += std::max(0.0, down_bps) * 0.5; + up_total_ += std::max(0.0, up_bps) * 0.5; + while ((int)down_.size() > capacity_) down_.erase(down_.begin()); + while ((int)up_.size() > capacity_) up_.erase(up_.begin()); + } + double down_rate() { return down_.empty() ? 0.0 : down_.back(); } + double up_rate() { return up_.empty() ? 0.0 : up_.back(); } + double down_total() { return down_total_; } + double up_total() { return up_total_; } + void reset_totals() + { + down_total_ = 0.0; + up_total_ = 0.0; + } + // endregion + + void draw() + { + if (!visible_) return; + SStyle st = style(); + int w = width(); + int h = height(); + XSetForeground(display_, gc_, col(white_color_)); + XFillRectangle(display_, window_, gc_, x1_, y1_, w, h); + + const int title_h = 20; + const int legend_h = 44; + const int axis_w = 52; + const int axis_h = 16; + int px = x1_ + axis_w; + int py = y1_ + title_h + legend_h + 4; + int pw = std::max(10, x2_ - 8 - px); + int ph = std::max(10, y2_ - axis_h - py); + + xf::draw_text_at(display_, window_, gc_, st, x1_ + 8, y1_ + 15, text_); + + double hi = y_max_; + if (hi <= 0.0) + { + hi = 1.0; + for (double v : down_) hi = std::max(hi, v); + for (double v : up_) hi = std::max(hi, v); + hi *= 1.05; + } + + // Grid + y labels. + XSetForeground(display_, gc_, col(grid_color_)); + for (int g = 0; g <= 4; ++g) + { + int gy = py + ph * g / 4; + XDrawLine(display_, window_, gc_, px, gy, px + pw, gy); + } + for (int g = 0; g <= 4; ++g) + { + double v = hi * (4 - g) / 4.0; + draw_text_color(px - 48, py + ph * g / 4 + 4, fmt_rate(v), Srgb{100, 100, 100}); + } + + draw_series(down_, px, py, pw, ph, hi, down_color_); + draw_series(up_, px, py, pw, ph, hi, up_color_); + + // Legend: current rates + totals. + XSetForeground(display_, gc_, col(down_color_)); + XFillRectangle(display_, window_, gc_, x1_ + 8, y1_ + title_h + 6, 18, 4); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 32, y1_ + title_h + 16, + "down " + fmt_rate(down_rate()) + " total " + fmt_total(down_total_)); + XSetForeground(display_, gc_, col(up_color_)); + XFillRectangle(display_, window_, gc_, x1_ + 8, y1_ + title_h + 24, 18, 4); + xf::draw_text_at(display_, window_, gc_, st, x1_ + 32, y1_ + title_h + 34, + "up " + fmt_rate(up_rate()) + " total " + fmt_total(up_total_)); + + XSetForeground(display_, gc_, col(axis_color_)); + XDrawRectangle(display_, window_, gc_, px, py, pw, ph); + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_, y1_, w, h); + XFlush(display_); + } + + bool on_button_press(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_button_release(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_motion(int x, int y) + { + (void)x; + (void)y; + return false; + } + bool on_key(KeySym key, const char* str) + { + (void)key; + (void)str; + return false; + } +}; diff --git a/widgets/components/XNetGraph/core/xframe_core.h b/widgets/components/XNetGraph/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/XNetGraph/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/XNetGraph/main_XNetGraph.cpp b/widgets/components/XNetGraph/main_XNetGraph.cpp new file mode 100644 index 0000000..ac44a10 --- /dev/null +++ b/widgets/components/XNetGraph/main_XNetGraph.cpp @@ -0,0 +1,69 @@ +#include "XNetGraph.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XNetGraph - 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"); + XNetGraph widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/XTempHistory/CMakeLists.txt b/widgets/components/XTempHistory/CMakeLists.txt new file mode 100644 index 0000000..52b8d9c --- /dev/null +++ b/widgets/components/XTempHistory/CMakeLists.txt @@ -0,0 +1,13 @@ +cmake_minimum_required(VERSION 3.20) + +project(XTempHistory LANGUAGES CXX) + +set(CMAKE_CXX_STANDARD 17) + +set(CMAKE_CXX_STANDARD_REQUIRED ON) + +find_package(X11 REQUIRED) + +add_executable(XTempHistory main_XTempHistory.cpp) + +target_link_libraries(XTempHistory PRIVATE X11::X11) diff --git a/widgets/components/XTempHistory/XTempHistory.h b/widgets/components/XTempHistory/XTempHistory.h new file mode 100644 index 0000000..7316620 --- /dev/null +++ b/widgets/components/XTempHistory/XTempHistory.h @@ -0,0 +1,249 @@ +#pragma once + +#include "core/xframe_core.h" + +#include +#include +#include +#include +#include + +// region XTempHistory +// +// Temperature history with a threshold line: samples above the threshold +// draw red, the threshold itself is a dashed red line, current / min / +// max in the legend. Raw X11, same as the rest of the XFrame set. +// +class XTempHistory +{ +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; + + int capacity_ = 120; + std::vector temps_; + double threshold_ = 80.0; // degrees C: over-temp line + double y_max_ = 100.0; // fixed scale 0..100 C by default + + Srgb white_color_{255, 255, 255}; + Srgb grid_color_{225, 225, 225}; + Srgb axis_color_{150, 150, 150}; + Srgb ok_color_{0, 170, 70}; + Srgb hot_color_{210, 40, 30}; + + unsigned long col(Srgb c) { return styles_->get_color_Srgb(c); } + + static std::string fmt1(double v) + { + char buf[32]; + std::snprintf(buf, sizeof(buf), "%.1f", v); + return buf; + } + + void draw_text_color(int x, int baseline_y, const std::string& s, Srgb color) + { + SStyle st = style(); + if (!st.font_ || s.empty()) return; + XSetFont(display_, gc_, st.font_->fid); + XSetForeground(display_, gc_, col(color)); + XDrawString(display_, window_, gc_, x, baseline_y, s.c_str(), (int)s.size()); + } + +public: + XTempHistory(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_ = "XTempHistory"; + text_ = "Temperature"; + + // Preload a demo: warm-up ramp crossing the 80 C threshold. + unsigned int seed = 777; + auto rnd = [&]() { + seed = seed * 1103515245 + 12345; + return ((seed >> 16) & 0x7fff) / 32767.0; + }; + for (int i = 0; i < capacity_; ++i) + { + double t = (double)i / capacity_; + push(52.0 + 34.0 * t + 4.0 * std::sin(t * 10.0) + (rnd() - 0.5) * 3.0); + } + } + + ~XTempHistory() {} + + // region Standard plumbing + void set_bounds(int x, int y, int width, int height) + { + x1_ = x; + y1_ = y; + x2_ = x + width; + y2_ = y + height; + } + int width() { return x2_ - x1_; } + int height() { 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_; } + 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_); } + // endregion + + // region Temp API + void push(double temp_c) + { + temps_.push_back(temp_c); + while ((int)temps_.size() > capacity_) temps_.erase(temps_.begin()); + } + void set_threshold(double t) { threshold_ = t; } + double get_threshold() { return threshold_; } + void set_y_max(double v) { y_max_ = v > 0.0 ? v : 100.0; } + double current() + { + return temps_.empty() ? 0.0 : temps_.back(); + } + bool over_temp() { return current() >= threshold_; } + // endregion + + void draw() + { + if (!visible_) return; + SStyle st = style(); + int w = width(); + int h = height(); + XSetForeground(display_, gc_, col(white_color_)); + XFillRectangle(display_, window_, gc_, x1_, y1_, w, h); + + const int title_h = 20; + const int legend_h = 18; + const int axis_w = 44; + const int axis_h = 16; + int px = x1_ + axis_w; + int py = y1_ + title_h + legend_h + 4; + int pw = std::max(10, x2_ - 8 - px); + int ph = std::max(10, y2_ - axis_h - py); + double hi = y_max_ > 0.0 ? y_max_ : 100.0; + + auto y_at = [&](double v) { + return py + ph - (int)(std::max(0.0, std::min(hi, v)) / hi * ph); + }; + + xf::draw_text_at(display_, window_, gc_, st, x1_ + 8, y1_ + 15, text_); + + // Grid + y labels. + XSetForeground(display_, gc_, col(grid_color_)); + for (int g = 0; g <= 4; ++g) + { + int gy = py + ph * g / 4; + XDrawLine(display_, window_, gc_, px, gy, px + pw, gy); + } + for (int g = 0; g <= 4; ++g) + { + double v = hi * (4 - g) / 4.0; + draw_text_color(px - 40, py + ph * g / 4 + 4, fmt1(v) + "C", Srgb{100, 100, 100}); + } + + // Threshold: dashed red line + label. + { + XGCValues gv; + gv.line_style = LineOnOffDash; + XChangeGC(display_, gc_, GCLineStyle, &gv); + XSetForeground(display_, gc_, col(hot_color_)); + int ty = y_at(threshold_); + XDrawLine(display_, window_, gc_, px, ty, px + pw, ty); + gv.line_style = LineSolid; + XChangeGC(display_, gc_, GCLineStyle, &gv); + std::string lim = fmt1(threshold_) + "C limit"; + draw_text_color(px + pw - xf::text_width(st, lim) - 4, ty - 4, lim, hot_color_); + } + + // Temperature line: green below the threshold, red above it. + if (temps_.size() >= 2) + { + int n = (int)temps_.size(); + XSetForeground(display_, gc_, col(ok_color_)); + xf::set_line_width(display_, gc_, 2); + for (int i = 1; i < n; ++i) + { + int x0 = px + (int)((double)(i - 1) / (capacity_ - 1) * pw); + int x1 = px + (int)((double)i / (capacity_ - 1) * pw); + XSetForeground(display_, gc_, col(temps_[i] >= threshold_ ? hot_color_ : ok_color_)); + XDrawLine(display_, window_, gc_, x0, y_at(temps_[i - 1]), x1, y_at(temps_[i])); + } + xf::set_line_width(display_, gc_, 1); + } + + // Legend: current (big, coloured by state) + min / max. + double mn = 0.0, mx = 0.0; + if (!temps_.empty()) + { + mn = mx = temps_[0]; + for (double v : temps_) + { + mn = std::min(mn, v); + mx = std::max(mx, v); + } + } + std::string cur = "now " + fmt1(current()) + "C"; + draw_text_color(x2_ - 8 - xf::text_width(st, cur), y1_ + title_h + 14, cur, over_temp() ? hot_color_ : ok_color_); + std::string mm = "min " + fmt1(mn) + "C max " + fmt1(mx) + "C threshold " + fmt1(threshold_) + "C"; + xf::draw_text_at(display_, window_, gc_, st, x1_ + 8, y1_ + title_h + 14, mm); + + XSetForeground(display_, gc_, col(axis_color_)); + XDrawRectangle(display_, window_, gc_, px, py, pw, ph); + XSetForeground(display_, gc_, st.lineColor_); + XDrawRectangle(display_, window_, gc_, x1_, y1_, w, h); + XFlush(display_); + } + + bool on_button_press(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_button_release(int x, int y, unsigned int button) + { + (void)x; + (void)y; + (void)button; + return false; + } + bool on_motion(int x, int y) + { + (void)x; + (void)y; + return false; + } + bool on_key(KeySym key, const char* str) + { + (void)key; + (void)str; + return false; + } +}; diff --git a/widgets/components/XTempHistory/core/xframe_core.h b/widgets/components/XTempHistory/core/xframe_core.h new file mode 100644 index 0000000..098187d --- /dev/null +++ b/widgets/components/XTempHistory/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/XTempHistory/main_XTempHistory.cpp b/widgets/components/XTempHistory/main_XTempHistory.cpp new file mode 100644 index 0000000..57de4c0 --- /dev/null +++ b/widgets/components/XTempHistory/main_XTempHistory.cpp @@ -0,0 +1,69 @@ +#include "XTempHistory.h" + +#include + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) { return 1; } + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 800, 600, 1, BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "XTempHistory - 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"); + XTempHistory widget(display, screen, window, gc, &styles, 20, 20, 720, 480); + 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/screenshots/XCoreGrid.png b/widgets/screenshots/XCoreGrid.png new file mode 100644 index 0000000..2d91667 Binary files /dev/null and b/widgets/screenshots/XCoreGrid.png differ diff --git a/widgets/screenshots/XHistoryGraph.png b/widgets/screenshots/XHistoryGraph.png new file mode 100644 index 0000000..6e42f3d Binary files /dev/null and b/widgets/screenshots/XHistoryGraph.png differ diff --git a/widgets/screenshots/XNetGraph.png b/widgets/screenshots/XNetGraph.png new file mode 100644 index 0000000..e8251c0 Binary files /dev/null and b/widgets/screenshots/XNetGraph.png differ diff --git a/widgets/screenshots/XTempHistory.png b/widgets/screenshots/XTempHistory.png new file mode 100644 index 0000000..f3d553b Binary files /dev/null and b/widgets/screenshots/XTempHistory.png differ