diff --git a/examples/monitor/disk-monitor/Makefile b/examples/monitor/disk-monitor/Makefile new file mode 100644 index 0000000..b8938d8 --- /dev/null +++ b/examples/monitor/disk-monitor/Makefile @@ -0,0 +1,20 @@ +CXX ?= g++ +CXXFLAGS ?= -std=c++17 -O2 -Wall + +ROOT = ../../.. +INC = -I$(ROOT)/widgets/components/XUsageBar \ + -I$(ROOT)/widgets/components/XHistoryGraph \ + -I$(ROOT)/widgets/components/XStackBar + +all: disk-monitor + +disk-monitor: main.cpp + $(CXX) $(CXXFLAGS) $(INC) main.cpp -o disk-monitor -lX11 + +run: disk-monitor + ./disk-monitor + +clean: + rm -f disk-monitor + +.PHONY: all run clean diff --git a/examples/monitor/disk-monitor/README.md b/examples/monitor/disk-monitor/README.md new file mode 100644 index 0000000..1d4d5d1 --- /dev/null +++ b/examples/monitor/disk-monitor/README.md @@ -0,0 +1,47 @@ +# Disk Monitor — C (XFrame) + +A live disk monitor in one 1024x768 window: per-mount usage bars, +a Used / Free stack bar for the largest mount, and a read/write +throughput history graph. All data is live — `/proc/mounts` + +`statvfs` for usage, `/proc/diskstats` (sectors differenced once a +second) for MB/s. Refreshes every second; Esc / `q` / window-close +quits. + +## Widgets used + +| Widget | Role | +| --- | --- | +| XUsageBar | One per disk mount (`/`, …): usage % with total size | +| XStackBar | Largest mount split into Used / Free (GiB) | +| XHistoryGraph | Read MB/s + Write MB/s history, 60 s window | + +**Why no XSysBox:** it has no clear-history API and its +constructor seeds 60 demo samples, so it cannot show live disk data +without the seeded demo leaking into the history. XUsageBar + +XHistoryGraph + XStackBar cover the same ground with live setters +(`set_value`, `push`, `set_segment`/`clear_segments`). + +## Build & run + +```sh +make +./disk-monitor +``` + +Build recipe (same as the widget demo mains): `g++ -std=c++17 +-I/widgets/components/XUsageBar +-I/widgets/components/XHistoryGraph +-I/widgets/components/XStackBar main.cpp -lX11`. + +## Screenshot + +![Disk Monitor (C)](screenshot.png) + +## Source + +- App: `examples/monitor/disk-monitor/main.cpp` +- Repo: https://github.com/cnmcdee/lightgui +- Rust port: `crates/xframe-demo/examples/monitor_disk_monitor/main.rs` + in https://github.com/cnmcdee/lightgui_rust +- Python port: `examples/monitor_disk_monitor/main.py` + in https://github.com/cnmcdee/lightgui_python diff --git a/examples/monitor/disk-monitor/main.cpp b/examples/monitor/disk-monitor/main.cpp new file mode 100644 index 0000000..83216dd --- /dev/null +++ b/examples/monitor/disk-monitor/main.cpp @@ -0,0 +1,303 @@ +// Disk Monitor - monitor (C / XFrame) +// +// One 1024x768 window: a live XUsageBar per disk mount (from +// /proc/mounts + statvfs), an XStackBar splitting the largest mount +// into Used / Free (GiB), and an XHistoryGraph of disk read/write +// throughput in MB/s (from /proc/diskstats, differenced once a second). +// +// Widgets used (all from the LightGUI registry, no raw drawing here +// beyond the demo-main window shell): +// XUsageBar - per-mount usage % +// XStackBar - Used / Free split of the largest mount +// XHistoryGraph - read / write MB/s history (60 s window) +// +// XSysBox is deliberately NOT used: it has no clear-history API and +// its constructor seeds 60 demo samples, so it cannot show live +// disk data without the seeded demo leaking into the history. +// +// Build: make (see Makefile) +// Run: ./disk-monitor (Esc / q / window-close quits) + +#include "XUsageBar.h" +#include "XHistoryGraph.h" +#include "XStackBar.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + +struct Mount +{ + std::string dev; // /dev/sda2 + std::string point; // / + std::string base; // sda (diskstats device backing this mount) + double total_gib = 0; // GiB + double used_gib = 0; // GiB + double free_gib = 0; // GiB + double pct = 0; // 0..100 +}; + +// Strip a partition suffix: sda2 -> sda, nvme0n1p2 -> nvme0n1. +std::string base_device(const std::string& dev) +{ + std::string name = dev; + std::size_t slash = name.rfind('/'); + if (slash != std::string::npos) name = name.substr(slash + 1); + while (!name.empty() && std::isdigit((unsigned char)name.back())) + name.pop_back(); + if (!name.empty() && name.back() == 'p' && name.size() >= 2 && + std::isdigit((unsigned char)name[name.size() - 2])) + name.pop_back(); + return name; +} + +bool real_fs(const std::string& fs) +{ + return fs == "ext4" || fs == "xfs" || fs == "btrfs"; +} + +// Live mounts (real on-disk filesystems, max 4), with statvfs sizes. +std::vector read_mounts() +{ + std::vector mounts; + FILE* f = std::fopen("/proc/mounts", "r"); + if (!f) return mounts; + char dev[256], point[256], fs[64], opts[256]; + int a, b; + while (std::fscanf(f, "%255s %255s %63s %255s %d %d", dev, point, fs, opts, &a, &b) == 6) + { + if (!real_fs(fs)) continue; + bool dup = false; + for (auto& m : mounts) + if (m.point == point) dup = true; + if (dup) continue; + struct statvfs sv; + if (statvfs(point, &sv) != 0) continue; + Mount m; + m.dev = dev; + m.point = point; + m.base = base_device(dev); + double total = (double)sv.f_blocks * (double)sv.f_frsize; + double free = (double)sv.f_bfree * (double)sv.f_frsize; + m.total_gib = total / 1073741824.0; + m.free_gib = free / 1073741824.0; + m.used_gib = m.total_gib - m.free_gib; + m.pct = m.total_gib > 0 ? m.used_gib / m.total_gib * 100.0 : 0.0; + mounts.push_back(m); + if (mounts.size() >= 4) break; + } + std::fclose(f); + return mounts; +} + +// (read_sectors, write_sectors) summed over the backing disks. +bool read_io(const std::vector& mounts, unsigned long long& rd, unsigned long long& wr) +{ + rd = 0; + wr = 0; + FILE* f = std::fopen("/proc/diskstats", "r"); + if (!f) return false; + char line[512]; + bool ok = false; + while (std::fgets(line, sizeof(line), f)) + { + unsigned long long rd_s = 0, wr_s = 0; + char name[64]; + // major minor name reads_completed reads_merged sectors_read ... + // sectors_written is field 10. + unsigned long long f1, f2, f3, f4, f5, f6, f7, f8, f9; + int n = std::sscanf(line, "%llu %llu %63s %llu %llu %llu %llu %llu %llu %llu %llu", + &f1, &f2, name, &f3, &f4, &rd_s, &f5, &f6, &f7, &wr_s, &f8); + (void)f9; + if (n < 10) continue; + for (auto& m : mounts) + { + if (m.base == name) + { + rd += rd_s; + wr += wr_s; + ok = true; + } + } + } + std::fclose(f); + return ok; +} + +std::string fmt_gib(double gib) +{ + char buf[32]; + std::snprintf(buf, sizeof(buf), "%.0f GiB", gib); + return buf; +} + +} // namespace + +int main() +{ + Display* display = XOpenDisplay(nullptr); + if (!display) return 1; + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), 100, 100, 1024, 768, 1, + BlackPixel(display, screen), WhitePixel(display, screen)); + XStoreName(display, window, "Disk Monitor - monitor"); + 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"); + + // Live mount list (fixed at startup; mounts rarely change). + std::vector mounts = read_mounts(); + if (mounts.empty()) + { + Mount root; + root.dev = "?"; + root.point = "/"; + root.base = ""; + mounts.push_back(root); + } + const int n = (int)mounts.size(); + + // Layout: usage bars on top, stack bar, history graph fills the rest. + const int margin = 16; + const int bar_h = 44; + const int bar_gap = 8; + const int stack_h = 170; + const int stack_y = margin + n * (bar_h + bar_gap) + 8; + const int hist_y = stack_y + stack_h + 8; + const int hist_h = 768 - margin - hist_y; + const int col_w = 1024 - 2 * margin; + + std::vector bars; + for (int i = 0; i < n; ++i) + { + bars.emplace_back(display, screen, window, gc, &styles, margin, + margin + i * (bar_h + bar_gap), col_w, bar_h); + bars.back().set_text(mounts[i].point + " " + fmt_gib(mounts[i].total_gib)); + } + + XStackBar stack(display, screen, window, gc, &styles, margin, stack_y, col_w, stack_h); + stack.set_text(mounts[0].point + " disk usage"); + stack.clear_segments(); + stack.add_segment("Used", mounts[0].used_gib, Srgb{0, 150, 60}); + stack.add_segment("Free", mounts[0].free_gib, Srgb{200, 200, 200}); + + XHistoryGraph hist(display, screen, window, gc, &styles, margin, hist_y, col_w, hist_h); + hist.set_text("Disk IO - MB/s (read / write)"); + hist.clear_series(); // drop the constructor's seeded demo series + hist.add_series("Read MB/s", Srgb{0, 170, 70}); + hist.add_series("Write MB/s", Srgb{0, 100, 200}); + + // No XClearWindow here: every widget paints its own white + // background first, so a clear would only blank the window and + // leave import/screenshot tools catching a half-painted frame + // (and XClearWindow itself generates another Expose). + auto redraw = [&]() { + for (auto& b : bars) b.draw(); + stack.draw(); + hist.draw(); + XFlush(display); + }; + + unsigned long long prev_rd = 0, prev_wr = 0; + bool have_prev = read_io(mounts, prev_rd, prev_wr); + auto refresh = [&]() { + std::vector live = read_mounts(); + for (int i = 0; i < n && i < (int)live.size(); ++i) + { + mounts[i].total_gib = live[i].total_gib; + mounts[i].used_gib = live[i].used_gib; + mounts[i].free_gib = live[i].free_gib; + mounts[i].pct = live[i].pct; + bars[i].set_value(mounts[i].pct); + } + stack.clear_segments(); + stack.add_segment("Used", mounts[0].used_gib, Srgb{0, 150, 60}); + stack.add_segment("Free", mounts[0].free_gib, Srgb{200, 200, 200}); + unsigned long long rd = 0, wr = 0; + if (read_io(mounts, rd, wr) && have_prev) + { + // 1 s tick, 512-byte sectors -> MB/s. + hist.push(0, (double)(rd - prev_rd) * 512.0 / 1e6); + hist.push(1, (double)(wr - prev_wr) * 512.0 / 1e6); + } + prev_rd = rd; + prev_wr = wr; + have_prev = true; + }; + + refresh(); + redraw(); + + bool running = true; + auto last_tick = std::chrono::steady_clock::now(); + int fd = ConnectionNumber(display); + while (running) + { + fd_set rfds; + FD_ZERO(&rfds); + FD_SET(fd, &rfds); + struct timeval tv; + tv.tv_sec = 0; + tv.tv_usec = 500000; + int ready = select(fd + 1, &rfds, nullptr, nullptr, &tv); + if (ready > 0) + { + while (XPending(display)) + { + XEvent event; + XNextEvent(display, &event); + switch (event.type) + { + case Expose: + // Only repaint on the last Expose of a series; + // earlier ones are superseded. + if (event.xexpose.count == 0) redraw(); + break; + case KeyPress: + { + char buffer[32]; + KeySym key = 0; + int k = XLookupString(&event.xkey, buffer, (int)sizeof(buffer) - 1, &key, nullptr); + buffer[k] = 0; + if (key == XK_Escape || buffer[0] == 'q') running = false; + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) running = false; + break; + default: + break; + } + } + } + auto now = std::chrono::steady_clock::now(); + if (std::chrono::duration_cast(now - last_tick).count() >= 1) + { + last_tick = now; + refresh(); + redraw(); + } + } + + XCloseDisplay(display); + return 0; +} diff --git a/examples/monitor/disk-monitor/screenshot.png b/examples/monitor/disk-monitor/screenshot.png new file mode 100644 index 0000000..efe2711 Binary files /dev/null and b/examples/monitor/disk-monitor/screenshot.png differ