commit 05b33a9c33210542ad923152b4ef983bcc6b6d1b Author: cnmcdee Date: Sat Dec 5 04:38:49 2026 +0000 Pilot batch: banner, bigfind, emptybig LightGUI apps + repo index and MIT license First 3 of the 5 pilot apps, all built and screenshot-tested on hot_dallas: - banner (Python): text + font combo + scrolling output, 12/12 GUI-vs-CLI - bigfind (C++): top-N largest files table, exact CLI match - emptybig (C++): sparse-file finder, exact CLI match on fixture Top-level README indexes all 50 drawn apps; LICENSE is MIT (util_box itself is unlicensed; MIT matches lzply and lightgui). datecalc and certcheck are blocked pending execution-risk approval. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..72f0516 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +# Built C binaries (rebuild with make in each app dir) +apps/c/bigfind/bigfind +apps/c/emptybig/emptybig diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..f362983 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 cnmcdee + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..25d196e --- /dev/null +++ b/README.md @@ -0,0 +1,126 @@ +# util_boxgui — GUI examples of utilities + +LightGUI recreations of 50 [util_box](https://github.com/cnmcdee/util_box) +command-line utilities. Each app is reimplemented as a GUI with +[LightGUI](https://github.com/cnmcdee/lightgui) widgets in its original +language, with a screenshot of the running GUI and a detailed walkthrough +guide on the matching LightGUI doc subdomain (C → [cdoc.lightgui.com](https://cdoc.lightgui.com), +Python → [pythondoc.lightgui.com](https://pythondoc.lightgui.com), +Rust → [rustdoc.lightgui.com](https://rustdoc.lightgui.com)). + +## Layout + +``` +apps/ + c// — C++ (LightGUI X11 widgets): .cpp + Makefile + python// — Python (PyGObject/Cairo): .py + rust// — Rust (xframe crates), if any +``` + +Each app directory holds its source, `screenshot.png` (a real capture of the +running GUI under Xvfb), and a `README.md` (what it does, how to build/run, +how it maps to the CLI, link to its walkthrough). + +## Status + +Pilot batch of 5: **3 done** (banner, bigfind, emptybig). datecalc and +certcheck are **blocked** — their builders hit an execution-risk check on the +server content and are waiting on a plain-words go-ahead to build/test code +on hot_dallas. The remaining 45 are todo. + +Walkthrough articles are written and published from hot_newyork (where the +Ghost API keys live) after the code lands here — the walkthrough links below +go live in that phase. Split: hot_dallas does all coding (source, build, run, +screenshot); hot_newyork does article writing only. This repo is the handoff. + +## The 50 + +| App | Lang | What it does | Screenshot | Walkthrough | Status | +|---|---|---|---|---|---| +| bigfind | C | Top-N largest files with age, type and parent-dir context | [screenshot](apps/c/bigfind/screenshot.png) | [walkthrough](https://cdoc.lightgui.com/bigfind/) | ✅ Done | +| cpuidle | C | Per-core idle and C-state time monitor | — | — | ⬜ Todo | +| cpusteal | C | Steal time monitor for VMs with history graph | — | — | ⬜ Todo | +| diskrate | C | Per-disk read/write rate bars, live | — | — | ⬜ Todo | +| emptybig | C | Find large files that are mostly zeros (sparse files) | [screenshot](apps/c/emptybig/screenshot.png) | [walkthrough](https://cdoc.lightgui.com/emptybig/) | ✅ Done | +| fatfree | C | Find files larger than X in a tree and suggest moving them | — | — | ⬜ Todo | +| inodehunt | C | Directories consuming the most inodes (many small files) | — | — | ⬜ Todo | +| iolat | C | Per-disk IO latency histogram from /proc/diskstats deltas | — | — | ⬜ Todo | +| loadhist | C | Record load average over time into a log and show a sparkline history | — | — | ⬜ Todo | +| pressure | C | PSI (pressure stall information) reader with a human summary | — | — | ⬜ Todo | +| procstate | C | Process counts by state (R/S/D/Z/T) graphed over time | — | — | ⬜ Todo | +| proctree | C | Process tree with CPU and memory per branch, collapsed by user | — | — | ⬜ Todo | +| runq | C | Run queue length history graph | — | — | ⬜ Todo | +| splitjoin | C | Split a file into N MB chunks and rejoin from a manifest with checksums | — | — | ⬜ Todo | +| suspendwatch | C | Suspend/resume event log monitor | — | — | ⬜ Todo | +| sysdash | C | Combined mini-dashboard: CPU, memory, disk, net, temp | — | — | ⬜ Todo | +| tempdiff | C | Temperature before vs after running a command | — | — | ⬜ Todo | +| watchdog | C | Watch a process and report (and optionally restart) when it dies or exceeds limits | — | — | ⬜ Todo | +| wifigraph | C | WiFi signal strength graph over time | — | — | ⬜ Todo | +| zombiefind | C | Find zombie processes and report their parents | — | — | ⬜ Todo | +| badlines | Python | Find overlong lines, trailing whitespace, and tabs — a lint for text files | — | — | ⬜ Todo | +| banner | Python | ASCII banner text with several built-in fonts (no figlet dependency) | [screenshot](apps/python/banner/screenshot.png) | [walkthrough](https://pythondoc.lightgui.com/banner/) | ✅ Done | +| benchcmd | Python | Benchmark a command's runtime over N runs (average, min, max) | — | — | ⬜ Todo | +| bomfix | Python | Detect, strip, or add a BOM in text files | — | — | ⬜ Todo | +| certcheck | Python | A site's TLS certificate expiry date and issuer | — | — | ⏳ Blocked (execution approval) | +| charset | Python | Detect a file's encoding (UTF-8/16/32, latin-1) with a confidence note | — | — | ⬜ Todo | +| connlog | Python | Log new connections over time (poll /proc/net/tcp) and report new/closed | — | — | ⬜ Todo | +| croncheck | Python | Validate a cron expression and show the next run times | — | — | ⬜ Todo | +| cronlist | Python | List cron jobs with a human-readable explanation of each schedule | — | — | ⬜ Todo | +| datecalc | Python | Date arithmetic: add/subtract days, difference between dates, weekday | — | — | ⏳ Blocked (execution approval) | +| diskalarm | Python | Alert when a mount crosses a usage threshold, with a one-line report | — | — | ⬜ Todo | +| disktemp | Python | Disk temperature from SMART if smartctl is present, else /sys, else a clear message | — | — | ⬜ Todo | +| dustack | Python | Show which subdirectories grew most since the last snapshot (growth tracker, not just du) | — | — | ⬜ Todo | +| exifsort | Python | Sort photos into YYYY/MM folders by EXIF/date, dry-run first | — | — | ⬜ Todo | +| flatpack | Python | Flatten a nested tree into one directory, resolving name clashes with suffixes | — | — | ⬜ Todo | +| gitdiffstat | Python | Diff stats between two refs with a per-file table | — | — | ⬜ Todo | +| hangman | Python | Hangman game in the terminal | — | — | ⬜ Todo | +| latency | Python | Measure latency to several hosts and rank them | — | — | ⬜ Todo | +| lostfound | Python | Digital-hoarding report: files untouched 2+ years and over 100 MB | — | — | ⬜ Todo | +| portfree | Python | Find the first free port in a range | — | — | ⬜ Todo | +| quiz | Python | Tiny quiz game with built-in questions and a score | — | — | ⬜ Todo | +| repocheck | Python | Health check for a git repo: uncommitted, untracked, ahead/behind, large files | — | — | ⬜ Todo | +| scriptcheck | Python | Syntax-check all shell scripts in a directory (bash -n) and report | — | — | ⬜ Todo | +| snapdiff | Python | Compare two disk-usage snapshots and show what grew | — | — | ⬜ Todo | +| sortbyage | Python | Move files into folders by age buckets (today / this week / this month / older) | — | — | ⬜ Todo | +| stopwatch | Python | Terminal stopwatch with laps | — | — | ⬜ Todo | +| tailfollow | Python | Follow a file and show only lines matching a pattern, with running counts | — | — | ⬜ Todo | +| typing | Python | Typing speed test in the terminal | — | — | ⬜ Todo | +| wifisignal | Python | Wi-Fi signal strength from /proc/net/wireless or iw, with fallback | — | — | ⬜ Todo | +| workdays | Python | Count working days between two dates (weekends excluded) | — | — | ⬜ Todo | + +The 50 were drawn with a seeded random sample (seed 20261204, stratified +20 C + 30 Python) from util_box's 310 utilities, excluding the 25 `tx*` +Termux bash wrappers (no LightGUI binding). + +## Building and running + +**C++ apps** (needs the LightGUI checkout for widget headers): + +```sh +cd apps/c/bigfind +make # g++ -std=c++17 -I/widgets/components -I/widgets .cpp -lX11 -o +DISPLAY=:98 ./bigfind +``` + +**Python apps** (needs the LightGUI Python checkout on `PYTHONPATH`): + +```sh +cd apps/python/banner +PYTHONPATH= python3 banner.py +``` + +Run under Xvfb for headless screenshots (see each app's README for its +display number and window title). + +## Links + +- Original CLI utilities: https://github.com/cnmcdee/util_box +- LightGUI (C++): https://github.com/cnmcdee/lightgui +- LightGUI (Rust): https://github.com/cnmcdee/lightgui_rust +- LightGUI (Python): https://github.com/cnmcdee/lightgui_python +- Docs: https://cdoc.lightgui.com · https://rustdoc.lightgui.com · https://pythondoc.lightgui.com + +## License + +MIT — see [LICENSE](LICENSE). (util_box itself carries no license file; +MIT matches the author's other public repos, lzply and lightgui.) diff --git a/apps/c/bigfind/Makefile b/apps/c/bigfind/Makefile new file mode 100644 index 0000000..31c1d99 --- /dev/null +++ b/apps/c/bigfind/Makefile @@ -0,0 +1,12 @@ +# bigfind - util_boxgui (C++ / LightGUI) +CXX = g++ +CXXFLAGS = -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets -O2 -Wall +LDFLAGS = -lX11 + +bigfind: bigfind.cpp + $(CXX) $(CXXFLAGS) bigfind.cpp $(LDFLAGS) -o bigfind + +clean: + rm -f bigfind + +.PHONY: clean diff --git a/apps/c/bigfind/README.md b/apps/c/bigfind/README.md new file mode 100644 index 0000000..36a0f79 --- /dev/null +++ b/apps/c/bigfind/README.md @@ -0,0 +1,91 @@ +# bigfind — util_boxgui (C++ / LightGUI) + +A LightGUI front-end for the `bigfind` CLI utility from +[util_box](https://github.com/cnmcdee/util_box) (`src/bigfind.c`): find the +top-N largest files in a directory tree, with age, type and parent-directory +context for each hit. + +Walkthrough: https://cdoc.lightgui.com/bigfind/ + +## What it does + +Type (or keep) a directory path, pick how many hits to show with the **Top N** +spinbox, and press **Run**. The table lists the N largest files in the tree, +largest first, with five columns: + +| Column | Meaning | +|------------|---------| +| Size | Human-readable size (`202.8 KiB`, `23.7 MiB` — same format as the CLI) | +| Age | Time since last modification (`23h`, `1d`, `2mo`, `3y` — same format as the CLI) | +| Type | Lowercased file extension, `(none)` when there is none | +| File | File name | +| Parent dir | Directory the file lives in | + +The status line under the table mirrors the CLI summary, e.g. +`top 10 of 1824 files; tree total 23.7 MiB`. + +On launch the app is already in a meaningful state: it scans +`/root/fileutils` with N=10, so the table is populated immediately. + +## Build + +```sh +make +``` + +One g++ line (see `Makefile`): + +```sh +g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets -O2 -Wall bigfind.cpp -lX11 -o bigfind +``` + +Builds clean with no warnings. Needs `g++`, `libx11-dev` and the LightGUI +checkout at `/root/lg-review/lightgui` (header-only widgets on raw X11). + +## Run + +Under a real X server, or under Xvfb: + +```sh +Xvfb :98 -screen 0 1024x768x24 & +DISPLAY=:98 ./bigfind +``` + +Close the window to quit. Changing the path (Enter) or the Top N value +re-runs the scan; the **Run** button re-scans the current path and N. + +## How it maps to the CLI + +The scan logic in `bigfind.cpp` is a direct port of `util_box`'s +`src/bigfind.c` (`bigfind [dir] [-n N]`): + +- **Traversal:** one recursive walk (`opendir`/`readdir`), following the same + rules — directories are recursed into, regular files are considered, + everything else (symlinks, sockets, devices) is skipped, unreadable + directories are silently skipped. +- **Top-N:** only the N largest files are kept (bounded memory); a file only + displaces the current smallest when it is strictly larger — same rule as + the CLI's heap. +- **Sort:** largest first by byte size. +- **Formatting:** `human()` (`%.1f` + B/KiB/MiB/GiB/TiB) and `age_str()` + (`59s`, `12m`, `23h`, `6d`, `3mo`, `2y`) are copied verbatim, and `ext_of` + reproduces the CLI's quirk of taking the last `.` in the *whole path*, + lowercased and capped at 31 characters — so extensionless files under + dotted directories (e.g. `.git/objects/…`) report odd "types" exactly as + the CLI does. +- **Differences:** the GUI has no `--min-size` or `--json` options (the table + shows the same columns the CLI prints); the CLI's two-line hit layout + (`PATH` + `in `) is split into the File and Parent dir columns. + +Verified against the CLI on the same inputs (`/root/fileutils`, N=10): the +GUI's table matches `/root/fileutils/bin/bigfind /root/fileutils -n 10` +exactly — same 10 files, same sizes, same order, same totals +(1824 files, 23.7 MiB). The app also echoes each scan to stdout in CLI +form, so the comparison can be re-run by diffing its output against the CLI. + +## Files + +- `bigfind.cpp` — the app (scan logic + LightGUI widgets) +- `Makefile` — the build +- `screenshot.png` — real Xvfb capture of the running GUI (default state) +- `README.md` — this file diff --git a/apps/c/bigfind/bigfind.cpp b/apps/c/bigfind/bigfind.cpp new file mode 100644 index 0000000..6142b69 --- /dev/null +++ b/apps/c/bigfind/bigfind.cpp @@ -0,0 +1,340 @@ +// bigfind - util_boxgui: top-N largest files with age, type and parent-dir context. +// LightGUI (C++) front-end for the `bigfind` CLI utility from util_box +// (https://github.com/cnmcdee/util_box, src/bigfind.c). +// +// The scan logic below is a direct port of the CLI: one recursive walk, +// only the N largest files are kept (bounded memory), sorted largest-first, +// with the CLI's size/age/type formatting reproduced exactly -- including +// its quirks (ext_of runs strrchr over the whole path, so extensionless +// files under dotted directories report odd "types"). +// +// Build: make (see Makefile) +// Run: ./bigfind (under Xvfb or a real X server) +// Window title: "bigfind - util_boxgui" +#include "GtkEntry/GtkEntry.h" +#include "GtkSpinButton/GtkSpinButton.h" +#include "GtkButton/GtkButton.h" +#include "GtkLabel/GtkLabel.h" +#include "TListView/TListView.h" + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +// --------------------------------------------------------------------------- +// Scan logic (ported from util_box src/bigfind.c) +// --------------------------------------------------------------------------- +struct Entry { + std::string path; + off_t size; + time_t mtime; +}; + +static std::vector g_top; +static size_t g_cap = 10; +static long long g_total_bytes = 0; +static long g_total_files = 0; + +static void consider(const std::string &p, off_t s, time_t m) { + g_total_bytes += s; + g_total_files++; + if (g_top.size() < g_cap) { + g_top.push_back({p, s, m}); + return; + } + size_t mn = 0; + for (size_t i = 1; i < g_top.size(); i++) + if (g_top[i].size < g_top[mn].size) mn = i; + if (s > g_top[mn].size) g_top[mn] = {p, s, m}; +} + +static void walk(const std::string &dir) { + DIR *d = opendir(dir.c_str()); + if (!d) return; + struct dirent *e; + while ((e = readdir(d))) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + std::string full = dir + "/" + e->d_name; + struct stat st; + if (lstat(full.c_str(), &st)) continue; + if (S_ISDIR(st.st_mode)) + walk(full); + else if (S_ISREG(st.st_mode)) + consider(full, st.st_size, st.st_mtime); + } + closedir(d); +} + +static std::string human(off_t b) { + static const char *u[] = {"B", "KiB", "MiB", "GiB", "TiB"}; + double v = (double)b; + int i = 0; + while (v >= 1024 && i < 4) { + v /= 1024; + i++; + } + char buf[32]; + snprintf(buf, sizeof buf, "%.1f %s", v, u[i]); + return buf; +} + +static std::string age_str(time_t m) { + time_t now = time(NULL); + long s = (long)(now - m); + if (s < 0) s = 0; + char buf[32]; + if (s < 60) + snprintf(buf, sizeof buf, "%lds", s); + else if (s < 3600) + snprintf(buf, sizeof buf, "%ldm", s / 60); + else if (s < 86400) + snprintf(buf, sizeof buf, "%ldh", s / 3600); + else if (s < 86400 * 30) + snprintf(buf, sizeof buf, "%ldd", s / 86400); + else if (s < 86400 * 365) + snprintf(buf, sizeof buf, "%ldmo", s / (86400 * 30)); + else + snprintf(buf, sizeof buf, "%ldy", s / (86400 * 365)); + return buf; +} + +// Same as the CLI: last '.' in the whole path, lowercased, capped at 31 chars. +static std::string ext_of(const std::string &p) { + const char *d = strrchr(p.c_str(), '.'); + if (!d || d == p.c_str()) return "(none)"; + std::string b; + for (const char *q = d + 1; *q && b.size() < 31; q++) + b += (char)tolower((unsigned char)*q); + return b; +} + +static std::string parent_of(const std::string &p) { + size_t s = p.rfind('/'); + if (s == std::string::npos) return "."; + if (s == 0) return "/"; + return p.substr(0, s); +} + +static std::string base_of(const std::string &p) { + size_t s = p.rfind('/'); + if (s == std::string::npos) return p; + return p.substr(s + 1); +} + +// --------------------------------------------------------------------------- +// GUI +// --------------------------------------------------------------------------- +static Display *g_display = nullptr; +static Window g_window; +static GC g_gc; +static SStyle_Manager *g_styles = nullptr; + +static GtkEntry *g_path_entry = nullptr; +static GtkSpinButton *g_n_spin = nullptr; +static GtkButton *g_run_button = nullptr; +static GtkLabel *g_status_label = nullptr; +static GtkLabel *g_dir_label = nullptr; +static GtkLabel *g_n_label = nullptr; +static TListView *g_table = nullptr; +static bool g_ready = false; // callbacks live only after the initial scan + +static void draw_all() { + XClearWindow(g_display, g_window); + g_dir_label->draw(); + g_n_label->draw(); + g_path_entry->draw(); + g_n_spin->draw(); + g_run_button->draw(); + g_table->draw(); + g_status_label->draw(); + XFlush(g_display); +} + +static void run_scan() { + std::string dir = g_path_entry->get_text(); + if (dir.empty()) dir = "."; + int n = g_n_spin->get_value_as_int(); + if (n < 1) n = 1; + g_cap = (size_t)n; + g_top.clear(); + g_total_bytes = 0; + g_total_files = 0; + walk(dir); + std::sort(g_top.begin(), g_top.end(), + [](const Entry &a, const Entry &b) { return a.size > b.size; }); + + g_table->clear_items(); + for (const auto &e : g_top) { + g_table->add_item({human(e.size), age_str(e.mtime), ext_of(e.path), + base_of(e.path), parent_of(e.path)}); + } + char status[256]; + snprintf(status, sizeof status, "top %zu of %ld files; tree total %s", + g_top.size(), g_total_files, human(g_total_bytes).c_str()); + g_status_label->set_text(status); + + // Echo the scan to stdout in CLI form so the GUI table can be diffed + // against `bigfind -n `. + printf("SCAN %s N=%d\n", dir.c_str(), n); + for (const auto &e : g_top) + printf("%-10s %-6s %-10s %s\n", human(e.size).c_str(), + age_str(e.mtime).c_str(), ext_of(e.path).c_str(), + e.path.c_str()); + printf("%s\n", status); + fflush(stdout); +} + +int main() { + g_display = XOpenDisplay(nullptr); + if (!g_display) { + fprintf(stderr, "bigfind: cannot open display\n"); + return 1; + } + int screen = DefaultScreen(g_display); + g_window = XCreateSimpleWindow(g_display, RootWindow(g_display, screen), + 20, 20, 960, 680, 1, + BlackPixel(g_display, screen), + WhitePixel(g_display, screen)); + XStoreName(g_display, g_window, "bigfind - util_boxgui"); + XSelectInput(g_display, g_window, + ExposureMask | KeyPressMask | StructureNotifyMask | + ButtonPressMask | ButtonReleaseMask | PointerMotionMask); + Atom deleteWindowMessage = + XInternAtom(g_display, "WM_DELETE_WINDOW", False); + XSetWMProtocols(g_display, g_window, &deleteWindowMessage, 1); + XMapWindow(g_display, g_window); + g_gc = DefaultGC(g_display, screen); + SStyle_Manager styles(g_display, g_window, screen, g_gc); + g_styles = &styles; + 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"); + + g_dir_label = new GtkLabel(g_display, screen, g_window, g_gc, g_styles, + 20, 14, 85, 26); + g_dir_label->set_text("Directory:"); + g_path_entry = new GtkEntry(g_display, screen, g_window, g_gc, g_styles, + 110, 10, 540, 32); + g_path_entry->set_text("/root/fileutils"); + g_n_label = new GtkLabel(g_display, screen, g_window, g_gc, g_styles, + 665, 14, 55, 26); + g_n_label->set_text("Top N:"); + g_n_spin = new GtkSpinButton(g_display, screen, g_window, g_gc, g_styles, + 725, 10, 85, 32); + g_n_spin->set_range(1, 100); + g_n_spin->set_digits(0); + g_n_spin->set_value(10); + g_run_button = new GtkButton(g_display, screen, g_window, g_gc, g_styles, + 825, 10, 95, 32); + g_run_button->set_text("Run"); + g_table = new TListView(g_display, screen, g_window, g_gc, g_styles, + 20, 56, 920, 540); + g_table->set_columns({}); + g_table->add_column("Size", 95); + g_table->add_column("Age", 60); + g_table->add_column("Type", 90); + g_table->add_column("File", 300); + g_table->add_column("Parent dir", 375); + g_status_label = new GtkLabel(g_display, screen, g_window, g_gc, g_styles, + 20, 612, 920, 28); + g_status_label->set_text(""); + + // Initial scan so the window opens with a populated table (the default + // state: /root/fileutils, N=10). + run_scan(); + g_ready = true; + + g_run_button->on_click = [] { + run_scan(); + draw_all(); + }; + g_path_entry->on_activate = [] { + run_scan(); + draw_all(); + }; + g_n_spin->on_value_changed = [](double) { + if (g_ready) { + run_scan(); + draw_all(); + } + }; + + draw_all(); + + bool running = true; + while (running) { + XEvent event; + XNextEvent(g_display, &event); + bool handled = false; + switch (event.type) { + case Expose: + handled = true; + break; + case ButtonPress: + handled = + g_path_entry->on_button_press(event.xbutton.x, + event.xbutton.y, + event.xbutton.button) || + g_n_spin->on_button_press(event.xbutton.x, event.xbutton.y, + event.xbutton.button) || + g_run_button->on_button_press(event.xbutton.x, + event.xbutton.y, + event.xbutton.button) || + g_table->on_button_press(event.xbutton.x, event.xbutton.y, + event.xbutton.button); + break; + case ButtonRelease: + handled = + g_run_button->on_button_release(event.xbutton.x, + event.xbutton.y, + event.xbutton.button) || + g_n_spin->on_button_release(event.xbutton.x, event.xbutton.y, + event.xbutton.button) || + g_path_entry->on_button_release(event.xbutton.x, + event.xbutton.y, + event.xbutton.button) || + g_table->on_button_release(event.xbutton.x, event.xbutton.y, + event.xbutton.button); + break; + case MotionNotify: + handled = + g_path_entry->on_motion(event.xmotion.x, event.xmotion.y) || + g_n_spin->on_motion(event.xmotion.x, event.xmotion.y) || + g_run_button->on_motion(event.xmotion.x, event.xmotion.y) || + g_table->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 = g_path_entry->on_key(key, buffer) || + g_n_spin->on_key(key, buffer) || + g_table->on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) + running = false; + break; + } + if (handled) draw_all(); + } + XCloseDisplay(g_display); + return 0; +} diff --git a/apps/c/bigfind/screenshot.png b/apps/c/bigfind/screenshot.png new file mode 100644 index 0000000..ea4c5a8 Binary files /dev/null and b/apps/c/bigfind/screenshot.png differ diff --git a/apps/c/emptybig/Makefile b/apps/c/emptybig/Makefile new file mode 100644 index 0000000..90e0c6f --- /dev/null +++ b/apps/c/emptybig/Makefile @@ -0,0 +1,17 @@ +# emptybig - LightGUI front end for the util_box emptybig utility. +# Build: make +# Run: ./emptybig (under Xvfb or a real X server) +CXX = g++ +CXXFLAGS = -std=c++17 -Wall -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets +LDFLAGS = -lX11 +TARGET = emptybig + +all: $(TARGET) + +$(TARGET): emptybig.cpp + $(CXX) $(CXXFLAGS) emptybig.cpp $(LDFLAGS) -o $(TARGET) + +clean: + rm -f $(TARGET) + +.PHONY: all clean diff --git a/apps/c/emptybig/README.md b/apps/c/emptybig/README.md new file mode 100644 index 0000000..505d29a --- /dev/null +++ b/apps/c/emptybig/README.md @@ -0,0 +1,102 @@ +# emptybig — util_boxgui (C++ / LightGUI) + +LightGUI front end for the `emptybig` utility from util_box. It finds large +files that are mostly zeros — sparse files and zero-filled files — under a +directory tree, and shows them in a table sorted by size, largest first. + +A file flagged here is a candidate for truncation, punching holes with +`fallocate -d`, or deletion: it reserves far more space than it holds. + +## What it does + +- **Path** — the directory tree to scan (scanned recursively). +- **Min size** — only files at least this large are considered (default `1M`; + accepts `K`, `M`, `G` suffixes, same as the CLI). +- **Min zero %** — a non-sparse file is flagged when at least this percent of + its sampled bytes are zero (default `50`). +- **Scan** — re-runs the scan with the current path and thresholds. +- The table shows the same columns as the CLI: **SIZE**, **ON DISK**, + **ZERO%**, **FILE**, plus a summary line with the file count and the + apparent waste (size minus on-disk bytes, summed over all hits). + +The scan runs once on launch, so the table is populated immediately. + +## How it maps to the CLI + +The detection logic is a direct port of `/root/fileutils/src/emptybig.c` +(util_box, HEAD 46e027c), same scan, same tests, same output values: + +- Only regular files are considered; symlinks are skipped; directories are + walked recursively. +- A file is **sparse** when its on-disk blocks use less than half its size + (`st_blocks * 512 * 2 < st_size`); sparse files are flagged with ZERO% 100. +- Otherwise up to 16 blocks of 64 KiB spread across the file are sampled, + and the file is flagged when the zero fraction is at least the min-zero + threshold. +- Results are sorted by size, largest first, and sizes use the same human + formatting as the CLI (`5.0M`, `2.0M`, `0B`). +- CLI flags: `[PATH]` maps to the Path field, `--min-size SIZE` to Min size, + `--min-zero PCT` to Min zero %. + +## Build + +```sh +make +``` + +One g++ line (see `Makefile`): + +```sh +g++ -std=c++17 -I/root/lg-review/lightgui/widgets/components -I/root/lg-review/lightgui/widgets emptybig.cpp -lX11 -o emptybig +``` + +Requires g++, libx11-dev, and the LightGUI checkout at +`/root/lg-review/lightgui` (widgets are header-only C++ on raw X11). + +## Run + +Under Xvfb (display :101 is the one used for this app): + +```sh +Xvfb :101 -screen 0 1024x768x24 & +DISPLAY=:101 ./emptybig +``` + +Or on a real X server, just `./emptybig`. + +## Default state and test fixture + +The app starts with Path `/tmp/emptybig-test`, Min size `1M`, Min zero `50%`, +and scans on launch. No directory on hot_dallas with real matches was found +(a scan of `/root` found 0 files), so the default points at a test fixture +with known sparse files. Recreate it with: + +```sh +mkdir -p /tmp/emptybig-test +truncate -s 5M /tmp/emptybig-test/sparse.bin +dd if=/dev/zero of=/tmp/emptybig-test/zeros.bin bs=64K count=32 +dd if=/dev/urandom of=/tmp/emptybig-test/dense.bin bs=64K count=32 +``` + +`sparse.bin` (5 MB, nothing written) and `zeros.bin` (2 MB of zeros) are +flagged; `dense.bin` (2 MB of random bytes) is correctly ignored. The CLI +agrees exactly on this fixture: + +```text +large mostly-empty files in /tmp/emptybig-test (min size 1.0M, min zero 50%): + SIZE ON DISK ZERO% FILE + 5.0M 0B 100% /tmp/emptybig-test/sparse.bin + 2.0M 2.0M 100% /tmp/emptybig-test/zeros.bin +2 file(s); apparent waste vs on-disk: 5.0M +``` + +## Walkthrough + +Planned walkthrough article: https://cdoc.lightgui.com/emptybig/ + +## Notes + +- The LightGUI `GtkEntry` widget does not implement Ctrl+A select-all, so + clear the Path field with End + Backspace before typing a new path. +- The result grid shows at most 200 rows; the summary line always reports + the full hit count. diff --git a/apps/c/emptybig/emptybig.cpp b/apps/c/emptybig/emptybig.cpp new file mode 100644 index 0000000..30bcfda --- /dev/null +++ b/apps/c/emptybig/emptybig.cpp @@ -0,0 +1,295 @@ +// emptybig - LightGUI front end for the util_box emptybig utility. +// Finds large files that are mostly zeros (sparse / zero-filled files) +// under a path, using the same detection logic as the CLI: +// * only regular files at least --min-size (default 1M) are considered +// * a file is "sparse" when its on-disk blocks use less than half its size +// * otherwise up to 16 64 KiB blocks spread across the file are sampled +// and the file is flagged when the zero fraction is >= --min-zero % +// Results are sorted by size, largest first, with SIZE / ON DISK / ZERO% +// columns identical to the CLI output. +// Build: make (see Makefile) +// Run: ./emptybig (under Xvfb or a real X server) +#define _POSIX_C_SOURCE 200809L +#define _DEFAULT_SOURCE +#include "GtkButton/GtkButton.h" +#include "GtkEntry/GtkEntry.h" +#include "GtkLabel/GtkLabel.h" +#include "GtkSpinButton/GtkSpinButton.h" +#include "TStringGrid/TStringGrid.h" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +namespace { + +// ---- CLI logic, ported 1:1 from /root/fileutils/src/emptybig.c ---- +long long g_minsize = 1024 * 1024; +int g_minzero = 50; /* percent */ + +void human(long long b, char* out, size_t n) { + const char* u[] = {"B", "K", "M", "G", "T"}; + double v = (double)b; + int i = 0; + while (v >= 1024 && i < 4) { v /= 1024; i++; } + if (i == 0) snprintf(out, n, "%lldB", b); + else snprintf(out, n, "%.1f%s", v, u[i]); +} + +/* sample up to 16 blocks spread across the file; return zero fraction 0..100, or -1 */ +int zero_fraction(const char* path, long long size) { + int fd = open(path, O_RDONLY); + if (fd < 0) return -1; + static char buf[65536]; + int nblocks = size < 16LL * 65536 ? (int)(size / 65536) + 1 : 16; + if (nblocks < 1) nblocks = 1; + long long zeros = 0, sampled = 0; + for (int i = 0; i < nblocks; i++) { + off_t off; + if (nblocks == 1) off = 0; + else off = (off_t)((long long)i * (size - 65536) / (nblocks - 1)); + if (off < 0) off = 0; + if (lseek(fd, off, SEEK_SET) < 0) continue; + ssize_t r = read(fd, buf, sizeof buf); + if (r <= 0) continue; + for (ssize_t k = 0; k < r; k++) if (buf[k] == 0) zeros++; + sampled += r; + } + close(fd); + if (!sampled) return -1; + return (int)(zeros * 100 / sampled); +} + +struct Hit { + std::string path; + long long size; + long long blocks_bytes; + int zero; +}; +std::vector g_hits; + +void walk(const char* path) { + DIR* d = opendir(path); + if (!d) return; + struct dirent* e; + while ((e = readdir(d))) { + if (!strcmp(e->d_name, ".") || !strcmp(e->d_name, "..")) continue; + char full[PATH_MAX]; + snprintf(full, sizeof full, "%s/%s", path, e->d_name); + struct stat st; + if (lstat(full, &st)) continue; + if (S_ISLNK(st.st_mode)) continue; + if (S_ISREG(st.st_mode)) { + if (st.st_size < g_minsize) continue; + long long disk = (long long)st.st_blocks * 512; + int sparse = st.st_size > 0 && disk * 2 < st.st_size; /* uses < half its size on disk */ + int z = -1; + if (!sparse) z = zero_fraction(full, st.st_size); + if (sparse || z >= g_minzero) + g_hits.push_back({full, st.st_size, disk, sparse ? 100 : z}); + } else if (S_ISDIR(st.st_mode)) { + walk(full); + } + } + closedir(d); +} + +long long parse_size(const char* s) { + char* e; + long long v = strtoll(s, &e, 10); + if (*e == 75 || *e == 107) v *= 1024LL; + else if (*e == 77 || *e == 109) v *= 1024LL * 1024; + else if (*e == 71 || *e == 103) v *= 1024LL * 1024 * 1024; + return v; +} + +void run_scan(const std::string& path) { + g_hits.clear(); + walk(path.c_str()); + std::sort(g_hits.begin(), g_hits.end(), + [](const Hit& a, const Hit& b) { return a.size > b.size; }); +} + +long long total_waste() { + long long w = 0; + for (const auto& h : g_hits) w += h.size - h.blocks_bytes; + return w; +} + +} // namespace + +int main() { + Display* display = XOpenDisplay(nullptr); + if (!display) return 1; + int screen = DefaultScreen(display); + Window window = XCreateSimpleWindow(display, RootWindow(display, screen), + 100, 100, 900, 640, 1, + BlackPixel(display, screen), + WhitePixel(display, screen)); + XStoreName(display, window, "emptybig - util_boxgui"); + 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"); + + GtkLabel lblPath(display, screen, window, gc, &styles, 16, 18, 40, 20); + lblPath.set_text("Path:"); + GtkEntry entPath(display, screen, window, gc, &styles, 60, 12, 420, 30); + entPath.set_text("/tmp/emptybig-test"); + GtkLabel lblMinSize(display, screen, window, gc, &styles, 496, 18, 70, 20); + lblMinSize.set_text("Min size:"); + GtkEntry entMinSize(display, screen, window, gc, &styles, 570, 12, 70, 30); + entMinSize.set_text("1M"); + GtkLabel lblMinZero(display, screen, window, gc, &styles, 656, 18, 80, 20); + lblMinZero.set_text("Min zero %:"); + GtkSpinButton spinZero(display, screen, window, gc, &styles, 740, 12, 70, 30); + spinZero.set_range(0, 100); + spinZero.set_increments(1, 10); + spinZero.set_digits(0); + spinZero.set_value(50); + GtkButton btnScan(display, screen, window, gc, &styles, 824, 12, 60, 30); + btnScan.set_text("Scan"); + GtkLabel lblStatus(display, screen, window, gc, &styles, 16, 52, 868, 20); + TStringGrid grid(display, screen, window, gc, &styles, 16, 80, 868, 520); + grid.set_col_count(4); + grid.set_col_width(0, 90); + grid.set_col_width(1, 90); + grid.set_col_width(2, 70); + grid.set_col_width(3, 618); + grid.set_fixed_rows(1); + GtkLabel lblSummary(display, screen, window, gc, &styles, 16, 610, 868, 20); + + auto refresh = [&]() { + std::string path = entPath.get_text(); + if (path.empty()) path = "."; + g_minsize = parse_size(entMinSize.get_text().c_str()); + if (g_minsize < 0) g_minsize = 0; + g_minzero = spinZero.get_value_as_int(); + run_scan(path); + char hb[32]; + human(g_minsize, hb, sizeof hb); + char status[1024]; + snprintf(status, sizeof status, + "large mostly-empty files in %s (min size %s, min zero %d%%):", + path.c_str(), hb, g_minzero); + lblStatus.set_text(status); + const size_t shown = std::min(g_hits.size(), 200); + grid.set_row_count((int)shown + 1); + grid.set_cell(0, 0, "SIZE"); + grid.set_cell(1, 0, "ON DISK"); + grid.set_cell(2, 0, "ZERO%"); + grid.set_cell(3, 0, "FILE"); + for (size_t i = 0; i < shown; i++) { + char sb[32], db[32], zb[16]; + human(g_hits[i].size, sb, sizeof sb); + human(g_hits[i].blocks_bytes, db, sizeof db); + snprintf(zb, sizeof zb, "%d%%", g_hits[i].zero); + grid.set_cell(0, (int)i + 1, sb); + grid.set_cell(1, (int)i + 1, db); + grid.set_cell(2, (int)i + 1, zb); + grid.set_cell(3, (int)i + 1, g_hits[i].path); + } + char rb[32]; + human(total_waste(), rb, sizeof rb); + char summary[256]; + snprintf(summary, sizeof summary, + "%zu file(s); apparent waste vs on-disk: %s", + g_hits.size(), rb); + lblSummary.set_text(summary); + }; + + btnScan.on_click = [&]() { refresh(); }; + + refresh(); // scan on launch so the table is populated immediately + + auto draw_all = [&]() { + lblPath.draw(); + entPath.draw(); + lblMinSize.draw(); + entMinSize.draw(); + lblMinZero.draw(); + spinZero.draw(); + btnScan.draw(); + lblStatus.draw(); + grid.draw(); + lblSummary.draw(); + }; + draw_all(); + XFlush(display); + + bool running = true; + while (running) { + XEvent event; + XNextEvent(display, &event); + bool handled = false; + switch (event.type) { + case Expose: + handled = true; + break; + case ButtonPress: + handled |= entPath.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= entMinSize.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= spinZero.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= btnScan.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= grid.on_button_press(event.xbutton.x, event.xbutton.y, event.xbutton.button); + break; + case ButtonRelease: + handled |= entPath.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= entMinSize.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= spinZero.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= btnScan.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); + handled |= grid.on_button_release(event.xbutton.x, event.xbutton.y, event.xbutton.button); + break; + case MotionNotify: + handled |= entPath.on_motion(event.xmotion.x, event.xmotion.y); + handled |= entMinSize.on_motion(event.xmotion.x, event.xmotion.y); + handled |= spinZero.on_motion(event.xmotion.x, event.xmotion.y); + handled |= btnScan.on_motion(event.xmotion.x, event.xmotion.y); + handled |= grid.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 |= entPath.on_key(key, buffer); + handled |= entMinSize.on_key(key, buffer); + handled |= spinZero.on_key(key, buffer); + handled |= btnScan.on_key(key, buffer); + handled |= grid.on_key(key, buffer); + break; + } + case ClientMessage: + if ((Atom)event.xclient.data.l[0] == deleteWindowMessage) + running = false; + break; + } + if (handled) { + XClearWindow(display, window); + draw_all(); + XFlush(display); + } + } + XCloseDisplay(display); + return 0; +} diff --git a/apps/c/emptybig/screenshot.png b/apps/c/emptybig/screenshot.png new file mode 100644 index 0000000..0fd8937 Binary files /dev/null and b/apps/c/emptybig/screenshot.png differ diff --git a/apps/python/banner/README.md b/apps/python/banner/README.md new file mode 100644 index 0000000..15cd3c9 --- /dev/null +++ b/apps/python/banner/README.md @@ -0,0 +1,91 @@ +# banner — util_boxgui + +A LightGUI (Python/XFrame) port of the util_box `banner` CLI utility: +type text, pick a font, and the ASCII banner renders live in the +scrolling output area below. + +![banner window](screenshot.png) + +## What it does + +- **Text entry** (top left): the text to render. Pre-filled with + `Hello` on launch. +- **Font combo** (top right): the four built-in fonts — `standard`, + `small`, `big`, `slant`. `standard` is selected on launch. Click + the combo to cycle to the next font. +- **Output area** (below, fills the window): the rendered banner in + a monospace font, with scroll bars. The banner for `Hello` in + `standard` is already rendered when the app starts, so a plain + launch + screenshot is representative. + +Interaction: click the text entry to focus it (blue outline), then +type — BackSpace deletes. Changing the text or the font re-renders +the banner immediately. + +## How to run + +On hot_dallas (104.225.223.162), from this directory: + +```sh +PYTHONPATH=/root/lg-review/lightgui_python python3 banner.py +``` + +Requires python3-gi / gir1.2-gtk-3.0 and the LightGUI Python checkout +at `/root/lg-review/lightgui_python` on `PYTHONPATH`. Under Xvfb: + +```sh +Xvfb :100 -screen 0 1024x768x24 & +DISPLAY=:100 PYTHONPATH=/root/lg-review/lightgui_python python3 banner.py +``` + +The window title is `banner - util_boxgui`. + +## How it maps to the CLI + +The original is `/root/fileutils/bin/banner` (util_box): + +```sh +banner [-f FONT] TEXT... | banner --list-fonts +``` + +- **Same fonts.** The combo lists exactly the CLI's four fonts: + `standard`, `small`, `big`, `slant` (`--list-fonts` output). +- **Same rendering.** The font table (`FONT`), the unknown-character + glyph (`UNKNOWN`), and `render()` are vendored verbatim from the + CLI script into `banner.py`, so the GUI output is byte-identical + to the CLI output for the same text and font — verified against + the CLI on 12 cases (all four fonts, mixed case, digits, + punctuation, spaces, unknown characters such as `@`, which the + CLI renders with the `UNKNOWN` block glyph). Lowercase input is + upper-cased, exactly as the CLI does. +- **Same edge cases.** Empty text: the CLI errors out + (`give text to render`); the GUI instead shows an empty output + area (the CLI's rendering of `""` is five blank lines — the GUI + shows the same blank result without the blank lines). Characters + with no glyph (e.g. `@`) render as the CLI's block glyph. +- **Font effects, as in the CLI:** `small` keeps the top, middle + and bottom rows; `big` doubles every character horizontally and + vertically (10 rows); `slant` indents each successive row one + space further right. + +One deliberate difference: the CLI prints to stdout; the GUI shows +the banner in the output area and never writes to stdout. + +## Known limitations + +- LightGUI draws its widgets with Cairo on a single `Gtk.DrawingArea` + — there is no native GTK keyboard focus or combo drop-down. This app + wires focus and typing itself (click the entry, then type) and the + font combo cycles through the four fonts on click instead of + opening a drop-down list. +- The output area does not really scroll: LightGUI's text-view scroll + bars are drawn, not functional. A very wide banner (long text in the + `big` font) is clipped at the right edge with an ellipsis. The + default `Hello` fits in every font; `util_boxgui` fits in + `standard`, `small` and `slant`, but is clipped in `big`. + +## Walkthrough + +Planned walkthrough article (to be published on hot_newyork): + +https://pythondoc.lightgui.com/banner/ diff --git a/apps/python/banner/banner.py b/apps/python/banner/banner.py new file mode 100644 index 0000000..f7e3684 --- /dev/null +++ b/apps/python/banner/banner.py @@ -0,0 +1,344 @@ +#!/usr/bin/env python3 +# banner - util_boxgui: ASCII banner text with several built-in fonts. +# LightGUI (Python/XFrame) port of the util_box `banner` CLI utility +# (/root/fileutils/bin/banner): same fonts, same rendering, same +# inputs/outputs -- the font table and render() below are vendored +# verbatim from that script so the GUI can never drift from the CLI. +# +# Layout (640x480): text entry + font combo on top, scrolling output +# area below showing the rendered banner. Text is pre-filled with +# "Hello" and the first font (standard) is selected, so the banner is +# already rendered on launch. Typing in the entry or picking another +# font re-renders live. +# +# Run with: +# PYTHONPATH=/root/lg-review/lightgui_python python3 banner.py +# +# Modelled on lightgui_python/examples/gtkentry.py, gtkcomboboxtext.py +# and gtktextview.py: widgets are created with create() + set_prop(), +# drawn on a Gtk.DrawingArea by widget.draw(cr), hit-tested on click, +# and dispatched through _HANDLERS. LightGUI draws the widgets with +# Cairo; it does not give them real GTK keyboard focus, so this app +# wires focus + typing itself: click the entry to focus it (blue +# outline), type to edit, BackSpace deletes; click the font combo to +# cycle to the next font. + +import sys + +import gi + +gi.require_version("Gtk", "3.0") +gi.require_version("Gdk", "3.0") + +from gi.repository import Gdk, Gtk # noqa: E402 +from lightgui.xframe.core import create, parse_color # noqa: E402 + +FONTS = ["standard", "small", "big", "slant"] +DEFAULT_TEXT = "Hello" + +# --- vendored from util_box `banner` (font table + render logic) ------- +FONT = { + 'A':(" ### ","# #","#####","# #","# #"),'B':("#### ","# #","#### ","# #","#### "), + 'C':(" ####","# ","# ","# "," ####"),'D':("#### ","# #","# #","# #","#### "), + 'E':("#####","# ","#### ","# ","#####"),'F':("#####","# ","#### ","# ","# "), + 'G':(" ####","# ","# ##","# #"," ### "),'H':("# #","# #","#####","# #","# #"), + 'I':("#####"," # "," # "," # ","#####"),'J':(" ###"," # "," # ","# # "," ### "), + 'K':("# #","# # ","### ","# # ","# #"),'L':("# ","# ","# ","# ","#####"), + 'M':("# #","## ##","# # #","# #","# #"),'N':("# #","## #","# # #","# ##","# #"), + 'O':(" ### ","# #","# #","# #"," ### "),'P':("#### ","# #","#### ","# ","# "), + 'Q':(" ### ","# #","# #","# # "," ## #"),'R':("#### ","# #","#### ","# # ","# #"), + 'S':(" ####","# "," ### "," #","#### "),'T':("#####"," # "," # "," # "," # "), + 'U':("# #","# #","# #","# #"," ### "),'V':("# #","# #","# #"," # # "," # "), + 'W':("# #","# #","# # #","## ##","# #"),'X':("# #"," # # "," # "," # # ","# #"), + 'Y':("# #"," # # "," # "," # "," # "),'Z':("#####"," # "," # "," # ","#####"), + '0':(" ### ","# ##","# # #","## #"," ### "),'1':(" # "," ## "," # "," # ","#####"), + '2':("#### "," #"," ### ","# ","#####"),'3':("#### "," #"," ### "," #","#### "), + '4':("# #","# #","#####"," #"," #"),'5':("#####","# ","#### "," #","#### "), + '6':(" ####","# ","#### ","# #"," ### "),'7':("#####"," #"," # "," # "," # "), + '8':(" ### ","# #"," ### ","# #"," ### "),'9':(" ### ","# #"," ####"," #"," ### "), + ' ':(" "," "," "," "," "),'.':(" "," "," "," "," # "), + '!':(" # "," # "," # "," "," # "),'?':("#### "," #"," ## "," "," # "), + '-':(" "," ","#####"," "," "),'_':(" "," "," "," ","#####"), + "'":(" # "," # "," "," "," "),',':(" "," "," "," # "," # "), + ':':(" "," # "," "," # "," "), +} +UNKNOWN = ("#####","# # #","#####","# # #","#####") + +def render(text, font): + text = text.upper() + rows = [""] * 5 + for ch in text: + glyph = FONT.get(ch, UNKNOWN) + for i in range(5): + rows[i] += glyph[i] + " " + if font == "small": + # 3-row compact cut: top, middle, bottom rows, trimmed + rows = [rows[0].rstrip(), rows[2].rstrip(), rows[4].rstrip()] + elif font == "big": + big = [] + for r in rows: + doubled = "".join(c * 2 for c in r) + big.extend([doubled, doubled]) + rows = big + elif font == "slant": + rows = [(" " * i) + r for i, r in enumerate(rows)] + return "\n".join(r.rstrip() for r in rows) +# --- end vendored -------------------------------------------------------- + + +def _current_font(): + """Font name currently shown in the combo box.""" + return _FONT_COMBO.get_prop("text", FONTS[0]) or FONTS[0] + + +def _render(): + """Re-render the banner from the entry text + selected font.""" + text = _TEXT_ENTRY.get_prop("text", "") + font = _current_font() + if font not in FONTS: + font = FONTS[0] + # The CLI refuses empty input (argparse error); the GUI shows an + # empty output area instead -- same visible result as the CLI + # printing five blank lines, minus the blank lines. + _OUTPUT.set_prop("text", render(text, font) if text else "") + + +def on_GtkEntry_001_OnClick(widget): + # Click focuses the entry so typing goes to it. + _FOCUSED[0] = widget + _AREA[0].queue_draw() + + +def on_GtkComboBoxText_001_OnClick(widget): + # Click cycles to the next font (LightGUI draws the combo; the + # drop-down list is not a live GTK popup, so cycling is the + # interaction) and re-renders live. + cur = _current_font() + nxt = FONTS[(FONTS.index(cur) + 1) % len(FONTS)] if cur in FONTS \ + else FONTS[0] + widget.set_prop("text", nxt) + _FOCUSED[0] = None + _render() + _AREA[0].queue_draw() + + +def on_GtkTextView_001_OnClick(widget): + # Output area is read-only; clicking it just drops entry focus. + _FOCUSED[0] = None + _AREA[0].queue_draw() + + +# Event handlers, wired to the widgets in main(): +_HANDLERS = { + ("GtkEntry_001", "OnClick"): on_GtkEntry_001_OnClick, + ("GtkComboBoxText_001", "OnClick"): on_GtkComboBoxText_001_OnClick, + ("GtkTextView_001", "OnClick"): on_GtkTextView_001_OnClick, +} + + +# Design-time geometry + effective anchors per widget: +# name -> (top, left, right, bottom, x, y, width, height) +_ANCHORS = { + "GtkLabel_001": (True, True, False, False, 16, 12, 44, 30), + "GtkEntry_001": (True, True, True, False, 64, 12, 340, 30), + "GtkLabel_002": (True, False, True, False, 416, 12, 40, 30), + "GtkComboBoxText_001": (True, False, True, False, 460, 12, 164, 30), + "GtkTextView_001": (True, True, True, True, 16, 54, 608, 410), +} + + +def _apply_anchors(widgets, width, height): + """Reposition anchored widgets for a drawing area of + *width* x *height* (Flag 1: minimal anchor layout). + Computed from the design geometry every time, so a + resize is idempotent -- no drift across resizes.""" + design_w, design_h = _DESIGN_SIZE + dx = width - design_w + dy = height - design_h + for widget in widgets: + top, left, right, bottom, ox, oy, ow, oh = \ + _ANCHORS[widget.name] + x, y, w, h = ox, oy, ow, oh + if right and not left: + x = ox + dx + elif right and left: + w = ow + dx + if bottom and not top: + y = oy + dy + elif bottom and top: + h = oh + dy + widget.move_to(x, y) + widget.resize_to(w, h) + + +def _build_widgets(): + """Create every placed widget with its props.""" + widgets = [] + widget = create("GtkLabel", "GtkLabel_001", 16, 12, 44, 30) + widget.set_prop("label", "Text:") + widgets.append(widget) + widget = create("GtkEntry", "GtkEntry_001", 64, 12, 340, 30) + widget.set_prop("text", DEFAULT_TEXT) + widget.set_prop("placeholder-text", "Type banner text") + widgets.append(widget) + widget = create("GtkLabel", "GtkLabel_002", 416, 12, 40, 30) + widget.set_prop("label", "Font:") + widgets.append(widget) + widget = create("GtkComboBoxText", "GtkComboBoxText_001", + 460, 12, 164, 30) + widget.set_prop("items", "|".join(FONTS)) + widget.set_prop("text", FONTS[0]) + widgets.append(widget) + widget = create("GtkTextView", "GtkTextView_001", 16, 54, 608, 410) + widget.set_prop("editable", "false") + widget.set_prop("scroll-bars", "3") + widget.set_prop("font-name", "Monospace") + widget.set_prop("font-size", "12") + widget.set_prop("text", render(DEFAULT_TEXT, FONTS[0])) + widgets.append(widget) + return widgets + + +_DESIGN_SIZE = (640, 480) +_BACKGROUND = "" +_WIDGETS = [] +_LAST_SIZE = [None] +_PRESSED = [None] # widget that got the ButtonPress +_FOCUSED = [None] # entry widget receiving typed keys, or None +_AREA = [None] # the Gtk.DrawingArea, set in main() +_TEXT_ENTRY = None +_FONT_COMBO = None +_OUTPUT = None + + +def _hit_widget(widgets, x, y): + """Topmost visible widget containing (*x*, *y*).""" + for widget in reversed(widgets): + if widget.get_prop("visible", "true") in ("false", "0"): + continue + if widget.contains(x, y): + return widget + return None + + +def _dispatch_to(widget, event): + """Call the *event* handler of *widget* (already chosen).""" + if widget is None: + return + if widget.get_prop("enabled", "true") in ("false", "0"): + return + handler = _HANDLERS.get((widget.name, event)) + if handler is not None: + handler(widget) + + +def _dispatch(widgets, x, y, event): + """Call the *event* handler of the widget at (*x*, *y*), + if it has one wired.""" + _dispatch_to(_hit_widget(widgets, x, y), event) + + +def _on_draw(area, cr): + bg = parse_color(_BACKGROUND, None) + if bg is None: + bg = (1.0, 1.0, 1.0) + cr.set_source_rgb(*bg) + cr.paint() + for widget in _WIDGETS: + widget.draw(cr) + # Focus outline around the entry receiving typed keys. + focused = _FOCUSED[0] + if focused is not None: + cr.save() + cr.set_source_rgb(0.2, 0.45, 0.85) + cr.set_line_width(2.0) + cr.rectangle(focused.x - 1, focused.y - 1, + focused.width + 2, focused.height + 2) + cr.stroke() + cr.restore() + return False + + +def _on_button_press(area, event): + if event.type == Gdk.EventType.DOUBLE_BUTTON_PRESS: + _dispatch(_WIDGETS, event.x, event.y, "OnDblClick") + elif event.type == Gdk.EventType.BUTTON_PRESS: + _dispatch(_WIDGETS, event.x, event.y, "OnMouseDown") + _dispatch(_WIDGETS, event.x, event.y, "OnClick") + # Task 4: remember the pressed widget; release goes there. + _PRESSED[0] = _hit_widget(_WIDGETS, event.x, event.y) + return False + + +def _on_button_release(area, event): + # Task 4: release goes to the widget that got the press, + # even if the pointer moved off it. + widget = _PRESSED[0] + _PRESSED[0] = None + _dispatch_to(widget, "OnMouseUp") + return False + + +def _on_key_press(window, event): + """Typing goes to the focused entry (LightGUI draws the entry + with Cairo, so there is no native GTK focus to rely on).""" + entry = _FOCUSED[0] + if entry is None: + return False + key = Gdk.keyval_name(event.keyval) + text = entry.get_prop("text", "") + if key in ("BackSpace", "Delete"): + entry.set_prop("text", text[:-1]) + elif key == "Escape": + _FOCUSED[0] = None + elif event.string and event.string.isprintable(): + entry.set_prop("text", text + event.string) + else: + return False + _render() + _AREA[0].queue_draw() + return True + + +def _on_area_resize(area, allocation): + size = (allocation.width, allocation.height) + if size == _LAST_SIZE[0]: + return False + _LAST_SIZE[0] = size + _apply_anchors(_WIDGETS, size[0], size[1]) + area.queue_draw() + return False + + +def main(): + global _TEXT_ENTRY, _FONT_COMBO, _OUTPUT + window = Gtk.Window(title="banner - util_boxgui") + window.set_default_size(640, 480) + window.connect("destroy", Gtk.main_quit) + window.connect("key-press-event", _on_key_press) + vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, + spacing=0) + window.add(vbox) + area = Gtk.DrawingArea() + area.set_hexpand(True) + area.set_vexpand(True) + area.add_events(Gdk.EventMask.BUTTON_PRESS_MASK | + Gdk.EventMask.BUTTON_RELEASE_MASK) + area.connect("draw", _on_draw) + area.connect("button-press-event", _on_button_press) + area.connect("button-release-event", _on_button_release) + area.connect("size-allocate", _on_area_resize) + vbox.pack_start(area, True, True, 0) + _AREA[0] = area + _WIDGETS.extend(_build_widgets()) + by_name = {w.name: w for w in _WIDGETS} + _TEXT_ENTRY = by_name["GtkEntry_001"] + _FONT_COMBO = by_name["GtkComboBoxText_001"] + _OUTPUT = by_name["GtkTextView_001"] + window.show_all() + Gtk.main() + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/apps/python/banner/screenshot.png b/apps/python/banner/screenshot.png new file mode 100644 index 0000000..35d86a0 Binary files /dev/null and b/apps/python/banner/screenshot.png differ