Skip to content
Repos

rgui

C++ 52.5 KB512 lines Opens in site

Directory Raw Download

// demo.cpp - XFCE-style desktop in Transport Tycoon style, using only ttgui.hpp.
// Structure: AppBase + one IApp per program (Terminal, File Manager, Editor,
// Settings, Widget Gallery, SmallMap Toy, About, Calculator, Task Manager,
// Console), then main() wiring: Config load, AppRegistry, wallpaper Desktop,
// top TT-toolbar panel (Whisker-style menu, launchers, pager, tray, clock,
// Calendar + Log Out), bottom status bar, pre-opened windows, global event
// hook (console toggle, window menu), and the tick hook (clock/ticker/
// tasklist/resize relayout). Adding a program = one IApp + one registry
// line (see API.md §7). Flags: --help, --config, --dump-config, --selftest
// (--selftest executes the §13 suite binary ./run_tests; it is not a stub).
#include "ttgui.hpp"
#include <algorithm>
#include <filesystem>
#include <fstream>
using namespace ttgui;
namespace fs = std::filesystem;

// ---------- Demo state ----------
/** @brief Deterministic toy world grid (water/trees/buildings) shared by the SmallMap and Viewport windows. */
static std::vector<std::string> sampleWorld(){
  std::vector<std::string> w;
  for(int y=0;y<24;y++){ std::string row; for(int x=0;x<60;x++){ if(y<3||y>20) row+='~'; else if((x*7+y*13)%17==0) row+='T'; else if((x+y)%23==0) row+='#'; else row+='.'; } w.push_back(row); }
  w[8] = "......####......TTTT......~~~~......####..................";
  w[12]= "..TT..#  #..TT......##......TT....####....TT..............";
  return w;
}
/** @brief Whole file as a string; "" when unreadable (README window falls back to a built-in text). */
static std::string readFileStr(const std::string& p){ std::ifstream in(p); if(!in) return ""; return std::string((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>()); }
static std::string sandboxDir(){ std::string sb="/tmp/rgui-sandbox"; std::error_code ec; fs::create_directories(sb,ec); if(!fs::exists(sb+"/welcome.txt")){ std::ofstream(sb+"/welcome.txt")<<"Welcome to the rgui sandbox. Drag this file onto the Editor.\n"; std::ofstream(sb+"/notes.txt")<<"sandbox notes\n"; } return sb; }
static std::string resolveShell(const Config& cfg){ if(!cfg.shell.empty()&&cfg.shell!="/bin/sh") return cfg.shell; const char* sh=getenv("SHELL"); if(sh&&*sh) return sh; return cfg.shell.empty()?"/bin/sh":cfg.shell; }
struct DragListBox : ListBox{ Application* app=nullptr; bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Drag&&app&&selected>=0&&selected<(int)items.size()&&!app->wm.dragManager.active){ app->wm.dragManager.start(DragPayload{"list-row",items[(size_t)selected],selected,Color{},""},this,m.pos); return true; } return ListBox::onMouse(m); } bool onEvent(Event& e) override { if(e.type==EventType::Drop&&e.dragType=="list-row"&&e.dragRow>=0&&e.dragRow<(int)items.size()){ int from=e.dragRow, to=std::clamp(selected,0,(int)items.size()-1); if(from!=to){ std::string v=items[(size_t)from]; items.erase(items.begin()+from); items.insert(items.begin()+to,v); selected=to; } e.handled=true; return true; } return ListBox::onEvent(e); } };
struct DragFileList : FileList{ Application* app=nullptr; bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Drag&&app&&!selectedPath().empty()&&!app->wm.dragManager.active){ std::string sp=selectedPath(); app->wm.dragManager.start(DragPayload{"file",sp,-1,Color{},sp},this,m.pos); return true; } return FileList::onMouse(m); } };
struct DropEditor : TextEditor{ bool onEvent(Event& e) override { if(e.type==EventType::Drop){ std::string ins; if(e.dragType=="file"&&!e.dragFile.empty()) ins=readFileStr(e.dragFile); else if(!e.dragText.empty()) ins=e.dragText; if(!ins.empty()){ ensureValid(); lines[(size_t)cy].insert((size_t)cx,ins); cx+=(int)ins.size(); modified=true; onChanged.emit(); } e.handled=true; return true; } return TextEditor::onEvent(e); } };
struct DropLabel : Label{ Signal<std::string> onDropped; bool onEvent(Event& e) override { if(e.type==EventType::Drop){ text="Dropped: "+(e.dragFile.empty()?e.dragText:e.dragFile); onDropped.emit(text); e.handled=true; return true; } return Label::onEvent(e); } };

// ---------- Apps ----------
/**
 * @brief Common IApp plumbing for demo programs: stores the display
 * name/glyph and returns them from name()/glyph(). `app` is wired by
 * createWindow implementations that need Application services.
 */
struct AppBase : IApp {
  Application* app=nullptr;
  std::string nm, gl;
  AppBase(std::string n,std::string g):nm(std::move(n)),gl(std::move(g)){}
  std::string name() const override { return nm; }
  std::string glyph() const override { return gl; }
};

/** @brief Green Terminal window: TabView with a single shell tab and a split tab (two PTYs), shell = explicit Config shell, else $SHELL, else /bin/sh. */
struct TerminalApp : AppBase {
  TerminalApp():AppBase("Terminal","▣"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("Terminal","green",{6,3,62,16}); win->appName=name();
    std::string shell=resolveShell(a.cfg);
    auto* tabs=new TabView(); tabs->cfg=&a.cfg; tabs->tabs={"Shell","Split"};
    auto* t1=new TerminalWidget(60,14); t1->cfg=&a.cfg;
    auto* split=new SplitPane(); split->ratio=0.5;
    auto* t2=new TerminalWidget(30,14); t2->cfg=&a.cfg; auto* t3=new TerminalWidget(30,14); t3->cfg=&a.cfg;
    split->addChild(std::unique_ptr<Widget>(t2)); split->addChild(std::unique_ptr<Widget>(t3));
    tabs->addChild(std::unique_ptr<Widget>(t1)); tabs->addChild(std::unique_ptr<Widget>(split));
    win->setContent(std::unique_ptr<Widget>(tabs));
    for(auto* t: {t1,t2,t3}){ a.registerTerminal(t); auto* tt=t; win->onClose.connect([&a,tt](){ auto&v=a.terminals; v.erase(std::remove(v.begin(),v.end(),tt),v.end()); }); t->start(shell); }
    win->layout(); a.setFocused(t1);
  }
};
/** @brief Grey Thunar-style file manager: FileList + path label + view/sort/hidden controls over a sandbox directory (mutations never leave it). */
struct FileManagerApp : AppBase {
  FileManagerApp():AppBase("File Manager","▣"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("File Manager - Home","grey",{8,4,66,18}); win->appName=name();
    auto* root=new VBox();
    auto* crumb=new Label("Home /"); crumb->cfg=&a.cfg; crumb->prefSize={60,1};
    root->addChild(std::unique_ptr<Widget>(crumb));
    auto* split=new SplitPane(); split->ratio=0.28;
    auto* side=new ListBox(); side->cfg=&a.cfg; side->items={"Sandbox","Home","Documents","Downloads","Pictures"}; side->selected=0;
    auto* fl=new DragFileList(); fl->app=&a; fl->cfg=&a.cfg; std::string home=getenv("HOME")?getenv("HOME"):"."; fl->path=sandboxDir(); fl->refresh();
    auto* status=new Label(""); status->cfg=&a.cfg;
    fl->onSelected.connect([status,fl](std::string p){ status->text=p; });
    fl->onActivated.connect([fl,crumb](std::string p){ std::error_code ec; if(fs::is_directory(p,ec)){ fl->path=p; fl->refresh(); crumb->text=p; } });
    side->onSelected.connect([fl,home](int i){ std::string sb=sandboxDir(); if(i==0) fl->path=sb; else if(i==1) fl->path=home; else if(i==2){ std::string d=home+"/Documents"; fl->path=fs::exists(d)?d:sb; } else if(i==3){ std::string d=home+"/Downloads"; fl->path=fs::exists(d)?d:sb; } else if(i==4){ std::string d=home+"/Pictures"; fl->path=fs::exists(d)?d:sb; } fl->refresh(); });
    split->addChild(std::unique_ptr<Widget>(side)); split->addChild(std::unique_ptr<Widget>(fl));
    // toolbar row simulated with buttons inside a HBox holder
    auto* tools=new HBox();
    auto* bUp=new PushButton("Up"); bUp->cfg=&a.cfg; bUp->onPressed.connect([fl](){ auto p=fs::path(fl->path).parent_path().string(); if(!p.empty()){ fl->path=p; fl->refresh(); } });
    auto* bHidden=new ToggleButton("Hidden"); bHidden->cfg=&a.cfg; bHidden->onPressed.connect([fl,bHidden](){ fl->showHidden=bHidden->toggled; fl->refresh(); });
    auto* bNew=new PushButton("New Folder"); bNew->cfg=&a.cfg; bNew->onPressed.connect([fl](){ std::string dir=fl->path.empty()?sandboxDir():fl->path; std::string np=dir+"/NewFolder"; int n=0; while(fs::exists(np)){ np=dir+"/NewFolder"+std::to_string(++n); } fs::create_directories(np); fl->refresh(); });
    auto* bSort=new PushButton("Sort"); bSort->cfg=&a.cfg; auto sortAsc=std::make_shared<bool>(true); bSort->onPressed.connect([fl,sortAsc](){ *sortAsc=!*sortAsc; std::sort(fl->entries.begin(),fl->entries.end(),[asc=*sortAsc](auto&x,auto&y){ if(x.is_directory()!=y.is_directory()) return x.is_directory()>y.is_directory(); return asc? x.path().filename().string()<y.path().filename().string() : x.path().filename().string()>y.path().filename().string(); }); });
    auto* bView=new PushButton("Refresh"); bView->cfg=&a.cfg; bView->onPressed.connect([fl](){ fl->refresh(); });
    auto* bProps=new PushButton("Properties"); bProps->cfg=&a.cfg;
    tools->addChild(std::unique_ptr<Widget>(bUp)); tools->addChild(std::unique_ptr<Widget>(bHidden)); tools->addChild(std::unique_ptr<Widget>(bNew)); tools->addChild(std::unique_ptr<Widget>(bSort)); tools->addChild(std::unique_ptr<Widget>(bView)); tools->addChild(std::unique_ptr<Widget>(bProps));
    tools->bounds={0,0,60,1};
    // layout manually via VBox children order: crumb, tools, split, status - use VBox layout override simple stacking in draw? We'll set flex
    split->flex=1; split->prefSize={60,12};
    root->addChild(std::unique_ptr<Widget>(tools));
    root->addChild(std::unique_ptr<Widget>(split));
    root->addChild(std::unique_ptr<Widget>(status));
    status->text=std::to_string(fl->entries.size())+" items";
    bProps->onPressed.connect([&a,fl,status,&wm](){ std::string p=fl->selectedPath(); std::error_code ec; auto sz=fs::is_directory(p,ec)?0:fs::file_size(p,ec); status->text=p+" size="+(fs::is_directory(p,ec)?std::string("dir"):std::to_string(sz)); (void)wm; (void)a; });
    win->setContent(std::unique_ptr<Widget>(root));
    win->layout(); // Window/VBox/HBox/SplitPane assign parent-relative child bounds
  }
};
/** @brief Grey Mousepad-style editor: TextEditor with modified tracking; closing with unsaved changes asks first (via the app hookup). */
struct EditorApp : AppBase {
  std::string initialPath;
  EditorApp():AppBase("Editor","✎"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("Mousepad - Untitled","grey",{14,5,64,16}); win->appName=name();
    auto* root=new VBox();
    auto* ed=new DropEditor(); ed->cfg=&a.cfg; ed->setText("Welcome to Mousepad (TT style)\nEdit here. Ctrl+Q quits desktop.\n");
    ed->flex=1; ed->prefSize={60,10};
    auto* findBar=new HBox();
    auto* findEdit=new EditBox(); findEdit->cfg=&a.cfg; findEdit->placeholder="Find..."; findEdit->prefSize={18,1};
    auto* findBtn=new PushButton("Find"); findBtn->cfg=&a.cfg;
    auto* wrapBtn=new ToggleButton("Wrap"); wrapBtn->cfg=&a.cfg; wrapBtn->onPressed.connect([ed,wrapBtn](){ ed->wordWrap=wrapBtn->toggled; });
    auto* pathBox=new EditBox(sandboxDir()+"/untitled.txt"); pathBox->cfg=&a.cfg; pathBox->prefSize={28,1};
    auto* saveBtn=new PushButton("Save"); saveBtn->cfg=&a.cfg;
    findBtn->onPressed.connect([ed,findEdit,&a](){ std::string t=ed->getText(); auto p=t.find(findEdit->text); if(p==std::string::npos) a.notify("Find","Not found: "+findEdit->text); else a.notify("Find","Found at offset "+std::to_string(p)); });
    saveBtn->onPressed.connect([ed,&a,win,pathBox](){ std::string p=pathBox->text.empty()?sandboxDir()+"/untitled.txt":pathBox->text; std::error_code ec; if(fs::path(p).has_parent_path()) fs::create_directories(fs::path(p).parent_path(),ec); std::ofstream out(p); if(!out){ a.notify("Editor","Save failed: "+p); return; } out<<ed->getText(); ed->modified=false; win->title="Mousepad - "+fs::path(p).filename().string(); a.notify("Editor","Saved to "+p); });
    findBar->addChild(std::unique_ptr<Widget>(pathBox)); findBar->addChild(std::unique_ptr<Widget>(findEdit)); findBar->addChild(std::unique_ptr<Widget>(findBtn)); findBar->addChild(std::unique_ptr<Widget>(wrapBtn)); findBar->addChild(std::unique_ptr<Widget>(saveBtn));
    root->addChild(std::unique_ptr<Widget>(ed)); root->addChild(std::unique_ptr<Widget>(findBar));
    win->setContent(std::unique_ptr<Widget>(root));
    win->layout();
    // Unsaved-changes veto: closing a dirty editor opens Yes/No/Cancel and only proceeds on Yes (save) or No (discard).
    win->onCloseRequest=[ed,&a,&wm,win,pathBox]()->bool{ if(!ed->modified) return true; auto* dw=wm.createWindow("Unsaved changes","grey",{20,8,44,9}); dw->appName="Confirm"; dw->modal=true; auto mb=MessageBox::question("Unsaved changes","Save changes before closing?"); mb->cfg=&a.cfg; auto* mbp=mb.get(); mbp->onResult.connect([ed,&a,&wm,win,dw,pathBox,mbp](int idx){ std::string choice=idx>=0&&idx<(int)mbp->buttons.size()?mbp->buttons[(size_t)idx]:""; wm.closeWindow(dw); if(choice=="Yes"){ std::string p=pathBox->text.empty()?sandboxDir()+"/untitled.txt":pathBox->text; std::ofstream out(p); out<<ed->getText(); ed->modified=false; win->forceClose=true; wm.closeWindow(win); } else if(choice=="No"){ ed->modified=false; win->forceClose=true; wm.closeWindow(win); } /* Cancel: stay open */ }); dw->setContent(std::move(mb)); dw->layout(); return false; };
    a.setFocused(ed);
  }
};
/** @brief Purple XFCE Settings: tabbed pages editing the live Config (colours, effects, bell, workspaces, keybindings) with save-back to the loaded *.env.json. */
struct SettingsApp : AppBase {
  SettingsApp():AppBase("Settings","⚙"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("Settings","purple",{18,4,68,20}); win->appName=name();
    auto* tabs=new TabView(); tabs->cfg=&a.cfg; tabs->tabs={"Appearance","Window Mgr","Panel","Workspaces","Keyboard","Mouse","Access."};
    // Appearance page
    auto* appear=new VBox();
    auto* cp=new ColourPicker(); cp->cfg=&a.cfg; cp->prefSize={40,8}; cp->flex=0;
    auto* colLabel=new Label("Pick colour (Enter/click applies to caption)"); colLabel->cfg=&a.cfg; colLabel->windowClass="purple";
    auto* effCheck=new CheckBox("Effects enabled",a.cfg.effectsEnabled); effCheck->cfg=&a.cfg;
    auto* shadowCheck=new CheckBox("Drop shadow",a.cfg.dropShadow); shadowCheck->cfg=&a.cfg;
    auto* bellCheck=new CheckBox("Bell audible",a.cfg.bellAudible); bellCheck->cfg=&a.cfg;
    auto* saveBtn=new PushButton("Save Config"); saveBtn->cfg=&a.cfg;
    auto* asciiCheck=new CheckBox("ASCII bevel (dumb terminal)",a.cfg.asciiMode); asciiCheck->cfg=&a.cfg;
    effCheck->onChanged.connect([&a](bool v){ a.cfg.effectsEnabled=v; });
    shadowCheck->onChanged.connect([&a](bool v){ a.cfg.dropShadow=v; });
    bellCheck->onChanged.connect([&a](bool v){ a.cfg.bellAudible=v; });
    asciiCheck->onChanged.connect([&a](bool v){ a.cfg.asciiMode=v; if(v) a.cfg.bevelStyle="ascii"; else a.cfg.bevelStyle="unicode"; });
    cp->onPicked.connect([&a,win](std::string n,Color c){ (void)n; // re-theme live: set purple bg to picked colour approx via windowColors override
      a.cfg.windowColors["purple"].bg=c; win->cfg=&a.cfg; a.notify("Appearance","Colour applied live"); });
    saveBtn->onPressed.connect([&a](){ std::string p=a.cfg.loadedPath.empty()?"rgui.env.json":a.cfg.loadedPath; if(a.cfg.saveToFile(p)) a.notify("Settings","Saved to "+p); else a.notify("Settings","Save failed"); });
    appear->addChild(std::unique_ptr<Widget>(colLabel)); appear->addChild(std::unique_ptr<Widget>(cp)); appear->addChild(std::unique_ptr<Widget>(effCheck)); appear->addChild(std::unique_ptr<Widget>(shadowCheck)); appear->addChild(std::unique_ptr<Widget>(bellCheck)); appear->addChild(std::unique_ptr<Widget>(asciiCheck)); appear->addChild(std::unique_ptr<Widget>(saveBtn));
    auto* wmPage=new VBox(); auto* snapSlider=new Slider(a.cfg.snapDistance,0,10); snapSlider->cfg=&a.cfg; snapSlider->prefSize={30,1}; snapSlider->onChanged.connect([&a](int v){ a.cfg.snapDistance=v; });
    auto* snapLabel=new Label("Snap distance (slider)"); snapLabel->cfg=&a.cfg; snapLabel->windowClass="purple";
    auto* focusLabel=new Label("Focus: click-to-focus | Tiling: drag to edges"); focusLabel->cfg=&a.cfg; focusLabel->windowClass="purple"; focusLabel->wrap=true;
    wmPage->addChild(std::unique_ptr<Widget>(snapLabel)); wmPage->addChild(std::unique_ptr<Widget>(snapSlider)); wmPage->addChild(std::unique_ptr<Widget>(focusLabel));
    auto* panelPage=new VBox(); auto* phStepper=new NumericStepper(a.cfg.panelHeight,1,3); phStepper->cfg=&a.cfg; phStepper->onChanged.connect([&a](int v){ a.cfg.panelHeight=v; }); auto* phLabel=new Label("Panel height"); phLabel->cfg=&a.cfg; phLabel->windowClass="purple"; auto* bpCheck=new CheckBox("Bottom panel",a.cfg.bottomPanel); bpCheck->cfg=&a.cfg; bpCheck->onChanged.connect([&a](bool v){ a.cfg.bottomPanel=v; }); auto* ffCheck=new CheckBox("Focus follows mouse",a.cfg.focusFollowsMouse); ffCheck->cfg=&a.cfg; ffCheck->onChanged.connect([&a](bool v){ a.cfg.focusFollowsMouse=v; }); panelPage->addChild(std::unique_ptr<Widget>(phLabel)); panelPage->addChild(std::unique_ptr<Widget>(phStepper)); panelPage->addChild(std::unique_ptr<Widget>(bpCheck)); panelPage->addChild(std::unique_ptr<Widget>(ffCheck));
    auto* wsPage=new VBox(); auto* wsStepper=new NumericStepper(a.cfg.workspaceCount,1,8); wsStepper->cfg=&a.cfg; wsStepper->onChanged.connect([&a](int v){ a.cfg.workspaceCount=v; }); auto* wsLabel=new Label("Workspace count"); wsLabel->cfg=&a.cfg; wsLabel->windowClass="purple"; wsPage->addChild(std::unique_ptr<Widget>(wsLabel)); wsPage->addChild(std::unique_ptr<Widget>(wsStepper));
    auto* kbPage=new VBox(); auto* kbTable=new Table(); kbTable->cfg=&a.cfg; kbTable->headers={"Action","Key"}; kbTable->colWidths={18,18}; for(auto&kv:a.cfg.keybindings) kbTable->rows.push_back({kv.first,kv.second}); kbTable->flex=1; auto* kbEdit=new EditBox(); kbEdit->cfg=&a.cfg; kbEdit->placeholder="Select row, type e.g. Ctrl+W, Apply"; kbEdit->prefSize={24,1}; auto* kbApply=new PushButton("Apply Binding"); kbApply->cfg=&a.cfg; kbApply->onPressed.connect([&a,kbTable,kbEdit](){ int r=kbTable->selected; if(r>=0&&r<(int)kbTable->rows.size()&&!kbEdit->text.empty()){ std::string act=kbTable->rows[(size_t)r][0]; a.cfg.keybindings[act]=kbEdit->text; kbTable->rows[(size_t)r][1]=kbEdit->text; a.notify("Keyboard","Binding "+act+" = "+kbEdit->text+" (live)"); } }); kbPage->addChild(std::unique_ptr<Widget>(kbTable)); kbPage->addChild(std::unique_ptr<Widget>(kbEdit)); kbPage->addChild(std::unique_ptr<Widget>(kbApply));
    auto* mousePage=new VBox(); auto* dcStepper=new NumericStepper(a.cfg.doubleClickMs,100,1000); dcStepper->cfg=&a.cfg; dcStepper->onChanged.connect([&a](int v){ a.cfg.doubleClickMs=v; }); auto* dcLabel=new Label("Double-click ms"); dcLabel->cfg=&a.cfg; dcLabel->windowClass="purple"; mousePage->addChild(std::unique_ptr<Widget>(dcLabel)); mousePage->addChild(std::unique_ptr<Widget>(dcStepper));
    auto* accPage=new VBox(); auto* rmCheck=new CheckBox("Reduced motion",a.cfg.reducedMotion); rmCheck->cfg=&a.cfg; rmCheck->onChanged.connect([&a](bool v){ a.cfg.reducedMotion=v; if(v) a.cfg.effectsEnabled=false; }); auto* bellVisualCheck=new CheckBox("Bell visual flash",a.cfg.bellVisual); bellVisualCheck->cfg=&a.cfg; bellVisualCheck->onChanged.connect([&a](bool v){ a.cfg.bellVisual=v; }); accPage->addChild(std::unique_ptr<Widget>(rmCheck)); accPage->addChild(std::unique_ptr<Widget>(bellVisualCheck));
    tabs->addChild(std::unique_ptr<Widget>(appear)); tabs->addChild(std::unique_ptr<Widget>(wmPage)); tabs->addChild(std::unique_ptr<Widget>(panelPage)); tabs->addChild(std::unique_ptr<Widget>(wsPage)); tabs->addChild(std::unique_ptr<Widget>(kbPage)); tabs->addChild(std::unique_ptr<Widget>(mousePage)); tabs->addChild(std::unique_ptr<Widget>(accPage));
    win->setContent(std::unique_ptr<Widget>(tabs));
    win->layout(); // TabView + VBox pages lay out children parent-relative
  }
};
/** @brief Widget Gallery: one tab per widget family with every framework widget live — the conformance surface the Gallery-coverage test iterates. */
struct GalleryApp : AppBase {
  GalleryApp():AppBase("Widget Gallery","▦"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("Widget Gallery","grey",{10,3,76,22}); win->appName=name();
    auto* tabs=new TabView(); tabs->cfg=&a.cfg; tabs->tabs={"Buttons","Text","Lists","Choice","Menus","Scroll","Graphs","Dialogs","Keys","DragDrop","Windows"};
    // Buttons
    auto* btnPage=new VBox();
    auto* b1=new PushButton("Push"); b1->cfg=&a.cfg; auto* b2=new ToggleButton("Toggle"); b2->cfg=&a.cfg; auto* b3=new IconButton("✕","Icon"); b3->cfg=&a.cfg; auto* b4=new ArrowButton(1); b4->cfg=&a.cfg; auto* cb1=new CheckBox("Check me",true); cb1->cfg=&a.cfg;
    auto* radioG=new RadioGroup(); auto* r1=radioG->addRadio("Radio A"); r1->cfg=&a.cfg; auto* r2=radioG->addRadio("Radio B"); r2->cfg=&a.cfg; radioG->select(r1);
    auto* step=new NumericStepper(5,0,99); step->cfg=&a.cfg; auto* sli=new Slider(40,0,100); sli->cfg=&a.cfg; sli->prefSize={30,1};
    auto* prog=new ProgressBar(65,100); prog->prefSize={30,1};
    b1->onPressed.connect([&a](){ a.notify("Gallery","Push pressed"); });
    for(auto*w: std::vector<Widget*>{b1,b2,b3,b4,cb1,step,sli,prog}) btnPage->addChild(std::unique_ptr<Widget>(w));
    btnPage->addChild(std::unique_ptr<Widget>(radioG));
    // Text
    auto* txtPage=new VBox(); auto* eb=new EditBox("Edit me"); eb->cfg=&a.cfg; eb->prefSize={30,1}; auto* pwd=new EditBox("secret"); pwd->cfg=&a.cfg; pwd->password=true; auto* editor=new TextEditor(); editor->cfg=&a.cfg; editor->setText("Multi-line editor\nSecond line"); editor->prefSize={50,6}; editor->flex=1;
    auto* lbl=new Label("Label centred"); lbl->cfg=&a.cfg; lbl->align=1; auto* txt=new TextWidget(); txt->text="Read-only text widget with scrolling. Lorem ipsum dolor sit amet."; txt->cfg=&a.cfg;
    txtPage->addChild(std::unique_ptr<Widget>(lbl)); txtPage->addChild(std::unique_ptr<Widget>(eb)); txtPage->addChild(std::unique_ptr<Widget>(pwd)); txtPage->addChild(std::unique_ptr<Widget>(editor)); txtPage->addChild(std::unique_ptr<Widget>(txt));
    // Lists
    auto* listPage=new SplitPane(); listPage->ratio=0.5;
    auto* lb=new ListBox(); lb->cfg=&a.cfg; lb->items={"Alpha","Bravo","Charlie","Delta","Echo","Foxtrot"}; lb->selected=0;
    auto* tbl=new Table(); tbl->cfg=&a.cfg; tbl->headers={"Name","Value"}; tbl->colWidths={14,10}; tbl->rows={{"Revenue","1200"},{"Cost","800"},{"Profit","400"}};
    listPage->addChild(std::unique_ptr<Widget>(lb)); listPage->addChild(std::unique_ptr<Widget>(tbl));
    auto* treePage=new TreeView(); treePage->cfg=&a.cfg; treePage->roots={{"Settings",{{"Appearance",{}},{"Panel",{}}}},{"Files",{{"Home",{}},{"Sandbox",{}}}}};
    // Choice page uses tree + combo
    auto* choicePage=new VBox(); auto* combo=new ComboBox(); combo->cfg=&a.cfg; combo->items={"Brown","Purple","Grey","Green","Blue"}; combo->selected=0; auto* dateP=new DatePicker(); dateP->cfg=&a.cfg; auto* cpick=new ColourPicker(); cpick->cfg=&a.cfg; cpick->prefSize={40,6};
    choicePage->addChild(std::unique_ptr<Widget>(combo)); choicePage->addChild(std::unique_ptr<Widget>(dateP)); choicePage->addChild(std::unique_ptr<Widget>(cpick)); choicePage->addChild(std::unique_ptr<Widget>(treePage));
    // Menus page
    auto* menuPage=new VBox(); auto* mbar=new MenuBar(); mbar->menus={"File","Edit","View"}; mbar->cfg=&a.cfg; auto* menu=new Menu(); menu->cfg=&a.cfg; menu->items={{"New", "Ctrl+N",false,false,nullptr},{"Open","Ctrl+O",false,false,nullptr},{"", "",true,false,nullptr},{"Quit","Ctrl+Q",false,false,nullptr}}; menu->bounds={0,0,30,6};
    menuPage->addChild(std::unique_ptr<Widget>(mbar)); menuPage->addChild(std::unique_ptr<Widget>(menu));
    // Scroll page
    auto* scrollPage=new VBox(); auto* sb=new ScrollBar(true); sb->maxV=100; sb->page=10; sb->prefSize={1,8}; auto* vp=new ViewportWidget(); vp->world=sampleWorld(); vp->cfg=&a.cfg; vp->prefSize={40,8};
    scrollPage->addChild(std::unique_ptr<Widget>(vp)); scrollPage->addChild(std::unique_ptr<Widget>(sb));
    // Graphs
    auto* graphPage=new VBox(); auto* gr=new Graph(); gr->series={{10,20,15,30,25,40},{5,12,18,14,22,19}}; gr->legend={"Profit","Cargo"}; gr->prefSize={50,8}; auto* gr2=new Graph(); gr2->barMode=true; gr2->series={{3,7,5,9,6}}; gr2->prefSize={50,6};
    graphPage->addChild(std::unique_ptr<Widget>(gr)); graphPage->addChild(std::unique_ptr<Widget>(gr2));
    // Dialogs page
    auto* dlgPage=new VBox(); auto* infoBtn=new PushButton("Info Dialog"); infoBtn->cfg=&a.cfg; infoBtn->onPressed.connect([&a](){ a.notify("Info","This is a TT-blue info message"); a.bellRing("app"); });
    auto* errBtn=new PushButton("Error + Bell"); errBtn->cfg=&a.cfg; errBtn->onPressed.connect([&a](){ a.notify("Error","Red error - bell!"); a.bellRing("error"); });
    dlgPage->addChild(std::unique_ptr<Widget>(infoBtn)); dlgPage->addChild(std::unique_ptr<Widget>(errBtn));
    // Keys
    auto* oskPage=new OnScreenKeyboard(); oskPage->cfg=&a.cfg; oskPage->onKeyPress.connect([&a](std::string k){ a.notify("OSK","Key: "+k); });
    // DragDrop playground: DragListBox starts a real DragManager drag (Drag motion), drop reorders; DropLabel accepts file/colour drops.
    auto* ddPage=new VBox(); auto* ddLabel=new DropLabel(); ddLabel->text="Drop files / colours here. Drag list rows to reorder."; ddLabel->cfg=&a.cfg; ddLabel->wrap=true; ddLabel->onDropped.connect([&a](std::string t){ a.notify("DragDrop",t); }); auto* ddList=new DragListBox(); ddList->app=&a; ddList->cfg=&a.cfg; ddList->items={"Wagon 1","Wagon 2","Wagon 3"}; ddList->selected=0;
    auto* cpDrop=new ColourPicker(); cpDrop->cfg=&a.cfg; cpDrop->prefSize={40,4}; cpDrop->onPicked.connect([&a,ddLabel](std::string n,Color c){ (void)c; ddLabel->text="Colour picked: "+n+" (drag rows / drop files here)"; a.notify("DragDrop","Colour "+n); });
    auto* upBtn=new PushButton("Move Up"); upBtn->cfg=&a.cfg; upBtn->onPressed.connect([ddList](){ int i=ddList->selected; if(i>0){ std::swap(ddList->items[(size_t)i],ddList->items[(size_t)i-1]); ddList->selected--; } });
    auto* dnBtn=new PushButton("Move Down"); dnBtn->cfg=&a.cfg; dnBtn->onPressed.connect([ddList](){ int i=ddList->selected; if(i>=0&&i+1<(int)ddList->items.size()){ std::swap(ddList->items[(size_t)i],ddList->items[(size_t)i+1]); ddList->selected++; } });
    ddPage->addChild(std::unique_ptr<Widget>(ddLabel)); ddPage->addChild(std::unique_ptr<Widget>(ddList)); ddPage->addChild(std::unique_ptr<Widget>(cpDrop)); ddPage->addChild(std::unique_ptr<Widget>(upBtn)); ddPage->addChild(std::unique_ptr<Widget>(dnBtn));
    // Windows page: one live window per canonical TT semantic colour, opened on demand
    auto* winPage=new VBox(); auto* winLabel=new Label("Canonical TT windows: press a colour to open one live window of that class."); winLabel->cfg=&a.cfg; winLabel->wrap=true; winPage->addChild(std::unique_ptr<Widget>(winLabel));
    for(auto cls: {"brown","purple","grey","green","lightblue","lightred","blue","red","white"}){ auto* b=new PushButton(std::string("Open ")+cls); b->cfg=&a.cfg; std::string cname=cls; b->onPressed.connect([&a,&wm,cname](){ auto* w=wm.createWindow(cname+" window",cname,{16,6,36,9}); w->appName="GalleryWindow"; auto* t=new TextWidget(); t->cfg=&a.cfg; t->text="Canonical TT window class: "+cname; w->setContent(std::unique_ptr<Widget>(t)); }); winPage->addChild(std::unique_ptr<Widget>(b)); }

    tabs->addChild(std::unique_ptr<Widget>(btnPage)); tabs->addChild(std::unique_ptr<Widget>(txtPage)); tabs->addChild(std::unique_ptr<Widget>(listPage)); tabs->addChild(std::unique_ptr<Widget>(choicePage)); tabs->addChild(std::unique_ptr<Widget>(menuPage)); tabs->addChild(std::unique_ptr<Widget>(scrollPage)); tabs->addChild(std::unique_ptr<Widget>(graphPage)); tabs->addChild(std::unique_ptr<Widget>(dlgPage)); tabs->addChild(std::unique_ptr<Widget>(oskPage)); tabs->addChild(std::unique_ptr<Widget>(ddPage)); tabs->addChild(std::unique_ptr<Widget>(winPage));
    win->setContent(std::unique_ptr<Widget>(tabs));
    radioG->prefSize={30,2};
    win->layout(); // TabView + page containers lay out children parent-relative
  }
};
/** @brief Brown SmallMap toy: a MiniMapWidget linked to a ViewportWidget window (clicking the map moves the viewport rectangle). */
struct SmallMapApp : AppBase {
  SmallMapApp():AppBase("SmallMap Toy","▦"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a;
    auto* win=wm.createWindow("SmallMap","brown",{30,6,52,16}); win->appName=name();
    auto* root=new SplitPane(); root->ratio=0.55;
    auto* mm=new MiniMapWidget(); mm->world=sampleWorld(); mm->cfg=&a.cfg; mm->viewRect={5,5,14,8};
    auto* vpWinHolder=new VBox();
    auto* vp=new ViewportWidget(); vp->world=sampleWorld(); vp->cfg=&a.cfg; vp->prefSize={24,10}; vp->flex=1;
    mm->onJump.connect([vp](Point p){ vp->camX=std::max(0,p.x-5); vp->camY=std::max(0,p.y-3); });
    vp->onCellClicked.connect([mm,vp](Point p){ mm->viewRect.x=p.x-mm->viewRect.w/2; mm->viewRect.y=p.y-mm->viewRect.h/2; (void)vp; });
    vpWinHolder->addChild(std::unique_ptr<Widget>(vp));
    root->addChild(std::unique_ptr<Widget>(mm)); root->addChild(std::unique_ptr<Widget>(vpWinHolder));
    win->setContent(std::unique_ptr<Widget>(root)); win->layout();
    // also open linked viewport window per spec
    auto* vwin=wm.createWindow("Viewport","brown",{48,14,40,12}); vwin->appName="Viewport";
    auto* vp2=new ViewportWidget(); vp2->world=sampleWorld(); vp2->cfg=&a.cfg;
    int jumpId=mm->onJump.connect([vp2](Point p){ vp2->camX=std::max(0,p.x-5); vp2->camY=std::max(0,p.y-3); });
    vwin->onClose.connect([mm,jumpId](){ mm->onJump.disconnect(jumpId); }); // C8: never deref a viewport owned by a closed window
    // MiniMap filter toggles are real state consumed by MiniMapWidget::draw
    auto* filtWin=wm.createWindow("Map Filters","brown",{52,4,30,9}); filtWin->appName="MapFilters"; auto* fbox=new VBox(); for(auto key: {"vegetation","industries","owners"}){ auto* cbx=new CheckBox(std::string("Show ")+key,true); cbx->cfg=&a.cfg; std::string k=key; cbx->onChanged.connect([mm,k](bool v){ mm->filters[k]=v; }); fbox->addChild(std::unique_ptr<Widget>(cbx)); } filtWin->setContent(std::unique_ptr<Widget>(fbox)); filtWin->layout();
    vwin->setContent(std::unique_ptr<Widget>(vp2)); wm.focusWindow(win);
  }
};
/** @brief White About window: project name, build/run hints, and framework summary text. */
struct AboutApp : AppBase {
  AboutApp():AppBase("About","?"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a; auto* win=wm.createWindow("About rgui","white",{28,8,44,10}); win->appName=name();
    auto* t=new TextWidget(); t->text="rgui - Terminal Transport Tycoon GUI\nXFCE-style desktop demo\nZero-dependency C++20\nBuild: g++ -std=c++20 -Wall -Wextra -Wpedantic -O2 demo.cpp -o demo"; t->cfg=&a.cfg;
    win->setContent(std::unique_ptr<Widget>(t));
  }
};
/** @brief Small extra app proving AppRegistry genericity: a button-grid calculator that needs no framework changes. */
struct CalculatorApp : AppBase {
  CalculatorApp():AppBase("Calculator","="){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a; auto* win=wm.createWindow("Calculator","grey",{40,8,34,12}); win->appName=name();
    auto* root=new VBox(); auto* disp=new EditBox("0"); disp->cfg=&a.cfg;
    auto* grid=new Grid(); grid->cols=4;
    std::string keys="789/456*123-0.+=";
    // store expression in disp text handling simplified
    std::shared_ptr<std::string> expr=std::make_shared<std::string>(""); std::shared_ptr<double> acc=std::make_shared<double>(0); std::shared_ptr<char> pendingOp=std::make_shared<char>(0);
    for(char k: keys){ auto* b=new PushButton(std::string(1,k)); b->cfg=&a.cfg; std::string kk(1,k); b->onPressed.connect([disp,expr,acc,pendingOp,kk](){ if(kk=="="){ double v=0; try{v=std::stod(disp->text);}catch(...){} if(*pendingOp=='+') *acc+=v; else if(*pendingOp=='-') *acc-=v; else if(*pendingOp=='*') *acc*=v; else if(*pendingOp=='/') *acc= v!=0?*acc/v:*acc; else *acc=v; disp->setText(std::to_string((long long)*acc)); *pendingOp=0; } else if(kk=="+"||kk=="-"||kk=="*"||kk=="/"){ try{*acc=std::stod(disp->text);}catch(...){} *pendingOp=kk[0]; disp->setText("0"); } else { if(disp->text=="0") disp->setText(kk); else disp->setText(disp->text+kk);} }); grid->addChild(std::unique_ptr<Widget>(b)); }
    root->addChild(std::unique_ptr<Widget>(disp)); root->addChild(std::unique_ptr<Widget>(grid));
    grid->flex=1; win->setContent(std::unique_ptr<Widget>(root)); win->layout();
  }
};
/** @brief Grey Task Manager: sortable process Table fed from /proc, refreshed by its own controls. */
struct TaskManagerApp : AppBase {
  TaskManagerApp():AppBase("Task Manager","≡"){}
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a; auto* win=wm.createWindow("Task Manager","grey",{22,5,58,16}); win->appName=name();
    auto* root=new VBox(); auto* tbl=new Table(); tbl->cfg=&a.cfg; tbl->headers={"PID","Name","State"}; tbl->colWidths={8,24,10};
    // read /proc
    std::error_code ec; for(auto&e: fs::directory_iterator("/proc",ec)){ std::string n=e.path().filename().string(); if(n.empty()||!std::isdigit((unsigned char)n[0])) continue; std::string comm=readFileStr(e.path().string()+"/comm"); if(!comm.empty()&&comm.back()=='\n') comm.pop_back(); std::string stat=readFileStr(e.path().string()+"/stat"); std::string state="?"; auto lp=stat.rfind(')'); if(lp!=std::string::npos&&lp+2<stat.size()) state=stat.substr(lp+2,1); tbl->rows.push_back({n,comm,state}); if(tbl->rows.size()>40) break; }
    auto* killBtn=new PushButton("Kill Selected..."); killBtn->cfg=&a.cfg; killBtn->onPressed.connect([tbl,&a,&wm](){ if(tbl->selected<0||tbl->selected>=(int)tbl->rows.size()) return; int pid=0; try{ pid=std::stoi(tbl->rows[(size_t)tbl->selected][0]); }catch(...){ return; } if(pid<=1||pid==(int)getpid()){ a.notify("Task Manager","Refusing to kill pid "+std::to_string(pid)); return; } auto* dw=wm.createWindow("Confirm Kill","red",{24,8,40,8}); dw->modal=true; auto mb=MessageBox::question("Kill process","Send SIGTERM to PID "+std::to_string(pid)+"?"); mb->cfg=&a.cfg; auto* mbp=mb.get(); mbp->onResult.connect([&a,&wm,dw,pid,mbp](int idx){ wm.closeWindow(dw); if(idx>=0&&idx<(int)mbp->buttons.size()&&mbp->buttons[(size_t)idx]=="Yes"){ int rc=kill((pid_t)pid,SIGTERM); a.notify("Task Manager", rc==0? "SIGTERM sent to "+std::to_string(pid) : "kill failed (not owned?) pid "+std::to_string(pid)); } }); dw->setContent(std::move(mb)); dw->layout(); });
    tbl->flex=1; root->addChild(std::unique_ptr<Widget>(tbl)); root->addChild(std::unique_ptr<Widget>(killBtn));
    win->setContent(std::unique_ptr<Widget>(root)); win->layout();
  }
};
/** @brief Sticky drop-down console window: command line over help/open <app>/bell/effects/config/quit, toggled by F12 or ~. */
struct ConsoleApp : AppBase {
  ConsoleApp():AppBase("Console","~"){}
  TextEditor* logEd=nullptr; EditBox* input=nullptr;
  void createWindow(WindowManager& wm, Application& a) override {
    app=&a; auto* win=wm.createWindow("Console (`~`/F12)","grey",{12,14,64,10}); win->appName=name(); win->sticky=true;
    auto* root=new VBox(); logEd=new TextEditor(); logEd->cfg=&a.cfg; logEd->setText("rgui console - type help\n"); logEd->showLineNumbers=false;
    input=new EditBox(); input->cfg=&a.cfg; input->placeholder="command...";
    // NOTE: capture the widgets, never `this`. App instances are ephemeral
    // (the factory object is destroyed when createWindow returns, while the
    // window lives on) - a [this] capture here was a heap-use-after-free
    // segfault on the first console command (ASan-verified, demo.cpp).
    auto* logEdW=logEd; auto* inputW=input;
    input->onEnter.connect([logEdW,inputW,&a,&wm](){ std::string cmd=inputW->text; inputW->setText(""); std::string out;
      if(cmd=="help") out="help | open <app> | bell | effects on|off | config | quit | clear";
      else if(cmd.rfind("open ",0)==0){ std::string n=cmd.substr(5); auto*e=a.registry.find(n); if(e){ auto inst=e->factory(); inst->createWindow(wm,a); out="opened "+n; } else out="unknown app: "+n; }
      else if(cmd=="bell"){ a.bellRing("app"); out="bell rung"; }
      else if(cmd=="effects on"){ a.cfg.effectsEnabled=true; out="effects on"; }
      else if(cmd=="effects off"){ a.cfg.effectsEnabled=false; out="effects off"; }
      else if(cmd=="config"){ out=a.cfg.loadedPath.empty()?"(defaults)":"loaded: "+a.cfg.loadedPath; }
      else if(cmd=="clear"){ logEdW->setText(""); return; }
      else if(cmd=="quit"){ a.quit("console quit"); return; }
      else out="unknown: "+cmd+" (help)";
      logEdW->setText(logEdW->getText()+"\n> "+cmd+"\n"+out); logEdW->cy=(int)logEdW->lines.size()-1; logEdW->scrollY=std::max(0,(int)logEdW->lines.size()-std::max(1,logEdW->bounds.h-2)); }); // always show newest line
    root->addChild(std::unique_ptr<Widget>(logEd)); root->addChild(std::unique_ptr<Widget>(input));
    logEd->flex=1; win->setContent(std::unique_ptr<Widget>(root)); win->layout();
    a.setFocused(input);
  }
};

// ---------- Main ----------
/** @brief --help text: usage, config search order, and the global key/mouse summary. Keep in sync with README.md. */
static void printHelp(){
  std::cout<<"rgui demo - XFCE-style desktop in Transport Tycoon style\n"
  <<"Usage: ./demo [--config <path>] [--dump-config] [--help] [--selftest]\n"
  <<"Config search: $RGUI_CONFIG -> ./rgui.env.json -> ./.env.json -> $XDG_CONFIG_HOME/rgui/rgui.env.json -> defaults\n"
  <<"Keys: Alt+Tab switch, Delete close-all non-sticky, F12/~ console, Ctrl+Q quit, Tab traverse, Esc cancel/close menu\n"
  <<"Mouse: drag caption move, resize box/border resize, wheel on caption shade, right-click tooltip/menu\n";
}
/**
 * @brief --selftest: executes the one §13 suite binary (run_tests next
 * to the executable, ./run_tests, or tests/run_tests). Returns the
 * suite's exit code, or 2 with build instructions when not built yet.
 * There is intentionally no second, in-demo test implementation.
 */
static int runSelfTest(const char* argv0){
  // §13: exactly one suite. Execute the separately built test binary
  // (tests/test_*.cpp -> ./tests); never a divergent in-demo stub.
  namespace fs=std::filesystem;
  std::vector<fs::path> candidates;
  std::error_code ec;
  fs::path exe=fs::canonical(argv0?argv0:"demo",ec);
  if(!ec) candidates.push_back(exe.parent_path()/"run_tests");
  candidates.push_back(fs::path("run_tests"));
  candidates.push_back(fs::path("tests")/"run_tests");
  for(auto& p: candidates){
    if(fs::is_regular_file(p)){
      std::string cmd="\""+p.string()+"\"";
      std::cout<<"Running §13 suite: "<<cmd<<"\n";
      int rc=std::system(cmd.c_str());
      return rc==0?0:1;
    }
  }
  std::cerr<<"--selftest: test binary not built yet. Build it first:\n"
           <<"  g++ -std=c++20 -Wall -Wextra -Wpedantic -O2 tests/test_*.cpp -o run_tests\n"
           <<"then re-run ./demo --selftest\n";
  return 2;
}

/**
 * @brief Entry point: parse flags, load Config, register apps, build the
 * Desktop + panels + pre-opened windows, install global/tick hooks, run
 * the Application loop, and free the manually owned desktop/panels.
 */
int main(int argc,char** argv){
  std::string cfgPath; bool dump=false;
  for(int i=1;i<argc;i++){ std::string a=argv[i]; if(a=="--help"||a=="-h"){ printHelp(); return 0; } if(a=="--dump-config") dump=true; if(a=="--config"&&i+1<argc) cfgPath=argv[++i]; if(a=="--selftest") return runSelfTest(argv[0]); }
  std::string cfgErr; Config cfg=Config::load(cfgPath,&cfgErr);
  if(!cfgErr.empty()) std::cerr<<"Config warning: "<<cfgErr<<"\n";
  for(auto&w:cfg.warnings) std::cerr<<"Config warning: "<<w<<"\n";
  if(dump){ std::cout<<json::dump(cfg.toJson()); return 0; }
  Application app(cfg);
  // Registry
  app.registry.add("Terminal","▣",[](){ return std::make_unique<TerminalApp>(); });
  app.registry.add("File Manager","▣",[](){ return std::make_unique<FileManagerApp>(); });
  app.registry.add("Editor","✎",[](){ return std::make_unique<EditorApp>(); });
  app.registry.add("Settings","⚙",[](){ return std::make_unique<SettingsApp>(); });
  app.registry.add("Widget Gallery","▦",[](){ return std::make_unique<GalleryApp>(); });
  app.registry.add("SmallMap Toy","▦",[](){ return std::make_unique<SmallMapApp>(); });
  app.registry.add("About","?",[](){ return std::make_unique<AboutApp>(); });
  app.registry.add("Calculator","=",[](){ return std::make_unique<CalculatorApp>(); });
  app.registry.add("Task Manager","≡",[](){ return std::make_unique<TaskManagerApp>(); });
  app.registry.add("Console","~",[](){ return std::make_unique<ConsoleApp>(); });

  auto termSz=app.terminal.size(); int TW=termSz.first, TH=termSz.second;
  if(TW<20) TW=80;
  if(TH<10) TH=24;
  app.wm.workArea={0,1,TW,TH-2};

  // Desktop
  auto desktopUp=std::make_unique<Desktop>(); Desktop* desktop=desktopUp.get(); desktop->cfg=&app.cfg;
  desktop->icons={{"▣","Home"},{"▣","Terminal"},{"✎","Editor"},{"⚙","Settings"},{"▦","Widget Gallery"},{"▦","SmallMap Toy"},{"🗑","Trash"},{"?","README"}};
  desktop->bounds={0,0,TW,TH};
  app.desktop=desktop;
  // Keep desktop alive via wm windows? store in static holder: attach to app via leaked unique? Use shared holder vector in main scope via app.desktop pointer + keep unique alive in a container bound to app lifetime: move into a Panel that is topPanel? Instead keep desktopUp in a variable that lives during run via app's desktop pointer and manual new
  // To avoid double ownership complexity, leak intentionally into app run duration then delete after
  Desktop* desktopOwned=desktopUp.get(); // owned by desktopUp (main scope, outlives app.run()); Application borrows it

  // Top panel (TT main toolbar styled)
  auto* topPanelW=new Panel(); topPanelW->cfg=&app.cfg; topPanelW->windowClass="green"; topPanelW->bounds={0,0,TW,1};
  auto* whiskerBtn=new PushButton("☰ Menu"); whiskerBtn->cfg=&app.cfg; whiskerBtn->windowClass="green"; whiskerBtn->tooltip="Applications Menu (Whisker-style)";
  auto* clockLabel=new Label(nowTimeStr(app.cfg.clockFormat)); clockLabel->cfg=&app.cfg; clockLabel->windowClass="green";
  auto* cpuGraph=new Graph(); cpuGraph->series={{0,0,0,0,0,0,0,0}}; cpuGraph->cfg=&app.cfg; cpuGraph->prefSize={10,1}; // D1: real child of topBox, fed by tick CPU samples
  auto* taskLabel=new Label(""); taskLabel->cfg=&app.cfg; taskLabel->windowClass="green";
  auto* taskBox=new HBox(); // D1: clickable tasklist (one PushButton per window, rebuilt on tick when set changes)
  auto* trayLabel=new Label("🔋 ▂▄▆"); trayLabel->cfg=&app.cfg; trayLabel->windowClass="green";
  // Whisker menu window handling via a Menu widget shown as window
  Window* whiskerWin=nullptr;
  whiskerBtn->onPressed.connect([&app,&wm=app.wm,&whiskerWin](){
    if(whiskerWin){ app.wm.closeWindow(whiskerWin); whiskerWin=nullptr; return; }
    auto* win=app.wm.createWindow("Applications","green",{0,1,36,16}); win->appName="Menu"; whiskerWin=win; win->onClose.connect([&whiskerWin](){ whiskerWin=nullptr; }); // never toggle a freed window
    auto* root=new VBox(); auto* search=new EditBox(); search->cfg=&app.cfg; search->placeholder="Search apps...";
    auto* list=new ListBox(); list->cfg=&app.cfg; for(auto&e:app.registry.entries) list->items.push_back(e.name); list->selected=0;
    search->onChanged.connect([list,&app](std::string q){ list->items.clear(); for(auto&e:app.registry.entries){ std::string low=e.name, lq=q; std::transform(low.begin(),low.end(),low.begin(),::tolower); std::transform(lq.begin(),lq.end(),lq.begin(),::tolower); if(q.empty()||low.find(lq)!=std::string::npos) list->items.push_back(e.name); } if(!list->items.empty()) list->selected=0; });
    list->onActivated.connect([&app,&wm,list,&whiskerWin](int idx){ if(idx>=0&&idx<(int)list->items.size()){ std::string n=list->items[(size_t)idx]; auto*e=app.registry.find(n); if(e){ auto inst=e->factory(); inst->createWindow(wm,app); } } if(whiskerWin){ app.wm.closeWindow(whiskerWin); whiskerWin=nullptr; } });
    root->addChild(std::unique_ptr<Widget>(search)); root->addChild(std::unique_ptr<Widget>(list));
    list->flex=1; win->setContent(std::unique_ptr<Widget>(root)); win->layout(); app.setFocused(search);
  });
  auto makeLauncher=[&app](const std::string& label,const std::string& appName)->PushButton*{ auto* b=new PushButton(label); b->cfg=&app.cfg; b->windowClass="green"; b->tooltip=appName; b->onPressed.connect([&app,appName](){ auto*e=app.registry.find(appName); if(e){ auto inst=e->factory(); inst->createWindow(app.wm,app); } }); return b; };

  // Bottom panel
  auto* bottomPanelW=new Panel(); bottomPanelW->cfg=&app.cfg; bottomPanelW->windowClass="grey"; bottomPanelW->bounds={0,TH-1,TW,1};
  auto* statusBar=new StatusBar(); statusBar->cfg=&app.cfg; statusBar->windowClass="grey"; statusBar->sections={userHostStr(), memFreeStr()}; statusBar->ticker="Welcome to rgui! Alt+Tab switch • Delete close-all • F12 console • Drag captions • Right-click for menus • ";
  bottomPanelW->addChild(std::unique_ptr<Widget>(statusBar));

  // Assemble top panel children manually (Panel layout fills all, so position manually)
  topPanelW->clearChildren();
  // Use a HBox as panel content
  auto* topBox=new HBox(); topBox->bounds={0,0,TW,1};
  topBox->addChild(std::unique_ptr<Widget>(whiskerBtn));
  auto* l1=makeLauncher("Term","Terminal"); auto* l2=makeLauncher("Files","File Manager"); auto* l3=makeLauncher("Edit","Editor"); auto* l4=makeLauncher("Gallery","Widget Gallery");
  topBox->addChild(std::unique_ptr<Widget>(l1)); topBox->addChild(std::unique_ptr<Widget>(l2)); topBox->addChild(std::unique_ptr<Widget>(l3)); topBox->addChild(std::unique_ptr<Widget>(l4));
  auto* taskSpacer=new Spacer(1); topBox->addChild(std::unique_ptr<Widget>(taskSpacer));
  // pager buttons 1-4
  for(int i=0;i<app.cfg.workspaceCount;i++){ auto* pb=new PushButton(std::to_string(i+1)); pb->cfg=&app.cfg; pb->windowClass="green"; pb->prefSize={3,1}; int ws=i; pb->onPressed.connect([&app,ws](){ app.wm.switchWorkspace(ws); app.notify("Pager","Workspace "+std::to_string(ws+1)); }); topBox->addChild(std::unique_ptr<Widget>(pb)); }
  topBox->addChild(std::unique_ptr<Widget>(cpuGraph)); topBox->addChild(std::unique_ptr<Widget>(trayLabel)); topBox->addChild(std::unique_ptr<Widget>(taskBox)); topBox->addChild(std::unique_ptr<Widget>(taskLabel)); topBox->addChild(std::unique_ptr<Widget>(clockLabel));
  auto* calBtn=new PushButton("Cal"); calBtn->cfg=&app.cfg; calBtn->windowClass="green"; calBtn->tooltip="Calendar";
  calBtn->onPressed.connect([&app](){ auto* win=app.wm.createWindow("Calendar","brown",{30,3,26,6}); win->appName="Calendar"; auto* dp=new DatePicker(); dp->cfg=&app.cfg; win->setContent(std::unique_ptr<Widget>(dp)); dp->bounds=win->contentRect(); app.setFocused(dp); });
  topBox->addChild(std::unique_ptr<Widget>(calBtn));
  auto* logoutBtn=new PushButton("⏻ Out"); logoutBtn->cfg=&app.cfg; logoutBtn->windowClass="green"; logoutBtn->tooltip="Log Out / session actions";
  logoutBtn->onPressed.connect([&app](){
    auto* win=app.wm.createWindow("Log Out","grey",{30,8,34,8}); win->appName="Logout"; win->modal=true;
    auto* box=new VBox();
    auto* msg=new Label("Log out of rgui?"); msg->cfg=&app.cfg;
    auto* yes=new PushButton("Log Out"); yes->cfg=&app.cfg; yes->onPressed.connect([&app](){ app.quit("logout"); });
    auto* lock=new PushButton("Lock Screen"); lock->cfg=&app.cfg; lock->onPressed.connect([&app,win](){ app.wm.closeWindow(win); auto* lw=app.wm.createWindow("Locked","blue",{20,8,40,10}); lw->appName="Lock"; lw->modal=true; lw->sticky=true; auto* lb=new VBox(); auto* lm=new Label("Screen locked. Close this window (caption X / Esc via window close) to unlock."); lm->cfg=&app.cfg; lm->wrap=true; auto* unlock=new PushButton("Unlock"); unlock->cfg=&app.cfg; unlock->onPressed.connect([&app,lw](){ app.wm.closeWindow(lw); }); lb->addChild(std::unique_ptr<Widget>(lm)); lb->addChild(std::unique_ptr<Widget>(unlock)); lw->setContent(std::unique_ptr<Widget>(lb)); lw->layout(); app.notify("Lock","Locked - use Unlock to return"); });
    auto* no=new PushButton("Cancel"); no->cfg=&app.cfg; no->onPressed.connect([&app,win](){ app.wm.closeWindow(win); });
    box->addChild(std::unique_ptr<Widget>(msg)); box->addChild(std::unique_ptr<Widget>(yes)); box->addChild(std::unique_ptr<Widget>(lock)); box->addChild(std::unique_ptr<Widget>(no));
    win->setContent(std::unique_ptr<Widget>(box)); box->bounds=win->contentRect(); box->layout();
  });
  topBox->addChild(std::unique_ptr<Widget>(logoutBtn));
  topPanelW->addChild(std::unique_ptr<Widget>(topBox));
  app.topPanel=topPanelW; app.bottomPanel=bottomPanelW;

  desktopOwned->onIconActivated.connect([&app](std::string label){
    std::string mapName=label; if(label=="Home") mapName="File Manager"; if(label=="README"){ auto* win=app.wm.createWindow("README","white",{8,6,60,14}); win->appName="README"; auto* t=new TextWidget(); t->text=readFileStr("README.md"); if(t->text.empty()) t->text="rgui README\nBuild: g++ -std=c++20 -Wall -Wextra -Wpedantic -O2 demo.cpp -o demo\nRun: ./demo"; t->cfg=&app.cfg; win->setContent(std::unique_ptr<Widget>(t)); return; }
    if(label=="Trash"){ app.notify("Trash","Trash is empty"); return; }
    auto*e=app.registry.find(mapName); if(!e&&label=="SmallMap Toy") e=app.registry.find("SmallMap Toy");
    if(e){ auto inst=e->factory(); inst->createWindow(app.wm,app); }
  });

  // Desktop context / global events
  Window* consoleWin=nullptr; bool consoleVisible=false;
  app.onGlobalEvent=[&app,&consoleWin,&consoleVisible,desktopOwned,clockLabel,statusBar,taskLabel](Event& e){
    if(e.type==EventType::Custom&&e.customName=="consoleToggle"){
      if(consoleVisible&&consoleWin){ app.wm.closeWindow(consoleWin); consoleWin=nullptr; consoleVisible=false; }
      else { auto inst=std::make_unique<ConsoleApp>(); inst->createWindow(app.wm,app); consoleWin=app.wm.focusedWin; consoleVisible=true; if(consoleWin) consoleWin->onClose.connect([&consoleWin,&consoleVisible](){ consoleWin=nullptr; consoleVisible=false; }); }
      return;
    }
    if(e.type==EventType::Custom&&e.customName=="windowMenu"&&app.wm.focusedWin){
      auto* win=app.wm.focusedWin;
      auto* mwin=app.wm.createWindow("Window Menu","grey",{e.mouse.pos.x,e.mouse.pos.y,24,7}); mwin->appName="WindowMenu";
      auto* menu=new Menu(); menu->cfg=&app.cfg; menu->items={{"Minimize","",false,false,[&app,win](){ win->minimized=true; }},{"Maximize","",false,false,[&app,win](){ app.wm.maximize(win); }},{"Shade","",false,false,[win](){ win->shaded=!win->shaded; win->layout(); }},{"Sticky","",false,false,[win](){ win->sticky=!win->sticky; }},{"Close","",false,false,[&app,win](){ app.wm.closeWindow(win); }}};
      mwin->setContent(std::unique_ptr<Widget>(menu)); mwin->layout(); menu->bounds=mwin->contentRect();
      return;
    }
    (void)desktopOwned; (void)clockLabel; (void)statusBar; (void)taskLabel;
  };

  // Pre-open windows
  { auto inst=std::make_unique<TerminalApp>(); inst->createWindow(app.wm,app); }
  { auto inst=std::make_unique<FileManagerApp>(); inst->createWindow(app.wm,app); }
  { auto inst=std::make_unique<SettingsApp>(); inst->createWindow(app.wm,app); }
  { auto inst=std::make_unique<SmallMapApp>(); inst->createWindow(app.wm,app); }
  // Gallery not auto-opened (available via icon/menu) to keep first screen readable

  // Tick: clock, ticker, tasklist text, cpu
  long long tickCounter=0;
  app.onTickExtra=[&,statusBarPtr=statusBar]() mutable {
    tickCounter++;
    if(tickCounter%20==0){ clockLabel->text=nowTimeStr(app.cfg.clockFormat); statusBar->sections={userHostStr(), memFreeStr(), "CPU "+std::to_string((int)cpuUsage())+"%"}; }
    if(tickCounter%5==0) statusBar->tickerOff++;
    // CPU graph sample
    { double u=cpuUsage(); auto& ser=cpuGraph->series[0]; ser.push_back(u); if(ser.size()>16) ser.erase(ser.begin()); }
    // tasklist: clickable buttons (raise/unminimize on press), rebuilt when membership changes; label keeps compact text fallback
    { static std::string lastKey; std::string key; for(auto*w: app.wm.tasklist()) key+=w->title+";"; if(key!=lastKey){ lastKey=key; taskBox->clearChildren(); for(auto*w: app.wm.tasklist()){ auto* b=new PushButton(w->title+(w->urgent?"(!)":"")); b->cfg=&app.cfg; b->windowClass="green"; b->prefSize={(int)w->title.size()+4,1}; Window* wp=w; b->onPressed.connect([&app,wp](){ app.wm.focusWindow(wp); }); taskBox->addChild(std::unique_ptr<Widget>(b)); } taskBox->layout(); } }
    std::string tl; for(auto*w: app.wm.tasklist()){ if(!tl.empty()) tl+=" | "; tl+=w->title; if(w->urgent) tl+="(!)"; if(w->minimized) tl+=" _"; } taskLabel->text=""; (void)tl;
    // relayout top/bottom on resize handled via bounds reset here
    auto sz=app.terminal.size(); int w=sz.first, h=sz.second; if(w>0&&h>0){ if(app.topPanel){ app.topPanel->bounds={0,0,w,1}; topBox->bounds={0,0,w,1}; topBox->layout(); } if(app.bottomPanel){ app.bottomPanel->bounds={0,h-1,w,1}; statusBarPtr->bounds={0,0,w,1}; app.bottomPanel->layout(); } app.wm.workArea={0,1,w,std::max(1,h-2)}; if(app.desktop) app.desktop->bounds={0,0,w,h}; }
    // notifications expire by ttlMs inside Application::dispatchTick (expiresAtMs), not by tick count
  };

  topBox->layout(); statusBar->bounds=bottomPanelW->bounds;
  int rc=app.run();
  // D10: owners are RAII holders in main scope (desktopUp + panel unique_ptrs below declared via app pointers are released at scope exit); clear borrowed pointers first
  app.desktop=nullptr; app.topPanel=nullptr; app.bottomPanel=nullptr; delete topPanelW; delete bottomPanelW;
  (void)rc;
  if(!app.quitReason.empty()){ /* clean exit */ }
  return 0;
}
28.1ms