#pragma once
// ttgui.hpp - Zero-dependency C++20 Terminal GUI framework (Transport Tycoon style)
// Single header. Only stdlib + POSIX. Full developer docs: API.md.
//
// File map (in order):
// json - own strict JSON parser/serializer (for *.env.json config)
// Geometry - Point/Size/Rect/Insets, Color/CellStyle/Cell
// Config - THE single source of truth for all style/behaviour (§6 of API.md)
// Theme - read-only view over Config
// Signal - slot lists used by every widget
// Events - Event/KeyEventData/MouseEventData (move/click/double/wheel/drag/focus/paste)
// Canvas - double-buffered cell grid + ANSI diff rendering
// Terminal - RAII raw mode / alt screen / SGR mouse; restores on destruction
// InputParser - stdin bytes -> ParsedEvent
// Widget tree - Widget base, layout containers, full leaf-widget catalogue (API.md §3)
// VtParser - VT100/xterm subset feeding TerminalWidget (PTY + fork/exec shell)
// Window - caption (close left, shade/sticky right), resize box, semantic colour
// DragManager / BellService / WindowManager / Desktop / IApp+AppRegistry / Application
//
// Conventions: widgets are owned by their parent's unique_ptr child list;
// every public widget takes a `const Config* cfg` for styling (never hard-code
// colours/glyphs/timings); draw() must not mutate layout; onKey/onMouse
// return true iff the event was handled.
#include <algorithm>
#include <array>
#include <cctype>
#include <cerrno>
#include <chrono>
#include <cmath>
#include <cstdint>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <deque>
#include <fcntl.h>
#include <filesystem>
#include <fstream>
#include <functional>
#include <iostream>
#include <map>
#include <memory>
#include <optional>
#include <poll.h>
#include <pwd.h>
#include <csignal>
#include <ctime>
#include <sstream>
#include <string>
#include <string_view>
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <termios.h>
#include <unistd.h>
#include <utility>
#include <variant>
#include <vector>
#if defined(__linux__)
#include <pty.h>
#endif
namespace ttgui {
// ---------- JSON ----------
namespace json {
struct Value;
using Array = std::vector<Value>;
using Object = std::map<std::string, Value>;
/**
* @brief A JSON value: null, bool, number (double), string, Array, or Object.
* @details Constructors: `Value()`/`Value(std::nullptr_t)` make null;
* `Value(bool)`, `Value(double)`, `Value(int)` (stored as double),
* `Value(const char*)`/`Value(std::string)`, `Value(Array)`, `Value(Object)`.
* Type queries: `isNull()`, `isBool()`, `isNum()`, `isStr()`, `isArr()`,
* `isObj()` report the held alternative and never throw.
* Accessors return the caller's default on type mismatch instead of
* throwing: `asBool(d)`, `asNum(d)`, `asInt(d)` (truncating `asNum`),
* `asStr(d)`, plus borrowed pointers `asArr()`/`asObj()` (nullptr on
* mismatch). `find(key)` returns a borrowed pointer to an object member,
* or nullptr when this is not an object or the key is absent. The owned
* variant is public as `v` for visitors that need it.
*/
struct Value {
std::variant<std::nullptr_t,bool,double,std::string,Array,Object> v;
Value():v(nullptr){}
Value(std::nullptr_t):v(nullptr){}
Value(bool b):v(b){} Value(double d):v(d){} Value(int i):v((double)i){}
Value(const char* s):v(std::string(s)){} Value(std::string s):v(std::move(s)){}
Value(Array a):v(std::move(a)){} Value(Object o):v(std::move(o)){}
bool isNull() const { return std::holds_alternative<std::nullptr_t>(v); }
bool isBool() const { return std::holds_alternative<bool>(v); }
bool isNum() const { return std::holds_alternative<double>(v); }
bool isStr() const { return std::holds_alternative<std::string>(v); }
bool isArr() const { return std::holds_alternative<Array>(v); }
bool isObj() const { return std::holds_alternative<Object>(v); }
bool asBool(bool d=false) const { auto*p=std::get_if<bool>(&v); return p?*p:d; }
double asNum(double d=0) const { auto*p=std::get_if<double>(&v); return p?*p:d; }
int asInt(int d=0) const { double v=asNum(d); if(!std::isfinite(v)) return d; v=std::clamp(v,(double)INT_MIN,(double)INT_MAX); return (int)v; }
std::string asStr(const std::string& d="") const { auto*p=std::get_if<std::string>(&v); return p?*p:d; }
const Array* asArr() const { return std::get_if<Array>(&v); }
const Object* asObj() const { return std::get_if<Object>(&v); }
const Value* find(const std::string& k) const { auto*o=asObj(); if(!o) return nullptr; auto it=o->find(k); return it==o->end()?nullptr:&it->second; }
};
/** @brief Parse failure report filled by json::parse(): `msg` plus 1-based `line`/`col`. */
struct ParseError{ std::string msg; int line=1,col=1; };
/**
* @brief Recursive-descent JSON parser over a string_view (internal; use parse()).
* @details `Parser(std::string_view)` stores the input; `peek()` returns the
* current char or '\0' at end; `get()` consumes one char tracking line/col;
* `ws()` skips JSON whitespace; `expect(c)` consumes `c` or sets `err`.
* `value()` parses any JSON value (objects keep last duplicate key);
* `match(word)` consumes an exact literal (`true`/`false`/`null`);
* `stringVal()` parses a quoted string with escapes and \uXXXX (encoded to
* UTF-8); `number()` parses a JSON number via std::stod. All failures set
* `err` and return std::nullopt — the parser never throws on bad input.
*/
struct Parser {
std::string_view s; size_t pos=0; int line=1,col=1; std::string err; int depth=0;
static constexpr int kMaxDepth=200;
explicit Parser(std::string_view sv):s(sv){}
char peek(){ return pos<s.size()?s[pos]:'\0'; }
char get(){ char c=peek(); if(pos<s.size()) pos++; if(c=='\n'){line++;col=1;} else col++; return c; }
void ws(){ while(pos<s.size()&&(s[pos]==' '||s[pos]=='\t'||s[pos]=='\n'||s[pos]=='\r')) get(); }
bool expect(char c){ ws(); if(peek()==c){get();return true;} err=std::string("expected ")+c; return false; }
std::optional<Value> value(){
if(depth>=kMaxDepth){ err="max nesting depth exceeded"; return std::nullopt; }
struct DepthGuard{ Parser& p; explicit DepthGuard(Parser& pp):p(pp){p.depth++;} ~DepthGuard(){p.depth--;} };
DepthGuard guard(*this);
ws(); char c=peek();
if(c=='{'){ get(); Object o; ws(); if(peek()=='}'){get();return Value(std::move(o));}
while(true){ ws(); auto k=stringVal(); if(!k) return std::nullopt; ws(); if(!expect(':')) return std::nullopt; auto val=value(); if(!val) return std::nullopt; o[*k]=std::move(*val); ws(); if(peek()==','){get();continue;} if(peek()=='}'){get();break;} err="expected , or }"; return std::nullopt; } return Value(std::move(o)); }
if(c=='['){ get(); Array a; ws(); if(peek()==']'){get();return Value(std::move(a));}
while(true){ auto val=value(); if(!val) return std::nullopt; a.push_back(std::move(*val)); ws(); if(peek()==','){get();continue;} if(peek()==']'){get();break;} err="expected , or ]"; return std::nullopt; } return Value(std::move(a)); }
if(c=='"'){ auto str=stringVal(); if(!str) return std::nullopt; return Value(*str); }
if(c=='t'){ if(match("true")) return Value(true); err="bad literal"; return std::nullopt; }
if(c=='f'){ if(match("false")) return Value(false); err="bad literal"; return std::nullopt; }
if(c=='n'){ if(match("null")) return Value(nullptr); err="bad literal"; return std::nullopt; }
return number();
}
bool match(std::string_view w){ if(s.substr(pos,w.size())==w){ for(size_t i=0;i<w.size();i++) get(); return true;} return false; }
std::optional<std::string> stringVal(){ if(peek()!='"') {err="expected string"; return std::nullopt;} get(); std::string out; while(pos<s.size()){ char c=get(); if(c=='"') return out; if(c=='\\'){ if(pos>=s.size()) break; char e=get(); if(e=='n') out+='\n'; else if(e=='t') out+='\t'; else if(e=='r') out+='\r'; else if(e=='"') out+='"'; else if(e=='\\') out+='\\'; else if(e=='/') out+='/'; else if(e=='u'){ std::string hex; for(int i=0;i<4&&pos<s.size();i++) hex+=get(); unsigned code=0; try{code=std::stoul(hex,nullptr,16);}catch(...){} if(code<0x80) out+=(char)code; else if(code<0x800){ out+=(char)(0xC0|(code>>6)); out+=(char)(0x80|(code&0x3F)); } else { out+=(char)(0xE0|(code>>12)); out+=(char)(0x80|((code>>6)&0x3F)); out+=(char)(0x80|(code&0x3F)); } } else out+=e; } else out+=c; } err="unterminated string"; return std::nullopt; }
std::optional<Value> number(){ size_t start=pos; if(peek()=='-') get(); while(std::isdigit((unsigned char)peek())) get(); if(peek()=='.'){get(); while(std::isdigit((unsigned char)peek())) get();} if(peek()=='e'||peek()=='E'){get(); if(peek()=='+'||peek()=='-') get(); while(std::isdigit((unsigned char)peek())) get();} if(start==pos){err="expected value";return std::nullopt;} try{ return Value(std::stod(std::string(s.substr(start,pos-start)))); }catch(...){ err="bad number"; return std::nullopt; } }
};
/**
* @brief Parse JSON text into a Value, tolerating // and block comments.
* @param sv input text (comments are stripped outside strings first).
* @param pe optional out-parameter receiving message and 1-based line/col.
* @return the value, or std::nullopt on any malformed input or trailing garbage.
*/
inline std::optional<Value> parse(std::string_view sv, ParseError* pe=nullptr){
// strip // and /* */ comments for env.json convenience (non-standard but useful)
std::string cleaned; cleaned.reserve(sv.size()); bool inStr=false; bool esc=false;
for(size_t i=0;i<sv.size();i++){ char c=sv[i]; if(inStr){ cleaned+=c; if(esc) esc=false; else if(c=='\\') esc=true; else if(c=='"') inStr=false; continue; } if(c=='"'){inStr=true;cleaned+=c;continue;} if(c=='/'&&i+1<sv.size()&&sv[i+1]=='/'){ while(i<sv.size()&&sv[i]!='\n') i++; if(i<sv.size()) cleaned+='\n'; continue; } if(c=='/'&&i+1<sv.size()&&sv[i+1]=='*'){ i+=2; while(i+1<sv.size()&&!(sv[i]=='*'&&sv[i+1]=='/')) i++; i++; continue; } cleaned+=c; }
Parser p(cleaned); auto v=p.value(); p.ws(); if(!v||p.pos<p.s.size()){ if(pe){pe->msg=p.err.empty()?"parse error":p.err; pe->line=p.line; pe->col=p.col;} return std::nullopt; } return v;
}
/**
* @brief Serialize a Value as pretty JSON (2-space indent) appended to `out`.
* @details Integral doubles print without a decimal point; strings escape
* quote, backslash, newline, and tab. The overload returning std::string
* wraps this and appends a trailing newline. Keys are emitted in sorted
* (std::map) order, so output is stable for round-trip comparisons.
*/
inline void dump(const Value& v, std::string& out, int indent=0){
if(indent>200){ out+="null"; return; }
auto pad=[&](int n){ out.append((size_t)n*2,' '); };
if(v.isNull()) out+="null";
else if(v.isBool()) out+=v.asBool()?"true":"false";
else if(v.isNum()){ double d=v.asNum(); if(d==std::floor(d)&&std::abs(d)<1e15){ out+=std::to_string((long long)d);} else { std::ostringstream oss; oss<<d; out+=oss.str(); } }
else if(v.isStr()){ out+='"'; for(char c: v.asStr()){ if(c=='"') out+="\\\""; else if(c=='\\') out+="\\\\"; else if(c=='\n') out+="\\n"; else if(c=='\t') out+="\\t"; else out+=c; } out+='"'; }
else if(v.isArr()){ auto*a=v.asArr(); out+="["; for(size_t i=0;i<a->size();i++){ if(i) out+=","; out+="\n"; pad(indent+1); dump((*a)[i],out,indent+1);} if(!a->empty()){out+="\n"; pad(indent);} out+="]"; }
else if(v.isObj()){ auto*o=v.asObj(); out+="{"; bool first=true; for(auto&kv:*o){ if(!first) out+=","; first=false; out+="\n"; pad(indent+1); out+='"'+kv.first+"\": "; dump(kv.second,out,indent+1);} if(!o->empty()){out+="\n"; pad(indent);} out+="}"; }
}
/// @brief Convenience overload of dump(): returns the pretty JSON string.
inline std::string dump(const Value& v){ std::string s; dump(v,s,0); s+="\n"; return s; }
} // json
// ---------- Geometry ----------
/** @brief Integer point in terminal cells. `Point(x,y)`; `operator==`, `operator+`, `operator-` are cell-wise. */
struct Point{ int x=0,y=0; Point()=default; Point(int x_,int y_):x(x_),y(y_){} bool operator==(const Point& o) const {return x==o.x&&y==o.y;} Point operator+(Point o) const {return {x+o.x,y+o.y};} Point operator-(Point o) const {return {x-o.x,y-o.y};} };
/** @brief Integer extent in cells. `empty()` is true when either dimension is <= 0. */
struct Size{ int w=0,h=0; Size()=default; Size(int w_,int h_):w(w_),h(h_){} bool empty() const {return w<=0||h<=0;} };
/**
* @brief Axis-aligned rectangle in cells, (x,y) inclusive, right()/bottom() exclusive.
* @details Constructors: default (empty at origin), `Rect(x,y,w,h)`,
* `Rect(Point, Size)`. Accessors: `left()/top()/right()/bottom()`,
* `pos()`, `size()`, `empty()`, `contains(Point)`/`contains(x,y)` (half-open).
* Transforms never produce negative sizes: `intersect(o)` (empty rect on
* disjoint input), `unionRect(o)` (empty-aware bounding box),
* `clampInside(bounds)` (shrinks then clamps position inside bounds),
* `inset(dx,dy)` (symmetric shrink) and `inset(l,t,r,b)` (per-edge shrink).
* `operator==` compares all four fields.
*/
struct Rect{ int x=0,y=0,w=0,h=0; Rect()=default; Rect(int x_,int y_,int w_,int h_):x(x_),y(y_),w(w_),h(h_){} Rect(Point p,Size s):x(p.x),y(p.y),w(s.w),h(s.h){}
int left() const {return x;} int top() const {return y;} int right() const {return x+w;} int bottom() const {return y+h;}
bool empty() const {return w<=0||h<=0;} bool contains(Point p) const {return p.x>=x&&p.x<x+w&&p.y>=y&&p.y<y+h;} bool contains(int px,int py) const {return contains({px,py});}
Rect intersect(Rect o) const { int nx=std::max(x,o.x), ny=std::max(y,o.y), nr=std::min(right(),o.right()), nb=std::min(bottom(),o.bottom()); if(nr<=nx||nb<=ny) return {nx,ny,0,0}; return {nx,ny,nr-nx,nb-ny}; }
Rect unionRect(Rect o) const { if(empty()) return o; if(o.empty()) return *this; int nx=std::min(x,o.x), ny=std::min(y,o.y); return {nx,ny,std::max(right(),o.right())-nx, std::max(bottom(),o.bottom())-ny}; }
Rect clampInside(Rect bounds) const { Rect r=*this; r.w=std::min(r.w,bounds.w); r.h=std::min(r.h,bounds.h); r.x=std::clamp(r.x,bounds.x,bounds.right()-r.w); r.y=std::clamp(r.y,bounds.y,bounds.bottom()-r.h); return r; }
Rect inset(int dx,int dy) const { return {x+dx,y+dy,std::max(0,w-2*dx),std::max(0,h-2*dy)}; }
Rect inset(int l,int t,int r,int b) const { return {x+l,y+t,std::max(0,w-l-r),std::max(0,h-t-b)}; }
Point pos() const {return {x,y};} Size size() const {return {w,h};}
bool operator==(const Rect& o) const {return x==o.x&&y==o.y&&w==o.w&&h==o.h;}
};
/** @brief Per-edge margins in cells: left, top, right, bottom. */
struct Insets{ int l=0,t=0,r=0,b=0; };
// ---------- Colour ----------
/**
* @brief A terminal colour: RGB (r/g/b >= 0), 256-palette index (idx >= 0),
* or the terminal default (idx == -2, see def()).
* @details Factories: `def()` (default), `indexed(i)`, `rgb(r,g,b)`,
* `named(n)` (named colour, "#rrggbb", or numeric index string; unknown
* names yield def()). `isDefault()` checks the def() sentinel.
* `operator==` compares all channels including the sentinel.
*/
struct Color{
int r=-1,g=-1,b=-1; int idx=-1; // idx 0-255, or -1 default
bool isDefault() const {return idx==-2;}
static Color def(){ Color c; c.idx=-2; return c; }
static Color indexed(int i){ Color c; c.idx=std::clamp(i,0,255); return c; }
static Color rgb(int r_,int g_,int b_){ Color c; c.r=std::clamp(r_,0,255);c.g=std::clamp(g_,0,255);c.b=std::clamp(b_,0,255); return c; }
static Color named(const std::string& n);
bool operator==(const Color& o) const {return r==o.r&&g==o.g&&b==o.b&&idx==o.idx;}
};
/// @brief Definition of Color::named(): built-in names, "#rrggbb", or a decimal 256-index; anything else yields def().
inline Color Color::named(const std::string& n){
static const std::map<std::string,Color> m={
{"black",rgb(0,0,0)},{"white",rgb(255,255,255)},{"red",rgb(205,49,49)},{"green",rgb(13,188,121)},
{"blue",rgb(36,114,200)},{"yellow",rgb(229,229,16)},{"magenta",rgb(188,63,188)},{"cyan",rgb(17,168,205)},
{"grey",rgb(128,128,128)},{"gray",rgb(128,128,128)},{"cream",rgb(255,240,200)},{"brown",rgb(139,90,43)},
{"orange",rgb(255,140,0)},{"purple",rgb(128,0,128)},{"pink",rgb(255,105,180)},{"darkblue",rgb(0,0,139)},
{"darkgreen",rgb(0,100,0)},{"lightblue",rgb(173,216,230)},{"palegreen",rgb(152,251,152)},{"mauve",rgb(224,176,255)},
};
auto it=m.find(n); if(it!=m.end()) return it->second;
if(!n.empty()&&n[0]=='#'&&n.size()==7){ try{ int v=std::stoi(n.substr(1),nullptr,16); return rgb((v>>16)&255,(v>>8)&255,v&255);}catch(...){} }
// 256 index as number string
try{ if(!n.empty()&&std::all_of(n.begin(),n.end(),::isdigit)) return indexed(std::stoi(n)); }catch(...){}
return def();
}
/** @brief Foreground/background plus SGR attributes for one cell. `operator==` compares colours and all attributes; the diff renderer relies on it. */
struct CellStyle{ Color fg=Color::def(), bg=Color::def(); bool bold=false, dim=false, underline=false, reverse=false, italic=false; bool operator==(const CellStyle& o) const {return fg==o.fg&&bg==o.bg&&bold==o.bold&&dim==o.dim&&underline==o.underline&&reverse==o.reverse&&italic==o.italic;} };
/** @brief One terminal cell: a UTF-8 glyph string `ch` (usually one codepoint) with style `st`. `operator==` compares both. */
struct Cell{ std::string ch=" "; CellStyle st; bool operator==(const Cell& o) const {return ch==o.ch&&st==o.st;} };
// ---------- Config ----------
/** @brief Foreground/background pair defining one semantic window colour. */
struct WindowColor{ Color fg, bg; };
/**
* @brief The single source of truth for all style and behaviour. No other
* global state exists; widgets receive a `const Config*`.
* @details Public fields (all documented in API.md §6): `windowColors`
* (semantic name -> WindowColor), `ttColors` (16 TT colours + Black),
* `glyphs`, `bevelStyle` ("unicode"|"ascii"), panel geometry
* (`panelHeight`, `panelPosition`, `bottomPanelHeight`, `bottomPanel`),
* layout/input (`padding`, `spacing`, `snapDistance`, `doubleClickMs`,
* `tooltipDelayMs`, `caretBlinkMs`), effects (`effectsEnabled`,
* `reducedMotion`, `dropShadow`, `popEffect`, `shadeSlide`, `menuReveal`,
* `smoothScroll`), bell (`bellAudible`, `bellVisual`, `bellVisualMs`,
* `bellOnError`, `bellSuppressFocused`), `keybindings`, `shell`,
* `workspaceCount`, `clockFormat`, wallpaper (`wallpaperPattern`,
* `wallpaperColor`, `wallpaperFg`), `mouseForwarding`, `loadedPath`,
* `warnings` (accumulated load diagnostics), `asciiMode`.
* Methods: `defaults()` builds the built-in theme; `windowColor(k)`
* (falls back to grey), `ttColor(k)`, `glyph(k, fallback)`;
* `toJson()` serializes every field (stable key order);
* `colorToStr(c)` ("#rrggbb", index, or "default") and
* `parseColor(v)` (string/number/{r,g,b}/{index} forms) convert colours;
* `applyJson(root)` merges a parsed file, warning on unknown keys and
* wrong types, clamping ranges, and forcing effects off under
* reducedMotion; `loadFromFile(path, errOut)` / `saveToFile(path)`;
* `findConfigPath(explicitPath)` implements the documented search order;
* `load(explicitPath, errOut)` = defaults + first found file.
*/
class Config{
public:
// colours
std::map<std::string,WindowColor> windowColors;
std::map<std::string,Color> ttColors;
std::map<std::string,Color> uiColors; ///< widget base colours by role: paper, paperText, selection, selectionText, disabledText, menuPaper, iconGridBg, badgeBg, badgeUrgent, urgent, progressTrack, progressFill
std::map<std::string,std::string> glyphs;
std::string bevelStyle="unicode"; // unicode|ascii
int panelHeight=1; std::string panelPosition="top"; int bottomPanelHeight=1; bool bottomPanel=true;
int padding=0, spacing=1, snapDistance=2, doubleClickMs=400, tooltipDelayMs=600, caretBlinkMs=500;
bool effectsEnabled=true, reducedMotion=false, dropShadow=true, popEffect=true, shadeSlide=true, menuReveal=true, smoothScroll=true;
bool bellAudible=true, bellVisual=true; int bellVisualMs=150; bool bellOnError=true; bool bellSuppressFocused=true;
std::map<std::string,std::string> keybindings;
std::string shell="/bin/sh"; int workspaceCount=4; std::string clockFormat="%H:%M"; std::string wallpaperPattern="shade"; Color wallpaperColor=Color::rgb(30,60,40);
int wallpaperFg=236; bool mouseForwarding=true; std::string loadedPath; std::vector<std::string> warnings;
bool asciiMode=false; bool focusFollowsMouse=false;
static Config defaults(){
Config c;
c.windowColors["brown"]={Color::rgb(255,240,200), Color::rgb(139,90,43)};
c.windowColors["purple"]={Color::rgb(255,255,255), Color::rgb(100,70,140)};
c.windowColors["grey"]={Color::rgb(0,0,0), Color::rgb(170,170,170)};
c.windowColors["green"]={Color::rgb(255,255,255), Color::rgb(34,120,60)};
c.windowColors["lightblue"]={Color::rgb(0,0,0), Color::rgb(173,216,230)};
c.windowColors["lightred"]={Color::rgb(0,0,0), Color::rgb(240,180,180)};
c.windowColors["blue"]={Color::rgb(255,255,255), Color::rgb(36,80,180)};
c.windowColors["red"]={Color::rgb(255,255,255), Color::rgb(180,30,30)};
c.windowColors["white"]={Color::rgb(0,0,0), Color::rgb(245,245,235)};
const char* names[]={"DarkBlue","PaleGreen","Pink","Yellow","Red","LightBlue","Green","DarkGreen","Blue","Cream","Mauve","Purple","Orange","Brown","Grey","White","Black"};
Color cols[]={Color::rgb(0,0,139),Color::rgb(152,251,152),Color::rgb(255,105,180),Color::rgb(255,235,0),Color::rgb(220,40,40),Color::rgb(100,180,255),Color::rgb(40,200,80),Color::rgb(0,120,40),Color::rgb(40,80,220),Color::rgb(255,240,200),Color::rgb(200,160,255),Color::rgb(150,60,200),Color::rgb(255,140,0),Color::rgb(139,90,43),Color::rgb(150,150,150),Color::rgb(255,255,255),Color::rgb(0,0,0)};
for(int i=0;i<17;i++) c.ttColors[names[i]]=cols[i];
c.uiColors={{"paper",Color::rgb(255,255,255)},{"paperText",Color::rgb(0,0,0)},{"selection",Color::rgb(36,80,180)},{"selectionText",Color::rgb(255,255,255)},{"disabledText",Color::rgb(150,150,150)},{"menuPaper",Color::rgb(245,245,245)},{"iconGridBg",Color::rgb(30,60,40)},{"badgeBg",Color::rgb(80,80,80)},{"badgeUrgent",Color::rgb(200,30,30)},{"urgent",Color::rgb(200,30,30)},{"progressTrack",Color::rgb(80,80,80)},{"progressFill",Color::rgb(34,120,60)},{"tooltipBg",Color::rgb(255,255,220)},{"panelGrey",Color::rgb(170,170,170)}};
c.glyphs={{"close","✕"},{"shade","▁"},{"sticky","📌"},{"resize","◢"},{"up","▲"},{"down","▼"},{"left","◀"},{"right","▶"},{"check","✓"},{"radio","●"},{"shadow","░"},{"block","█"},{"shadeLight","░"},{"shadeMed","▒"},{"shadeDark","▓"},{"halfTop","▀"},{"halfBot","▄"}};
c.keybindings={{"closeAll","Delete"},{"switchWindow","Alt+Tab"},{"console","F12"},{"quit","Ctrl+Q"},{"keyboardMove","Alt+F7"},{"cascade","Alt+F8"},{"tile","Alt+F9"}};
return c;
}
WindowColor windowColor(const std::string& k) const { auto it=windowColors.find(k); if(it!=windowColors.end()) return it->second; auto g=windowColors.find("grey"); if(g!=windowColors.end()) return g->second; return WindowColor{Color::rgb(0,0,0),Color::rgb(170,170,170)}; }
std::string binding(const std::string& action, const std::string& fallback="") const { auto it=keybindings.find(action); return it!=keybindings.end()?it->second:fallback; }
Color ttColor(const std::string& k) const { auto it=ttColors.find(k); if(it!=ttColors.end()) return it->second; return Color::def(); }
/** @brief Widget base colour by role (paper/selection/urgent/...); falls back to `fb` when cfg role unset. */
Color uiColor(const std::string& k, Color fb) const { auto it=uiColors.find(k); return it!=uiColors.end()?it->second:fb; }
std::string glyph(const std::string& k, const std::string& fb="") const { auto it=glyphs.find(k); return it!=glyphs.end()?it->second:fb; }
json::Value toJson() const {
json::Object o; json::Object wc; for(auto&kv:windowColors){ json::Object p; p["fg"]=json::Value(colorToStr(kv.second.fg)); p["bg"]=json::Value(colorToStr(kv.second.bg)); wc[kv.first]=json::Value(std::move(p)); } o["windowColors"]=json::Value(std::move(wc));
json::Object g; for(auto&kv:glyphs) g[kv.first]=json::Value(kv.second); o["glyphs"]=json::Value(std::move(g));
o["bevelStyle"]=json::Value(bevelStyle); o["panelHeight"]=json::Value(panelHeight); o["panelPosition"]=json::Value(panelPosition); o["bottomPanel"]=json::Value(bottomPanel);
o["snapDistance"]=json::Value(snapDistance); o["doubleClickMs"]=json::Value(doubleClickMs); o["tooltipDelayMs"]=json::Value(tooltipDelayMs); o["caretBlinkMs"]=json::Value(caretBlinkMs);
o["effectsEnabled"]=json::Value(effectsEnabled); o["reducedMotion"]=json::Value(reducedMotion); o["dropShadow"]=json::Value(dropShadow);
o["bellAudible"]=json::Value(bellAudible); o["bellVisual"]=json::Value(bellVisual); o["bellVisualMs"]=json::Value(bellVisualMs); o["bellOnError"]=json::Value(bellOnError);
o["shell"]=json::Value(shell); o["workspaceCount"]=json::Value(workspaceCount); o["clockFormat"]=json::Value(clockFormat); o["wallpaperPattern"]=json::Value(wallpaperPattern);
{ json::Object tc; for(auto&kv:ttColors) tc[kv.first]=json::Value(colorToStr(kv.second)); o["ttColors"]=json::Value(std::move(tc)); }
{ json::Object uc; for(auto&kv:uiColors) uc[kv.first]=json::Value(colorToStr(kv.second)); o["uiColors"]=json::Value(std::move(uc)); }
o["spacing"]=json::Value(spacing); o["padding"]=json::Value(padding); o["bottomPanelHeight"]=json::Value(bottomPanelHeight);
o["popEffect"]=json::Value(popEffect); o["shadeSlide"]=json::Value(shadeSlide); o["menuReveal"]=json::Value(menuReveal); o["smoothScroll"]=json::Value(smoothScroll);
o["bellSuppressFocused"]=json::Value(bellSuppressFocused); o["mouseForwarding"]=json::Value(mouseForwarding); o["asciiMode"]=json::Value(asciiMode); o["focusFollowsMouse"]=json::Value(focusFollowsMouse); o["wallpaperFg"]=json::Value(wallpaperFg); o["wallpaperColor"]=json::Value(colorToStr(wallpaperColor));
json::Object kb; for(auto&kv:keybindings) kb[kv.first]=json::Value(kv.second); o["keybindings"]=json::Value(std::move(kb));
return json::Value(std::move(o));
}
static std::string colorToStr(const Color& c){ if(c.r>=0){ char buf[16]; std::snprintf(buf,sizeof(buf),"#%02x%02x%02x",c.r,c.g,c.b); return buf; } if(c.idx>=0) return std::to_string(c.idx); return "default"; }
static Color parseColor(const json::Value& v){ if(v.isStr()) return Color::named(v.asStr()); if(v.isNum()) return Color::indexed(std::clamp(v.asInt(),0,255)); if(v.isObj()){ auto* r=v.find("r"); auto* g=v.find("g"); auto* b=v.find("b"); if(r&&g&&b) return Color::rgb(std::clamp(r->asInt(),0,255),std::clamp(g->asInt(),0,255),std::clamp(b->asInt(),0,255)); auto* idx=v.find("index"); if(idx) return Color::indexed(std::clamp(idx->asInt(),0,255)); auto* rgb=v.find("rgb"); if(rgb&&rgb->isStr()) return Color::named(rgb->asStr()); } return Color::def(); }
void applyJson(const json::Value& root){
if(!root.isObj()){ warnings.push_back("config root not object"); return; }
{ static const std::vector<std::string> known={"bevelStyle","panelPosition","shell","clockFormat","wallpaperPattern","wallpaperColor","panelHeight","bottomPanelHeight","bottomPanel","snapDistance","doubleClickMs","tooltipDelayMs","caretBlinkMs","workspaceCount","bellVisualMs","spacing","padding","effectsEnabled","reducedMotion","dropShadow","popEffect","shadeSlide","menuReveal","smoothScroll","bellAudible","bellVisual","bellOnError","bellSuppressFocused","mouseForwarding","asciiMode","focusFollowsMouse","wallpaperFg","glyphs","windowColors","ttColors","keybindings","colors","uiColors"};
for(auto&kv:*root.asObj()) if(std::find(known.begin(),known.end(),kv.first)==known.end()) warnings.push_back("unknown key: "+kv.first); }
auto getStr=[&](const char* k, std::string& dst){ auto*v=root.find(k); if(v){ if(v->isStr()) dst=v->asStr(); else warnings.push_back(std::string("wrong type: ")+k); } };
auto getInt=[&](const char* k, int& dst){ auto*v=root.find(k); if(v){ if(v->isNum()) dst=v->asInt(); else warnings.push_back(std::string("wrong type: ")+k); } };
auto getBool=[&](const char* k, bool& dst){ auto*v=root.find(k); if(v){ if(v->isBool()) dst=v->asBool(); else warnings.push_back(std::string("wrong type: ")+k); } };
getStr("bevelStyle",bevelStyle); getStr("panelPosition",panelPosition); getStr("shell",shell); getStr("clockFormat",clockFormat); getStr("wallpaperPattern",wallpaperPattern);
getInt("panelHeight",panelHeight); getInt("bottomPanelHeight",bottomPanelHeight); getInt("snapDistance",snapDistance); getInt("doubleClickMs",doubleClickMs); getInt("tooltipDelayMs",tooltipDelayMs); getInt("caretBlinkMs",caretBlinkMs); getInt("workspaceCount",workspaceCount); getInt("bellVisualMs",bellVisualMs); getInt("spacing",spacing);
getBool("bottomPanel",bottomPanel); getBool("effectsEnabled",effectsEnabled); getBool("reducedMotion",reducedMotion); getBool("dropShadow",dropShadow); getBool("popEffect",popEffect); getBool("shadeSlide",shadeSlide); getBool("menuReveal",menuReveal); getBool("smoothScroll",smoothScroll); getBool("bellAudible",bellAudible); getBool("bellVisual",bellVisual); getBool("bellOnError",bellOnError); getBool("bellSuppressFocused",bellSuppressFocused); getBool("mouseForwarding",mouseForwarding); getBool("focusFollowsMouse",focusFollowsMouse); getInt("wallpaperFg",wallpaperFg);
if(auto*v=root.find("wallpaperColor"); v) wallpaperColor=parseColor(*v);
if(auto*v=root.find("asciiMode")) asciiMode=v->asBool(asciiMode);
if(auto*v=root.find("glyphs"); v&&v->isObj()) for(auto&kv:*v->asObj()) if(kv.second.isStr()) glyphs[kv.first]=kv.second.asStr();
if(auto*v=root.find("windowColors"); v&&v->isObj()) for(auto&kv:*v->asObj()){ if(kv.second.isObj()){ WindowColor wc=windowColor(kv.first); if(auto*f=kv.second.find("fg")) wc.fg=parseColor(*f); if(auto*b=kv.second.find("bg")) wc.bg=parseColor(*b); windowColors[kv.first]=wc; } }
if(auto*v=root.find("ttColors"); v&&v->isObj()) for(auto&kv:*v->asObj()) ttColors[kv.first]=parseColor(kv.second);
if(auto*v=root.find("uiColors"); v&&v->isObj()) for(auto&kv:*v->asObj()) uiColors[kv.first]=parseColor(kv.second);
if(auto*v=root.find("keybindings"); v&&v->isObj()) for(auto&kv:*v->asObj()) if(kv.second.isStr()) keybindings[kv.first]=kv.second.asStr();
if(auto*v=root.find("colors"); v&&v->isObj()) for(auto&kv:*v->asObj()) ttColors[kv.first]=parseColor(kv.second);
workspaceCount=std::clamp(workspaceCount,1,8); snapDistance=std::clamp(snapDistance,0,10); panelHeight=std::clamp(panelHeight,1,3);
if(reducedMotion) effectsEnabled=false;
}
bool loadFromFile(const std::string& path, std::string* errOut=nullptr){
std::ifstream in(path); if(!in){ if(errOut) *errOut="cannot open "+path; return false; }
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
json::ParseError pe; auto v=json::parse(content,&pe);
if(!v){ std::string e="JSON error at "+std::to_string(pe.line)+":"+std::to_string(pe.col)+" "+pe.msg; warnings.push_back(e); if(errOut) *errOut=e; return false; }
applyJson(*v); loadedPath=path; return true;
}
bool saveToFile(const std::string& path) const { std::ofstream out(path); if(!out) return false; out<<json::dump(toJson()); return true; }
static std::string findConfigPath(const std::string& explicitPath=""){
if(!explicitPath.empty()) return explicitPath;
if(const char* e=std::getenv("RGUI_CONFIG"); e&&*e) return e;
if(std::filesystem::exists("rgui.env.json")) return "rgui.env.json";
if(std::filesystem::exists(".env.json")) return ".env.json";
std::string home=std::getenv("HOME")?std::getenv("HOME"):"";
std::string xdg=std::getenv("XDG_CONFIG_HOME")?std::getenv("XDG_CONFIG_HOME"):(home+"/.config");
std::string p=xdg+"/rgui/rgui.env.json"; if(std::filesystem::exists(p)) return p;
return "";
}
static Config load(const std::string& explicitPath="", std::string* errOut=nullptr){
Config c=defaults(); std::string p=findConfigPath(explicitPath);
if(!p.empty()) c.loadFromFile(p,errOut); else if(!explicitPath.empty()&&errOut) *errOut="config not found: "+explicitPath;
if(c.asciiMode) c.bevelStyle="ascii";
return c;
}
};
/**
* @brief Read-only convenience view over a Config (may wrap nullptr).
* @details `Theme(const Config*)` stores the pointer; `win(k)` returns the
* semantic WindowColor (built-in defaults when cfg is null); `glyph(k,
* fallback)`; `ascii()` is true for ascii bevel style or asciiMode.
*/
struct Theme{
const Config* cfg=nullptr;
explicit Theme(const Config* c=nullptr):cfg(c){}
WindowColor win(const std::string& k) const { return cfg?cfg->windowColor(k):Config::defaults().windowColor(k); }
std::string glyph(const std::string& k, const std::string& fb="") const { return cfg?cfg->glyph(k,fb):fb; }
bool ascii() const { return cfg&&(cfg->bevelStyle=="ascii"||cfg->asciiMode); }
};
// ---------- Signal ----------
/**
* @brief Minimal type-safe signal: an ordered list of slots.
* @details `connect(fn)` appends a slot and returns its id;
* `disconnect(id)` removes it; `emit(args...)` invokes a snapshot copy of
* the slots in connect order, so slots may connect/disconnect re-entrantly.
* Slots are owned by the Signal; no lifetime management beyond that.
*/
template<typename... Args>
class Signal{
std::vector<std::pair<int,std::function<void(Args...)>>> slots; int nextId=1;
public:
int connect(std::function<void(Args...)> f){ int id=nextId++; slots.push_back({id,std::move(f)}); return id; }
void disconnect(int id){ slots.erase(std::remove_if(slots.begin(),slots.end(),[&](auto& p){return p.first==id;}),slots.end()); }
void emit(Args... a){ auto copy=slots; for(auto& p: copy) if(p.second) p.second(a...); }
};
// ---------- Events ----------
/** @brief Discriminator for Event: keyboard, mouse, focus, resize, timer tick, application-defined custom, bracketed paste, or drag-drop delivery. */
enum class EventType{ Key, Mouse, Focus, Resize, Tick, Custom, Paste, Drop };
/** @brief Logical key identity; Char carries the decoded text in KeyEventData::text. */
enum class KeyCode{ None, Char, Enter, Escape, Tab, Backspace, Delete, Insert, Home, End, PageUp, PageDown, Up, Down, Left, Right, F1,F2,F3,F4,F5,F6,F7,F8,F9,F10,F11,F12 };
/**
* @brief One keyboard event: `code`, UTF-8 `text`, modifier flags, decoded `ch`.
* @details `KeyEventData()` is an empty event; `KeyEventData(KeyCode)` sets
* only the code (used as `Event::makeKey({KeyCode::Escape})`).
* `name()` returns a binding name ("F12", "Delete", "Ctrl+Q", else text)
* for keybinding comparison; `isChar()` is `code == KeyCode::Char`.
*/
struct KeyEventData{ KeyCode code=KeyCode::None; std::string text; bool ctrl=false, alt=false, shift=false; char32_t ch=0;
KeyEventData()=default; KeyEventData(KeyCode c):code(c){}
std::string name() const {
std::string base;
if(code==KeyCode::Tab) base="Tab"; else if(code==KeyCode::Delete) base="Delete"; else if(code==KeyCode::Escape) base="Escape";
else if(code==KeyCode::Enter) base="Enter"; else if(code==KeyCode::Backspace) base="Backspace";
else if(code>=KeyCode::F1&&code<=KeyCode::F12) base="F"+std::to_string((int)code-(int)KeyCode::F1+1);
else if(code==KeyCode::Up) base="Up"; else if(code==KeyCode::Down) base="Down"; else if(code==KeyCode::Left) base="Left"; else if(code==KeyCode::Right) base="Right";
else if(code==KeyCode::Home) base="Home"; else if(code==KeyCode::End) base="End"; else if(code==KeyCode::PageUp) base="PageUp"; else if(code==KeyCode::PageDown) base="PageDown"; else if(code==KeyCode::Insert) base="Insert";
else if(!text.empty()){ base=text; if(ctrl&&base.size()==1) base[0]=(char)std::toupper((unsigned char)base[0]); else if(ch&&base.size()==1&&ctrl) base=std::string(1,(char)std::toupper((unsigned char)ch)); }
else if(ch) base=std::string(1,(char)ch);
std::string out; if(ctrl) out+="Ctrl+"; if(alt) out+="Alt+"; if(shift&&code!=KeyCode::Char) out+="Shift+"; out+=base; return out;
} bool isChar() const { return code==KeyCode::Char; } };
/** @brief Mouse action kind, including hover Enter/Leave and the DragStart/Drag/DragEnd lifecycle. */
enum class MouseKind{ Move, Down, Up, Click, DoubleClick, Wheel, DragStart, Drag, DragEnd, Enter, Leave };
/** @brief One mouse event: `kind`, absolute cell `pos`, `button` (0 left, 1 middle, 2 right), signed `wheelDelta`, modifiers. */
struct MouseEventData{ MouseKind kind=MouseKind::Move; Point pos; int button=0; int wheelDelta=0; bool ctrl=false,alt=false,shift=false; };
/**
* @brief The single event value passed through the whole dispatch pipeline.
* @details Fields: `type`, `handled` (set by a consumer to stop bubbling),
* `customName` (for Custom events and focusIn/focusOut), the active payload
* (`key`, `mouse`, `pasteText`, `newW/newH` for resize, `dt` seconds for
* tick). Factories: `makeKey(k)`, `makeMouse(kind, pos, button)`,
* `makeTick(dt)`, `makeResize(w,h)`, `makePaste(text)`, `makeCustom(name)`.
* Factories set exactly the payload matching the returned type.
*/
struct Event{
EventType type=EventType::Custom; bool handled=false; std::string customName;
KeyEventData key; MouseEventData mouse; std::string pasteText; int newW=0,newH=0; double dt=0; std::string dragType, dragText, dragFile; int dragRow=-1;
static Event makeKey(KeyEventData k){ Event e; e.type=EventType::Key; e.key=k; return e; }
static Event makeMouse(MouseKind k, Point p, int btn=0){ Event e; e.type=EventType::Mouse; e.mouse.kind=k; e.mouse.pos=p; e.mouse.button=btn; return e; }
static Event makeTick(double dt_){ Event e; e.type=EventType::Tick; e.dt=dt_; return e; }
static Event makeResize(int w,int h){ Event e; e.type=EventType::Resize; e.newW=w; e.newH=h; return e; }
static Event makePaste(const std::string& t){ Event e; e.type=EventType::Paste; e.pasteText=t; return e; }
static Event makeCustom(const std::string& n){ Event e; e.type=EventType::Custom; e.customName=n; return e; }
};
// ---------- Canvas ----------
/**
* @brief Double-buffered grid of Cells with a clip stack; the only surface
* widgets draw on. Drawing never touches the real terminal — Application
* diff-renders a Canvas to ANSI.
* @details Construction: `Canvas()` (empty) or `Canvas(w,h)`;
* `resize(w,h)` (re)allocates and resets the clip to the full grid;
* `width()`/`height()`; `clear(style)` fills with spaces in one style.
* Clipping: `pushClip(r)` intersects and saves, `popClip()` restores,
* `clip()` reads, `setClip(r)` replaces (clamped to the grid),
* `inClip(x,y)` tests. All writes respect the clip and the grid bounds.
* Cells: `set(x,y,glyph,style)` / `set(x,y,char,style)` (out-of-bounds and
* out-of-clip writes are silently dropped), `get(x,y)` (borrowed; a shared
* empty cell out of bounds), `getMut(x,y)` (mutable, caller guarantees
* bounds), `data()` exposes the row-major cell vector, `fill(r,glyph,
* style)` in string and char forms.
* Primitives: `drawText(x,y,text,style,maxW)` (UTF-8 codepoints, width 1
* each, stops at newline or maxW), `drawBox(r,style,ascii,filled)`
* (Unicode or ASCII frame; degenerate rects only fill),
* `drawBevel(r,base,raised,ascii)` (light top/left, dark bottom/right;
* inverted when raised=false), `drawInset(...)` (a sunken drawBevel).
* Test/introspection helpers: `textLine(y)` (trailing spaces trimmed),
* `text()` (whole grid, newline-joined), `findText(needle)` -> (x,y) or
* (-1,-1). Invariant: rendering a Canvas never mutates widget state.
*/
class Canvas{
int W=0,H=0; std::vector<Cell> cells; Rect clipRect; std::vector<Rect> clipStack;
public:
Canvas()=default; Canvas(int w,int h){ resize(w,h); }
void resize(int w,int h){ W=std::max(0,w); H=std::max(0,h); cells.assign((size_t)W*H, Cell{}); clipRect={0,0,W,H}; }
int width() const {return W;} int height() const {return H;}
void clear(CellStyle st={}){ for(auto&c:cells){c.ch=" "; c.st=st;} }
void pushClip(Rect r){ clipStack.push_back(clipRect); clipRect=clipRect.intersect(r); }
void popClip(){ if(!clipStack.empty()){ clipRect=clipStack.back(); clipStack.pop_back(); } }
Rect clip() const {return clipRect;}
void setClip(Rect r){ clipRect=r.intersect({0,0,W,H}); }
bool inClip(int x,int y) const { return clipRect.contains(x,y); }
void set(int x,int y,const std::string& ch,CellStyle st={}){ if(x<0||y<0||x>=W||y>=H) return; if(!clipRect.contains(x,y)) return; cells[(size_t)y*W+x]={ch,st}; }
void set(int x,int y,char ch,CellStyle st={}){ set(x,y,std::string(1,ch),st); }
const Cell& get(int x,int y) const { static const Cell empty; if(x<0||y<0||x>=W||y>=H) return empty; return cells[(size_t)y*W+x]; }
Cell& getMut(int x,int y){ static thread_local Cell dummy; if(x<0||y<0||x>=W||y>=H){ dummy=Cell{}; return dummy; } return cells[(size_t)y*W+x]; }
void fill(Rect r, const std::string& ch, CellStyle st){ for(int y=r.y;y<r.bottom();y++) for(int x=r.x;x<r.right();x++) set(x,y,ch,st); }
void fill(Rect r, char ch, CellStyle st){ fill(r,std::string(1,ch),st); }
void drawText(int x,int y,const std::string& text,CellStyle st, int maxW=-1){
int cx=x; size_t i=0;
while(i<text.size()&& (maxW<0||cx-x<maxW)){
// UTF-8 decode one codepoint (best effort, width 1)
unsigned char c=(unsigned char)text[i]; size_t len=1; if((c&0x80)==0) len=1; else if((c&0xE0)==0xC0) len=2; else if((c&0xF0)==0xE0) len=3; else if((c&0xF8)==0xF0) len=4;
if(i+len>text.size()) len=1;
if(text[i]=='\n'){ break; }
set(cx,y,text.substr(i,len),st); cx++; i+=len;
}
}
void drawBox(Rect r, CellStyle st, bool ascii=false, bool filled=true){
if(r.w<2||r.h<2) { if(filled) fill(r," ",st); return; }
if(filled) fill(r," ",st);
std::string tl=ascii?"+":"┌", tr=ascii?"+":"┐", bl=ascii?"+":"└", br=ascii?"+":"┘", hz=ascii?"-":"─", vt=ascii?"|":"│";
for(int x=r.x+1;x<r.right()-1;x++){ set(x,r.y,hz,st); set(x,r.bottom()-1,hz,st); }
for(int y=r.y+1;y<r.bottom()-1;y++){ set(r.x,y,vt,st); set(r.right()-1,y,vt,st); }
set(r.x,r.y,tl,st); set(r.right()-1,r.y,tr,st); set(r.x,r.bottom()-1,bl,st); set(r.right()-1,r.bottom()-1,br,st);
}
void drawBevel(Rect r, CellStyle base, bool raised=true, bool ascii=false){
(void)ascii; if(r.empty()) return; fill(r," ",base);
// Degenerate 1-row / 1-column bevels: top and bottom (or left and
// right) edges would land on the same cells and draw stray "─"/"│"
// lines beside the label (seen on every 1-row button, e.g. a toolbar
// or an "Apply" button). A flat fill is the correct rendering there.
if(r.h<2||r.w<2) return;
Color light=Color::rgb(255,255,255), dark=Color::rgb(40,40,40);
if(!raised) std::swap(light,dark);
CellStyle top=base, left=base, bot=base, rightS=base; top.fg=light; left.fg=light; bot.fg=dark; rightS.fg=dark;
// Use bg shading via fg glyphs on edges: draw edge cells with shade
for(int x=r.x;x<r.right();x++){ auto c=get(x,r.y); CellStyle s=c.st; s.fg=light; if(!raised) s.fg=dark; set(x,r.y,c.ch==" "? "─":c.ch, s); auto c2=get(x,r.bottom()-1); CellStyle s2=c2.st; s2.fg=raised?dark:light; set(x,r.bottom()-1,c2.ch==" "? "─":c2.ch,s2); }
for(int y=r.y;y<r.bottom();y++){ auto c=get(r.x,y); CellStyle s=c.st; s.fg=raised?light:dark; set(r.x,y,c.ch==" "? "│":c.ch,s); auto c2=get(r.right()-1,y); CellStyle s2=c2.st; s2.fg=raised?dark:light; set(r.right()-1,y,c2.ch==" "? "│":c2.ch,s2); }
}
void drawInset(Rect r, CellStyle base, bool ascii=false){ drawBevel(r,base,false,ascii); }
std::string textLine(int y) const { std::string s; for(int x=0;x<W;x++) s+=get(x,y).ch;
while(!s.empty()&&s.back()==' ') s.pop_back();
return s; }
std::string text() const { std::string s; for(int y=0;y<H;y++){ if(y) s+="\n"; s+=textLine(y);} return s; }
std::pair<int,int> findText(const std::string& needle) const { for(int y=0;y<H;y++){ std::string line; for(int x=0;x<W;x++) line+=get(x,y).ch; auto p=line.find(needle); if(p!=std::string::npos) return {(int)p,y}; } return {-1,-1}; }
const std::vector<Cell>& data() const { return cells; }
};
/// @brief Alias used where a Canvas acts as the screen buffer.
using ScreenBuffer = Canvas;
/**
* @brief ANSI SGR sequence switching from `prev` to `st` (full reset first).
* @details Emits nothing when the styles are equal and `force` is false.
* Colours are emitted as truecolor (38;2/48;2), 256-index (38;5/48;5), or
* the default-colour codes (39/49), plus bold/dim/underline/reverse/italic.
*/
inline std::string ansiForStyle(const CellStyle& st, const CellStyle& prev, bool force){
std::string out;
auto colEsc=[&](const Color& c, bool fg)->std::string{
if(c.isDefault()) return fg?"\033[39m":"\033[49m";
if(c.r>=0){ char buf[64]; std::snprintf(buf,sizeof(buf),"\033[%d;2;%d;%d;%dm", fg?38:48, c.r,c.g,c.b); return buf; }
if(c.idx>=0){ char buf[32]; std::snprintf(buf,sizeof(buf),"\033[%d;5;%dm", fg?38:48, c.idx); return buf; }
return "";
};
if(force||!(st==prev)){
out+="\033[0m";
if(st.bold) out+="\033[1m";
if(st.dim) out+="\033[2m";
if(st.underline) out+="\033[4m";
if(st.reverse) out+="\033[7m";
if(st.italic) out+="\033[3m";
out+=colEsc(st.fg,true); out+=colEsc(st.bg,false);
}
return out;
}
/**
* @brief Minimal ANSI byte stream turning `prev` into `cur`.
* @details On a size change, repaints every cell (cursor-home relative
* moves). Otherwise emits only changed cells, coalescing adjacent changes
* without redundant cursor moves, and ends with a style reset. Equal
* buffers produce an empty string — asserted by the test suite.
*/
inline int glyphDisplayWidth(const std::string& ch){ if(ch.size()<2) return 1; unsigned char c=(unsigned char)ch[0]; char32_t cp=0; if((c&0xF0)==0xF0&&ch.size()>=4) cp=((c&7)<<18)|(((unsigned char)ch[1]&63)<<12)|(((unsigned char)ch[2]&63)<<6)|((unsigned char)ch[3]&63); else if((c&0xE0)==0xE0&&ch.size()>=3) cp=((c&15)<<12)|(((unsigned char)ch[1]&63)<<6)|((unsigned char)ch[2]&63); else return 1; if(cp>=0x1100&&((cp<=0x115F)||(cp>=0x2E80&&cp<=0xA4CF)||(cp>=0xAC00&&cp<=0xD7A3)||(cp>=0xF900&&cp<=0xFAFF)||(cp>=0xFE30&&cp<=0xFE4F)||(cp>=0xFF00&&cp<=0xFF60)||(cp>=0x1F300&&cp<=0x1FAFF)||(cp>=0x20000))) return 2; return 1; }
inline std::string diffRender(const Canvas& cur, const Canvas& prev){
if(cur.width()!=prev.width()||cur.height()!=prev.height()){
std::string out="\033[H"; CellStyle last; bool first=true;
for(int y=0;y<cur.height();y++){ char buf[32]; std::snprintf(buf,sizeof(buf),"\033[%d;1H",y+1); out+=buf; for(int x=0;x<cur.width();x++){ auto&c=cur.get(x,y); out+=ansiForStyle(c.st,last,first); last=c.st; first=false; out+=c.ch; } }
out+="\033[0m"; return out;
}
std::string out; CellStyle last; bool haveLast=false; int cx=-1, cy=-1;
for(int y=0;y<cur.height();y++) for(int x=0;x<cur.width();x++){
auto&c=cur.get(x,y); auto&p=prev.get(x,y); int gw=glyphDisplayWidth(c.ch); if(c==p){ if(gw==2) x++; continue; }
if(cx!=x||cy!=y){ char buf[32]; std::snprintf(buf,sizeof(buf),"\033[%d;%dH",y+1,x+1); out+=buf; }
out+=ansiForStyle(c.st,last,!haveLast); last=c.st; haveLast=true; out+=c.ch; cx=x+gw; cy=y; if(gw==2) x++;
}
if(!out.empty()) out+="\033[0m";
return out;
}
// ---------- Terminal RAII ----------
/**
* @brief RAII owner of the real terminal. Non-copyable.
* @details `init()` (false when stdin is not a TTY) saves termios, enters
* raw mode, switches to the alternate screen (1049), enables mouse
* (1002+1003+1006), focus events (1004) and bracketed paste (2004), and
* hides the cursor. `restore()` emits the inverse sequences and restores
* termios; the destructor calls restore(), so exit, exceptions, and early
* returns all leave a sane terminal. `isActive()` reports raw state.
* `size()` returns (cols, rows) from TIOCGWINSZ, falling back to
* $COLUMNS/$LINES then 80x24. `bell()` writes one BEL byte; `writeStr(s)`
* writes raw output unbuffered. `onResize` is reserved for embedders that
* forward SIGWINCH themselves; Application polls size() instead.
*/
class Terminal{
termios orig{}; bool active=false; bool hasOrig=false;
public:
std::function<void(int,int)> onResize;
Terminal()=default; ~Terminal(){ restore(); }
Terminal(const Terminal&)=delete; Terminal& operator=(const Terminal&)=delete;
bool init(){
if(!isatty(STDIN_FILENO)) return false;
if(tcgetattr(STDIN_FILENO,&orig)!=0) return false;
hasOrig=true;
termios raw=orig; raw.c_iflag&=~(BRKINT|ICRNL|INPCK|ISTRIP|IXON); raw.c_oflag&=~OPOST; raw.c_lflag&=~(ECHO|ICANON|IEXTEN|ISIG); raw.c_cflag|=CS8; raw.c_cc[VMIN]=0; raw.c_cc[VTIME]=0;
tcsetattr(STDIN_FILENO,TCSANOW,&raw); active=true;
std::string initSeq="\033[?1049h\033[?1002h\033[?1006h\033[?1003h\033[?1004h\033[?2004h\033[?25l";
(void)!write(STDOUT_FILENO,initSeq.data(),initSeq.size());
return true;
}
void restore(){
if(active){ std::string s="\033[?25h\033[?2004l\033[?1004l\033[?1003l\033[?1002l\033[?1006l\033[?1049l\033[0m\n"; (void)!write(STDOUT_FILENO,s.data(),s.size()); active=false; }
if(hasOrig) tcsetattr(STDIN_FILENO,TCSANOW,&orig);
}
bool isActive() const { return active; }
std::pair<int,int> size() const {
winsize ws{}; if(ioctl(STDOUT_FILENO,TIOCGWINSZ,&ws)==0&&ws.ws_col>0) return {std::max(1,(int)ws.ws_col),std::max(1,(int)ws.ws_row)};
const char* c=getenv("COLUMNS"); const char* r=getenv("LINES"); return {std::max(1,c?atoi(c):80), std::max(1,r?atoi(r):24)};
}
void bell(){ const char b='\a'; (void)!write(STDOUT_FILENO,&b,1); }
void writeStr(const std::string& s){ if(!s.empty()) (void)!write(STDOUT_FILENO,s.data(),s.size()); }
};
// ---------- InputParser ----------
/** @brief A parsed resize notification: `isResize` plus the new size `w`/`h`; `ev` is unused for resizes. */
struct ParsedEvent{ Event ev; bool isResize=false; int w=0,h=0; };
/**
* @brief Stateful decoder from raw stdin bytes to Events.
* @details `feed(data)` appends to an internal buffer and returns every
* complete event: printable UTF-8 (Char), Enter/Tab/Backspace, control
* keys (Ctrl+letter), CSI/SS3 arrows, Home/End, Insert/Delete, PgUp/PgDn,
* F1–F12 (with ;5 Ctrl / ;3 Alt modifiers where present), SGR mouse
* (button, Drag/Move discrimination, wheel as wheelDelta, modifiers),
* focus in/out (CSI I/O), Alt+char, lone Esc, and bracketed paste
* (200~...201~ -> one Paste event). Incomplete sequences are buffered
* across feed() calls, never dropped or misdecoded. `split(s, delim)` is
* the static parameter-list helper. The parser is pure: the same feed
* path serves real stdin and test-injected raw bytes.
*/
class InputParser{
std::string buf; bool inPaste=false; std::string pasteBuf; bool mousePressed=false;
static constexpr size_t kMaxBuf=65536; static constexpr size_t kMaxPaste=1048576; static constexpr size_t kMaxCsi=4096;
public:
// Flush a pending lone ESC (call after a poll timeout, ~25-50ms with no bytes).
std::vector<Event> flushPending(){
std::vector<Event> out;
if(inPaste) return out;
if(buf=="\033"){ KeyEventData k; k.code=KeyCode::Escape; out.push_back(Event::makeKey(k)); buf.clear(); }
else if(buf.size()>kMaxBuf) buf.clear();
return out;
}
std::vector<Event> flushEsc(){ return flushPending(); }
bool hasPendingEsc() const { return buf=="\033"; }
std::vector<Event> feed(const std::string& data){
std::vector<Event> out; buf+=data;
size_t i=0;
while(i<buf.size()){
if(inPaste){
if(pasteBuf.size()>kMaxPaste){ pasteBuf.clear(); inPaste=false; }
auto end=buf.find("\033[201~",i);
if(end==std::string::npos){ // wait for more, keep remainder
// consume all but possible partial suffix
size_t keep=std::min<size_t>(buf.size()-i,6);
pasteBuf+=buf.substr(i, buf.size()-i-keep); buf=buf.substr(buf.size()-keep); return out;
} else { pasteBuf+=buf.substr(i,end-i); out.push_back(Event::makePaste(pasteBuf)); pasteBuf.clear(); inPaste=false; i=end+6; continue; }
}
char c=buf[i];
if(c=='\033'){
if(i+1>=buf.size()) break;
if(buf[i+1]=='['){
// find final byte
size_t j=i+2; while(j<buf.size()&&!((buf[j]>='@'&&buf[j]<='~'))) j++;
if(j>=buf.size()){ if(buf.size()-i>kMaxCsi){ i=buf.size(); } break; }
std::string seq=buf.substr(i, j-i+1);
std::string params=buf.substr(i+2, j-(i+2));
char fin=buf[j];
if(seq=="\033[200~"){ inPaste=true; i=j+1; continue; }
if(fin=='M'||fin=='m'){
// SGR mouse: [<b;x;yM
if(params.size()&¶ms[0]=='<'){
auto parts=split(params.substr(1),';');
if(parts.size()>=3){ int b=atoi(parts[0].c_str()), x=atoi(parts[1].c_str())-1, y=atoi(parts[2].c_str())-1;
Event e; e.type=EventType::Mouse; e.mouse.pos={x,y};
if((b&64)!=0){ e.mouse.kind=MouseKind::Wheel; e.mouse.wheelDelta=(b&1)?-1:1; }
else if(fin=='M'){ if(b&32){ e.mouse.kind=((b&3)!=3||mousePressed)?MouseKind::Drag:MouseKind::Move; } else { e.mouse.kind=MouseKind::Down; mousePressed=true; } }
else { e.mouse.kind=MouseKind::Up; mousePressed=false; }
e.mouse.button=b&3; e.mouse.ctrl=(b&16)!=0; e.mouse.alt=(b&8)!=0; e.mouse.shift=(b&4)!=0;
out.push_back(e);
}
}
i=j+1; continue;
}
if(fin=='I'){ Event e; e.type=EventType::Focus; e.customName="focusIn"; out.push_back(e); i=j+1; continue; }
if(fin=='O'){ Event e; e.type=EventType::Focus; e.customName="focusOut"; out.push_back(e); i=j+1; continue; }
// keys: numeric modifier param (Ps;Pm) for every final byte
KeyEventData k; bool handledSeq=true;
{ auto parts=split(params,';'); if(parts.size()>=2){ int mod=atoi(parts[1].c_str())-1; if(mod>0){ if(mod&1) k.shift=true; if(mod&2) k.alt=true; if(mod&4) k.ctrl=true; } } }
if(fin=='A') k.code=KeyCode::Up; else if(fin=='B') k.code=KeyCode::Down; else if(fin=='C') k.code=KeyCode::Right; else if(fin=='D') k.code=KeyCode::Left;
else if(fin=='H') k.code=KeyCode::Home; else if(fin=='F') k.code=KeyCode::End;
else if(fin=='Z'){ k.code=KeyCode::Tab; k.shift=true; }
else if(fin=='~'){
int n=atoi(params.c_str());
if(n==2) k.code=KeyCode::Insert; else if(n==3) k.code=KeyCode::Delete; else if(n==5) k.code=KeyCode::PageUp; else if(n==6) k.code=KeyCode::PageDown;
else if(n==15) k.code=KeyCode::F5; else if(n==17) k.code=KeyCode::F6; else if(n==18) k.code=KeyCode::F7; else if(n==19) k.code=KeyCode::F8; else if(n==20) k.code=KeyCode::F9; else if(n==21) k.code=KeyCode::F10; else if(n==23) k.code=KeyCode::F11; else if(n==24) k.code=KeyCode::F12;
else if(n==1||n==7) k.code=KeyCode::Home; else if(n==4||n==8) k.code=KeyCode::End; else handledSeq=false;
} else if(fin=='P') k.code=KeyCode::F1; else if(fin=='Q') k.code=KeyCode::F2; else if(fin=='R') k.code=KeyCode::F3; else if(fin=='S') k.code=KeyCode::F4;
else handledSeq=false;
if(handledSeq){ out.push_back(Event::makeKey(k)); }
i=j+1; continue;
} else if(buf[i+1]=='O'){
if(i+2>=buf.size()) break;
char f=buf[i+2]; KeyEventData k;
if(f=='P') k.code=KeyCode::F1; else if(f=='Q') k.code=KeyCode::F2; else if(f=='R') k.code=KeyCode::F3; else if(f=='S') k.code=KeyCode::F4;
else if(f=='A') k.code=KeyCode::Up; else if(f=='B') k.code=KeyCode::Down; else if(f=='C') k.code=KeyCode::Right; else if(f=='D') k.code=KeyCode::Left;
else if(f=='H') k.code=KeyCode::Home; else if(f=='F') k.code=KeyCode::End; else { i+=3; continue; }
out.push_back(Event::makeKey(k)); i+=3; continue;
} else {
// Alt+char or Esc alone: peek if more data
if(i+1<buf.size()&&buf[i+1]!='\033'){ KeyEventData k; k.alt=true; if(buf[i+1]=='\t'){ k.code=KeyCode::Tab; } else if(buf[i+1]=='\r'||buf[i+1]=='\n'){ k.code=KeyCode::Enter; } else { k.code=KeyCode::Char; k.ch=(unsigned char)buf[i+1]; k.text=std::string(1,buf[i+1]); } out.push_back(Event::makeKey(k)); i+=2; continue; }
KeyEventData k; k.code=KeyCode::Escape; out.push_back(Event::makeKey(k)); i+=1; continue;
}
} else if(c=='\r'||c=='\n'){ KeyEventData k; k.code=KeyCode::Enter; out.push_back(Event::makeKey(k)); i++; }
else if(c=='\t'){ KeyEventData k; k.code=KeyCode::Tab; out.push_back(Event::makeKey(k)); i++; }
else if(c==0x7f||c==0x08){ KeyEventData k; k.code=KeyCode::Backspace; out.push_back(Event::makeKey(k)); i++; }
else if((unsigned char)c<0x20){ KeyEventData k; k.ctrl=true; k.code=KeyCode::Char; k.ch=c; k.text=std::string(1,(char)('a'+c-1)); if(c==0x11) k.text="q"; if(c==0x03) k.text="c"; out.push_back(Event::makeKey(k)); i++; }
else {
// UTF-8 char
unsigned char uc=(unsigned char)c; size_t len=1; if((uc&0xE0)==0xC0) len=2; else if((uc&0xF0)==0xE0) len=3; else if((uc&0xF8)==0xF0) len=4;
if(i+len>buf.size()) break;
KeyEventData k; k.code=KeyCode::Char; k.text=buf.substr(i,len); // decode ch
if(len==1) k.ch=uc; else if(len==2&&i+1<buf.size()) k.ch=((uc&0x1F)<<6)| (buf[i+1]&0x3F); else k.ch='?';
if(k.text=="~"){ k.code=KeyCode::Char; }
out.push_back(Event::makeKey(k)); i+=len;
}
}
buf.erase(0,i);
return out;
}
static std::vector<std::string> split(const std::string& s,char d){ std::vector<std::string> o; std::string cur; for(char c: s){ if(c==d){o.push_back(cur);cur.clear();} else cur+=c;} o.push_back(cur); return o; }
};
// ---------- Widget base ----------
/**
* @brief Base class of every UI element; owns its children.
* @details COORDINATE CONVENTION: `bounds` is ALWAYS relative to the
* parent widget (roots such as windows/panels/desktop have no parent,
* so their bounds are screen cells). absoluteBounds() sums the parent
* chain. Layout code must therefore assign children coordinates starting
* at (0,0) of the parent - assigning screen coordinates to a child
* double-offsets it (the classic bug this convention prevents).
* Public state: `bounds` (relative to parent), `parent` (borrowed,
* set by addChild), `visible`, `enabled`, `focusable`, `focused`, `hovered`,
* `id`, `tooltip`, `tabOrder`, constraint sizes `minSize`/`prefSize`/
* `maxSize` and layout weight `flex`, plus `styleOverride`/
* `hasStyleOverride` to replace the themed style wholesale.
* Signals: `onClick`, `onFocus`, `onBlur`, `onKeySignal`, `onMouseSignal`
* (emitted in addition to the virtual handlers).
* Virtual interface: `draw(Canvas&)` paints inside absoluteBounds();
* `onEvent(Event&)` dispatches to `onKey(KeyEventData&)` /
* `onMouse(MouseEventData&)`, each returning true when handled (the base
* onMouse emits onClick on Down); `measure()` returns the preferred size
* (default prefSize); `layout()` lays out children (default: recurse);
* `hitTest(abs)` returns the deepest visible child containing the point,
* else this; `drawTree(Canvas&)` clips to this widget, draws, then draws
* children in order. The destructor is virtual; children are destroyed
* with the parent.
* Non-virtual helpers: `setEnabled(bool)`, `setVisible(bool)`,
* `setTooltip(string)`, `setFocusPolicy(FocusPolicy)` (None disables
* focusability), `absoluteBounds()` (bounds accumulated up the parent
* chain), `addChild(unique_ptr<Widget>)` -> borrowed child pointer (sets
* parent, takes ownership), `emplace<T>(args...)` -> borrowed T*,
* `children()` (mutable and const views of the owned child list),
* `findById(id)` (depth-first, nullptr when absent), `containsAbs(p)`.
* Protected: `children_` storage and `themeStyle(theme, windowClass)`
* (themed style honouring styleOverride, disabled greying, focus bold).
*/
class Widget{
public:
Rect bounds; Widget* parent=nullptr; bool visible=true, enabled=true, focusable=false, focused=false, hovered=false;
std::string id, tooltip; int tabOrder=0; Size minSize{1,1}, prefSize{10,1}, maxSize{10000,10000}; int flex=0;
CellStyle styleOverride; bool hasStyleOverride=false;
Signal<> onClick, onFocus, onBlur; Signal<KeyEventData> onKeySignal; Signal<MouseEventData> onMouseSignal;
virtual ~Widget()=default;
virtual void draw(Canvas& c){ (void)c; }
virtual bool onCapture(Event&){ return false; }
virtual bool onEvent(Event& e){ bool r=false; if(e.type==EventType::Key) r=onKey(e.key); else if(e.type==EventType::Mouse) r=onMouse(e.mouse); if(r) e.handled=true; return r; }
virtual bool onKey(KeyEventData&){ return false; }
virtual bool onMouse(MouseEventData& m){ if(m.kind==MouseKind::Down&&enabled) onClick.emit(); (void)m; return false; }
virtual Size measure(){ return prefSize; }
virtual void layout(){ for(auto& ch: children_) ch->layout(); }
void setEnabled(bool v){ enabled=v; } void setVisible(bool v){ visible=v; } void setTooltip(const std::string& t){ tooltip=t; }
enum class FocusPolicy{ None, Tab, Click, Strong }; FocusPolicy focusPolicy=FocusPolicy::None;
void setFocusPolicy(FocusPolicy p){ focusPolicy=p; focusable=(p!=FocusPolicy::None); }
Rect absoluteBounds() const { Rect r=bounds; const Widget* p=parent; while(p){ r.x+=p->bounds.x; r.y+=p->bounds.y; p=p->parent; } return r; }
Widget* addChild(std::unique_ptr<Widget> ch){ ch->parent=this; children_.push_back(std::move(ch)); return children_.back().get(); }
template<typename T, typename... A> T* emplace(A&&... a){ auto up=std::make_unique<T>(std::forward<A>(a)...); T* raw=up.get(); addChild(std::move(up)); return raw; }
const std::vector<std::unique_ptr<Widget>>& children() const { return children_; }
bool removeChild(Widget* w){ auto it=std::find_if(children_.begin(),children_.end(),[&](auto& c){return c.get()==w;}); if(it==children_.end()) return false; (*it)->parent=nullptr; children_.erase(it); return true; }
void clearChildren(){ for(auto& c: children_) c->parent=nullptr; children_.clear(); }
Widget* findById(const std::string& wid){ if(id==wid) return this; for(auto&c:children_){ if(auto*f=c->findById(wid)) return f; } return nullptr; }
bool containsAbs(Point p) const { return absoluteBounds().contains(p); }
virtual Widget* hitTest(Point abs){ if(!visible) return nullptr; for(int i=(int)children_.size()-1;i>=0;--i){ if(auto*h=children_[(size_t)i]->hitTest(abs)) return h; } if(absoluteBounds().contains(abs)) return this; return nullptr; }
virtual Rect drawClipRect() const { return absoluteBounds(); }
virtual void drawTree(Canvas& c){ if(!visible) return; Rect abs=drawClipRect(); c.pushClip(abs); draw(c); for(auto&ch:children_) ch->drawTree(c); c.popClip(); }
protected:
std::vector<std::unique_ptr<Widget>> children_;
CellStyle themeStyle(const Theme& th, const std::string& wc="grey") const { if(hasStyleOverride) return styleOverride; auto w=th.win(wc); CellStyle s; s.fg=w.fg; s.bg=w.bg; if(!enabled){ s.fg=Color::rgb(90,90,90); } if(focused) s.bold=true; s.bg=w.bg; s.fg=enabled?w.fg:Color::rgb(90,90,90); return s; }
};
// ---------- Layout containers ----------
/**
* @brief Word-wrap `t` to width `w` cells, splitting on explicit newlines first.
* @details Words longer than `w` are hard-split. Returns one entry per
* visual line; returns an empty vector when w <= 0. Used by Label,
* TextWidget, and other text widgets for both measure() and draw().
*/
inline std::vector<std::string> wrapText(const std::string& t, int w){
std::vector<std::string> lines; if(w<=0) return lines; std::istringstream iss(t); std::string word, line;
// simple: split by \n then wrap
std::vector<std::string> paras; std::string cur; for(char c: t){ if(c=='\n'){paras.push_back(cur);cur.clear();} else cur+=c; } paras.push_back(cur);
for(auto¶: paras){ std::istringstream ps(para); line.clear(); while(ps>>word){ if((int)(line.size()+word.size()+1)>w&&!line.empty()){ lines.push_back(line); line=word; } else { if(!line.empty()) line+=" "; line+=word; } if((int)line.size()>w){ while((int)line.size()>w){ lines.push_back(line.substr(0,(size_t)w)); line=line.substr((size_t)w);} } } lines.push_back(line); }
return lines;
}
/** @brief Truncate `s` to at most `w` cells, replacing the tail with "..." when anything was cut; returns "" for w <= 0. Byte-based (glyphs are width-1 in this framework). */
inline std::string ellipsize(const std::string& s, int w){ if(w<=0) return ""; if((int)s.size()<=w) return s; if(w<=3) return s.substr(0,(size_t)w); return s.substr(0,(size_t)w-3)+"..."; }
/**
* @brief Horizontal layout container; draws nothing itself.
* @details `layout()` gives non-flex children their measure() width and
* distributes the remaining width to flex children by weight, clamping
* every child to its min/max width; children fill the container height.
* `spacing` cells are inserted between children. Invisible children are
* skipped. Content wider than the box overflows to the right (clipped by
* drawTree), never producing negative sizes.
*/
struct HBox : Widget{
int spacing=1;
void layout() override {
int x=0; int avail=bounds.w; int totalFlex=0; int fixed=0;
for(auto&c:children_){ if(!c->visible) continue; if(c->flex>0) totalFlex+=c->flex; else fixed+=c->measure().w; }
fixed+= spacing*(int)children_.size();
int flexSpace=std::max(0, avail-fixed);
for(auto&c:children_){ if(!c->visible) continue; int w=c->measure().w; if(c->flex>0&&totalFlex>0) w=flexSpace*c->flex/totalFlex; w=std::clamp(w,c->minSize.w,c->maxSize.w); c->bounds={x,0,w,bounds.h}; x+=w+spacing; c->layout(); }
}
void draw(Canvas&) override {}
};
/** @brief Vertical layout container; the height-wise mirror of HBox. `layout()` distributes height by measure()/flex with min/max clamping; children fill the width. */
struct VBox : Widget{
int spacing=0;
void layout() override {
int y=0; int avail=bounds.h; int totalFlex=0; int fixed=0;
for(auto&c:children_){ if(!c->visible) continue; if(c->flex>0) totalFlex+=c->flex; else fixed+=c->measure().h; }
int flexSpace=std::max(0, avail-fixed);
for(auto&c:children_){ if(!c->visible) continue; int h=c->measure().h; if(c->flex>0&&totalFlex>0) h=flexSpace*c->flex/totalFlex; h=std::clamp(h,c->minSize.h,c->maxSize.h); c->bounds={0,y,bounds.w,h}; y+=h+spacing; c->layout(); }
}
};
/** @brief Grid layout container: children fill equal cells in row-major order. `cols` columns (forced >= 1); cell sizes are clamped >= 0 so tiny bounds never yield negative child sizes. */
struct Grid : Widget{
int cols=2; int spacing=1;
void layout() override { if(cols<=0) cols=1; int rows=(int)(children_.size()+cols-1)/cols; if(rows==0) return; int cw=bounds.w/cols, ch=bounds.h/rows; for(size_t i=0;i<children_.size();i++){ int cx=(int)i%cols, cy=(int)i/cols; children_[i]->bounds={cx*cw, cy*ch, std::max(0,cw-spacing), std::max(0,ch)}; children_[i]->layout(); } }
};
/** @brief Invisible flex filler: `Spacer(flexWeight)` takes a share of free space in an HBox/VBox. Alias SpacerWidget. */
struct Spacer : Widget{ Spacer(int f=1){ flex=f; prefSize={1,1}; } };
/** @brief Stacking container: `layout()` gives every child the container's full bounds, so later children draw over earlier ones. */
struct Layered : Widget{ void layout() override { for(auto&c:children_){ c->bounds={0,0,bounds.w,bounds.h}; c->layout(); } } };
// ---------- Leaf widgets ----------
/**
* @brief Static text label. Fields: `text`, `align` (0 left, 1 centre,
* 2 right), `wrap` (word-wrap instead of ellipsize), `windowClass`
* (semantic colour used via `cfg`).
* @details `Label(text)` is non-focusable with preferred width = text
* length. `measure()` reports one line, or the wrapped line count when
* wrap is set. `draw()` fills its rect in the themed colour (greyed when
* disabled) and draws the text aligned/ellipsized or wrapped.
*/
struct Label : Widget{
std::string text; int align=0; bool wrap=false; std::string windowClass="grey"; const Config* cfg=nullptr;
explicit Label(std::string t=""):text(std::move(t)){ prefSize={(int)text.size(),1}; focusable=false; }
Size measure() override { if(wrap) return {10, (int)wrapText(text, std::max(1,bounds.w)).size()}; return {(int)text.size(),1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170); if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } if(hasStyleOverride) s=styleOverride; if(!enabled) s.fg=Color::rgb(90,90,90);
c.fill(a," ",s);
if(wrap){ auto lines=wrapText(text, a.w); for(size_t i=0;i<lines.size()&&(int)i<a.h;i++) c.drawText(a.x,a.y+(int)i,lines[i],s,a.w); }
else { std::string t=ellipsize(text,a.w); int x=a.x; if(align==1) x=a.x+std::max(0,(a.w-(int)t.size())/2); if(align==2) x=a.x+std::max(0,a.w-(int)t.size()); c.drawText(x,a.y,t,s,a.w); }
}
};
/**
* @brief Read-only multi-line text view (alias Text). Fields: `text`,
* `scroll` (first visible wrapped line).
* @details `draw()` fills a paper-white rect and draws wrapped lines from
* `scroll`. `onKey()` scrolls: Up/Down by one line, PgUp/PgDn by five,
* clamped at the top; returns false for other keys.
*/
struct TextWidget : Widget{
std::string text; const Config* cfg=nullptr; int scroll=0;
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); s.bg=cfg?cfg->uiColor("menuPaper",Color::rgb(245,245,245)):Color::rgb(245,245,245); if(hasStyleOverride) s=styleOverride; c.fill(a," ",s); auto lines=wrapText(text,a.w); for(int i=0;i<a.h;i++){ int idx=i+scroll; if(idx<(int)lines.size()) c.drawText(a.x,a.y+i,lines[idx],s,a.w); } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up) scroll=std::max(0,scroll-1); else if(k.code==KeyCode::Down) scroll++; else if(k.code==KeyCode::PageDown) scroll+=5; else if(k.code==KeyCode::PageUp) scroll=std::max(0,scroll-5); else return false; return true; }
};
using Text = TextWidget;
/**
* @brief Clickable button with a raised bevel that inverts while down
* (alias TextButton). Fields: `label`, `pressed` (mouse currently down),
* `toggled` (latched state), `latch` (stay down on click), `windowClass`.
* @details `PushButton(label)` is Strong-focusable; `measure()` is label
* width + 4. Emits `onPressed` (and base onClick) on mouse-Up after a Down
* on the button, or on Enter/Space; `draw()` renders centred text, greyed
* when disabled, bold when focused, bevel raised unless pressed/toggled.
* Ignores input entirely while disabled.
*/
struct PushButton : Widget{
std::string label; bool pressed=false, toggled=false, latch=false; const Config* cfg=nullptr; std::string windowClass="grey";
Signal<> onPressed;
explicit PushButton(std::string l=""):label(std::move(l)){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={(int)label.size()+4,1}; }
Size measure() override { return {(int)label.size()+4,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle base; if(cfg){ auto w=cfg->windowColor(windowClass); base.fg=w.fg; base.bg=w.bg; } else { base.fg=Color::rgb(0,0,0); base.bg=Color::rgb(170,170,170);} if(hasStyleOverride) base=styleOverride; if(!enabled) base.fg=Color::rgb(90,90,90); bool down=pressed||toggled; c.drawBevel(a,base,!down, cfg&&cfg->asciiMode); std::string t=ellipsize(label, std::max(0,a.w-2)); int x=a.x+std::max(0,(a.w-(int)t.size())/2)+(down?0:0); CellStyle ts=base; if(focused) ts.bold=true; if(down) ts.dim=true; c.drawText(x,a.y+(a.h>1?a.h/2:0),t,ts,a.w); if(focused&&a.h>0){ /* focus indicated by bold */ } }
bool onMouse(MouseEventData& m) override { if(!enabled) return false; if(m.kind==MouseKind::Down){ pressed=true; return true; } if(m.kind==MouseKind::Up){ bool was=pressed; pressed=false; if(was){ if(latch) toggled=!toggled; onPressed.emit(); onClick.emit(); } return true; } return false; }
bool onKey(KeyEventData& k) override { if(!enabled) return false; if(k.code==KeyCode::Enter||(k.isChar()&&k.text==" ")){ if(latch) toggled=!toggled; onPressed.emit(); onClick.emit(); return true; } return false; }
};
using TextButton = PushButton;
/** @brief PushButton whose label is `icon` or `icon + " " + label`. Alias IconTextButton. */
struct IconButton : PushButton{ IconButton(std::string icon,std::string lab=""):PushButton(lab.empty()?icon:icon+" "+lab){} };
using IconTextButton = IconButton;
/**
* @brief Directional PushButton (▲▼◀▶). `ArrowButton(dir)` with
* dir 0=up, 1=down, 2=left, 3=right. Emits `onStep` in addition to
* onPressed whenever clicked by mouse or key.
*/
struct ArrowButton : PushButton{
int dir=0; //0 up 1 down 2 left 3 right
Signal<> onStep;
ArrowButton(int d=1):PushButton(d==0?"▲":d==1?"▼":d==2?"◀":"▶"),dir(d){}
bool onMouse(MouseEventData& m) override { bool r=PushButton::onMouse(m); if(m.kind==MouseKind::Up&&pressed==false) onStep.emit(); return r; }
bool onKey(KeyEventData& k) override { bool r=PushButton::onKey(k); if(r) onStep.emit(); return r; }
};
/** @brief Latching PushButton (stays down until pressed again). Alias BoolButton. */
struct ToggleButton : PushButton{ ToggleButton(std::string l=""):PushButton(l){ latch=true; } };
using BoolButton = ToggleButton;
/**
* @brief Two-state "[✓] label" control. Fields: `label`, `checked`.
* @details `CheckBox(label, initial)`; mouse Down or Enter/Space flips
* `checked` and emits `onChanged(checked)`; draws "[x]" instead of "[✓]"
* in ascii mode; ignores input while disabled.
*/
struct CheckBox : Widget{
std::string label; bool checked=false; const Config* cfg=nullptr; Signal<bool> onChanged;
CheckBox(std::string l="",bool v=false):label(std::move(l)),checked(v){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={(int)label.size()+4,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170); if(hasStyleOverride) s=styleOverride; if(!enabled) s.fg=Color::rgb(90,90,90); if(focused) s.bold=true; std::string chk=cfg?cfg->glyph("check","✓"):"✓"; std::string box=checked?("["+chk+"]"):"[ ]"; if(cfg&&cfg->asciiMode) box=checked?"[x]":"[ ]"; c.drawText(a.x,a.y,ellipsize(box+" "+label,a.w),s,a.w); }
bool onMouse(MouseEventData& m) override { if(!enabled) return false; if(m.kind==MouseKind::Down){ checked=!checked; onChanged.emit(checked); onClick.emit(); return true; } return false; }
bool onKey(KeyEventData& k) override { if(!enabled) return false; if(k.code==KeyCode::Enter||(k.isChar()&&k.text==" ")){ checked=!checked; onChanged.emit(checked); return true; } return false; }
};
/**
* @brief "(●) label" radio item. Fields: `label`, `selected`, `groupId`.
* @details Click or Enter/Space sets `selected` and emits `onSelected`;
* exclusivity within a group is RadioGroup's job, not this widget's.
*/
struct RadioButton : Widget{
std::string label; bool selected=false; int groupId=0; const Config* cfg=nullptr; Signal<> onSelected;
RadioButton(std::string l="",int g=0):label(std::move(l)),groupId(g){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170); if(hasStyleOverride) s=styleOverride; if(focused) s.bold=true; std::string rad=cfg?cfg->glyph("radio","●"):"●"; c.drawText(a.x,a.y,ellipsize(std::string(selected?("("+rad+") "):"( ) ")+label,a.w),s,a.w); }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down&&enabled){ selected=true; onSelected.emit(); return true; } return false; }
bool onKey(KeyEventData& k) override { if((k.code==KeyCode::Enter||(k.isChar()&&k.text==" "))&&enabled){ selected=true; onSelected.emit(); return true; } return false; }
};
/**
* @brief Owns a vertical stack of RadioButtons with single selection.
* @details `addRadio(label)` creates, appends, and wires a button and
* returns it (borrowed); `select(radio)` enforces exclusivity and updates
* `selectedIndex` (-1 before any selection); `layout()` stacks children
* one row each.
*/
struct RadioGroup : Widget{
std::vector<RadioButton*> buttons; int selectedIndex=-1;
RadioButton* addRadio(const std::string& l){ auto* r=emplace<RadioButton>(l); r->onSelected.connect([this,r](){ select(r); }); buttons.push_back(r); return r; }
void select(RadioButton* r){ for(size_t i=0;i<buttons.size();i++){ buttons[i]->selected=(buttons[i]==r); if(buttons[i]==r) selectedIndex=(int)i; } }
void layout() override { int y=0; for(auto&c:children_){ c->bounds={0,y,bounds.w,1}; y+=1; c->layout(); } }
};
/**
* @brief Single-line text editor with sunken inset and reversed-caret.
* @details Fields: `text`, `cursor` (byte offset), `selStart`/`hasSel`
* (selection anchor for Ctrl+A), `password` (masks display with '*'),
* `placeholder` (dim text shown when empty and unfocused). Signals:
* `onChanged(text)` after every mutation, `onEnter` on Enter.
* Methods: `EditBox(initial)` (cursor at end); `setText(t)` (cursor to
* end, emits); `pushUndo()` (snapshots text, capped at 50, internal);
* `onKey()`: Ctrl+Z undo, Ctrl+A select-all, Enter, Backspace/Delete,
* Left/Right/Home/End cursor motion, printable insert — all no-ops
* returning false while disabled; `onEvent()` additionally handles
* bracketed Paste events by inserting at the cursor when focused.
* `draw()` scrolls horizontally to keep the cursor visible. While it
* holds global focus it receives all keys including hotkeys (API.md §4).
*/
struct EditBox : Widget{
std::string text; size_t cursor=0, selStart=0; bool hasSel=false; bool password=false; std::string placeholder; const Config* cfg=nullptr;
std::vector<std::string> undoStack; Signal<std::string> onChanged; Signal<> onEnter;
EditBox(std::string t=""):text(std::move(t)),cursor(text.size()){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={20,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); std::string disp=password?std::string(text.size(),'*'):text; if(disp.empty()&&!focused){ CellStyle ph=s; ph.dim=true; c.drawText(a.x+1,a.y,ellipsize(placeholder,std::max(0,a.w-2)),ph); }
else { // horizontal scroll to keep cursor visible
int inner=std::max(1,a.w-2); size_t off=0; if((int)cursor>=inner) off=cursor-(size_t)inner+1;
std::string view=disp.substr(off,(size_t)inner); c.drawText(a.x+1,a.y,view,s,inner);
if(focused){ size_t cx=std::min<size_t>(cursor-off,(size_t)inner-1); if(a.x+1+(int)cx<a.right()-1){ auto cell=c.get(a.x+1+(int)cx,a.y); CellStyle cs=cell.st; cs.reverse=true; c.set(a.x+1+(int)cx,a.y,cell.ch.empty()?" ":cell.ch,cs); } }
}
}
void pushUndo(){ undoStack.push_back(text); if(undoStack.size()>50) undoStack.erase(undoStack.begin()); }
bool onKey(KeyEventData& k) override {
if(!enabled) return false;
if(k.ctrl&&k.text=="z"){ if(!undoStack.empty()){ text=undoStack.back(); undoStack.pop_back(); cursor=std::min(cursor,text.size()); onChanged.emit(text);} return true; }
if(k.ctrl&&k.text=="a"){ selStart=0; hasSel=true; cursor=text.size(); return true; }
if(k.code==KeyCode::Enter){ onEnter.emit(); return true; }
if(k.code==KeyCode::Backspace){ if(cursor>0){ pushUndo(); text.erase(cursor-1,1); cursor--; onChanged.emit(text);} return true; }
if(k.code==KeyCode::Delete){ if(cursor<text.size()){ pushUndo(); text.erase(cursor,1); onChanged.emit(text);} return true; }
if(k.code==KeyCode::Left){ if(cursor>0) cursor--; return true; }
if(k.code==KeyCode::Right){ if(cursor<text.size()) cursor++; return true; }
if(k.code==KeyCode::Home){ cursor=0; return true; }
if(k.code==KeyCode::End){ cursor=text.size(); return true; }
if(k.isChar()&&!k.ctrl&&!k.alt){ pushUndo(); text.insert(cursor,k.text); cursor+=k.text.size(); // cursor counts bytes approx
if(cursor>text.size()) cursor=text.size();
onChanged.emit(text); return true; }
return false;
}
bool onEvent(Event& e) override { if(e.type==EventType::Paste&&focused){ std::string t=e.pasteText.substr(0,1048576); pushUndo(); text.insert(cursor,t); cursor+=t.size(); onChanged.emit(text); e.handled=true; return true; } return Widget::onEvent(e); }
void setText(const std::string& t){ text=t; cursor=text.size(); onChanged.emit(text); }
};
/**
* @brief Multi-line text editor (alias TextView).
* @details Fields: `lines` (one string per line, never empty), caret
* `cx` (byte column) / `cy` (line), `scrollY` (first visible line),
* `showLineNumbers` (4-cell gutter), `wordWrap` (draw wraps every
* visual line), `modified` (dirty flag cleared by setText).
* Methods: `getText()` joins lines with '\n'; `setText(t)` splits,
* resets caret/scroll, clears modified; `onKey()`: arrows/Home/End/
* PgUp/PgDn move (crossing line boundaries), Enter splits the line,
* Backspace deletes or joins with the previous line, Delete, Tab
* (two spaces), printable insert — mutations set modified and emit
* `onChanged`, and scrollY is maintained so the caret stays visible
* (no scrolling is computed while bounds.h is 0). `draw()` renders the
* inset, line numbers, and a reversed caret cell when focused.
*/
struct TextEditor : Widget{
std::vector<std::string> lines{""}; int cx=0, cy=0, scrollY=0; bool showLineNumbers=true, wordWrap=false, modified=false; const Config* cfg=nullptr; Signal<> onChanged;
TextEditor(){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={40,10}; }
std::string getText() const { std::string s; for(size_t i=0;i<lines.size();i++){ if(i) s+="\n"; s+=lines[i]; } return s; }
void ensureValid(){ if(lines.empty()) lines.push_back(""); cy=std::clamp(cy,0,(int)lines.size()-1); cx=std::clamp(cx,0,(int)lines[(size_t)cy].size()); scrollY=std::clamp(scrollY,0,std::max(0,(int)lines.size()-1)); }
void setText(const std::string& t){ lines.clear(); std::string cur; for(char c: t){ if(c=='\n'){lines.push_back(cur);cur.clear();} else cur+=c; } lines.push_back(cur); cx=cy=0; scrollY=0; modified=false; }
void draw(Canvas& c) override { ensureValid(); Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); Rect inner=a.h>2?a.inset(1,1,1,1):a.inset(1,0,1,0);
int gutter=showLineNumbers?4:0; int vrow=0; for(int li=scrollY; li<(int)lines.size()&&vrow<inner.h; li++){ std::vector<std::string> segs; if(wordWrap){ segs=wrapText(lines[(size_t)li],std::max(1,inner.w-gutter)); if(segs.empty()) segs={""}; } else segs={lines[(size_t)li]}; for(size_t si=0;si<segs.size()&&vrow<inner.h;si++,vrow++){ int y=inner.y+vrow; if(showLineNumbers&&si==0){ CellStyle gs=s; gs.dim=true; char buf[16]; std::snprintf(buf,sizeof(buf),"%3d ",li+1); c.drawText(inner.x,y,buf,gs); } c.drawText(inner.x+gutter,y, wordWrap?segs[si]:ellipsize(segs[si], inner.w-gutter),s, inner.w-gutter); if(focused&&li==cy){ int wv=std::max(1,inner.w-gutter); int segIdx=wordWrap? cx/wv:0; if((int)si==std::min(segIdx,(int)segs.size()-1)){ int col=wordWrap? cx%wv:cx; int px=inner.x+gutter+std::min(col, std::max(0,inner.w-gutter-1)); if(px<inner.right()){ auto cell=c.get(px,y); CellStyle cs=cell.st; cs.reverse=true; c.set(px,y,cell.ch.empty()?" ":cell.ch,cs); } } } } }
}
bool onKey(KeyEventData& k) override {
if(!enabled) return false;
ensureValid();
if(k.code==KeyCode::Up){ cy=std::max(0,cy-1); cx=std::min(cx,(int)lines[(size_t)cy].size()); }
else if(k.code==KeyCode::Down){ cy=std::min((int)lines.size()-1,cy+1); cx=std::min(cx,(int)lines[(size_t)cy].size()); }
else if(k.code==KeyCode::Left){ if(cx>0) cx--; else if(cy>0){cy--; cx=(int)lines[(size_t)cy].size();} }
else if(k.code==KeyCode::Right){ if(cx<(int)lines[(size_t)cy].size()) cx++; else if(cy+1<(int)lines.size()){cy++;cx=0;} }
else if(k.code==KeyCode::Home) cx=0; else if(k.code==KeyCode::End) cx=(int)lines[(size_t)cy].size();
else if(k.code==KeyCode::PageDown){ cy=std::min((int)lines.size()-1,cy+10); } else if(k.code==KeyCode::PageUp){ cy=std::max(0,cy-10); }
else if(k.code==KeyCode::Enter){ std::string rest=lines[(size_t)cy].substr((size_t)cx); lines[(size_t)cy]=lines[(size_t)cy].substr(0,(size_t)cx); lines.insert(lines.begin()+cy+1,rest); cy++; cx=0; modified=true; onChanged.emit(); }
else if(k.code==KeyCode::Backspace){ if(cx>0){ lines[(size_t)cy].erase((size_t)cx-1,1); cx--; modified=true; onChanged.emit(); } else if(cy>0){ cx=(int)lines[(size_t)cy-1].size(); lines[(size_t)cy-1]+=lines[(size_t)cy]; lines.erase(lines.begin()+cy); cy--; modified=true; onChanged.emit(); } }
else if(k.code==KeyCode::Delete){ if(cx<(int)lines[(size_t)cy].size()){ lines[(size_t)cy].erase((size_t)cx,1); modified=true; onChanged.emit(); } }
else if(k.code==KeyCode::Tab){ lines[(size_t)cy].insert((size_t)cx," "); cx+=2; modified=true; onChanged.emit(); }
else if(k.isChar()&&!k.ctrl&&!k.alt){ lines[(size_t)cy].insert((size_t)cx,k.text); cx+=(int)k.text.size(); modified=true; onChanged.emit(); }
else return false;
if(bounds.h>0){ int vis=std::max(1,bounds.h-2); if(cy<scrollY) scrollY=cy; if(cy>=scrollY+vis) scrollY=cy-vis+1; scrollY=std::clamp(scrollY,0,std::max(0,(int)lines.size()-vis)); }
return true;
}
};
using TextView = TextEditor;
/**
* @brief Integer value with ▲▼ steppers. Fields: `value`, `minV`, `maxV`, `step`.
* @details `NumericStepper(value, min, max)`; `setValue(v)` clamps to
* [minV, maxV] and emits `onChanged(value)` only on change. Keys: Up/Down
* step, digits append decimal digits, Backspace divides by ten. Mouse:
* click on the trailing arrow cells steps, wheel steps by wheelDelta.
*/
struct NumericStepper : Widget{
int value=0, minV=0, maxV=100, step=1; const Config* cfg=nullptr; Signal<int> onChanged;
NumericStepper(int v=0,int mn=0,int mx=100):value(v),minV(mn),maxV(mx){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={10,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); c.drawText(a.x+1,a.y,std::to_string(value),s); if(a.w>4){ c.drawText(a.right()-3,a.y,"▲",s); c.drawText(a.right()-2,a.y,"▼",s);} if(focused){ CellStyle f=s; f.bold=true; c.drawText(a.x+1,a.y,std::to_string(value),f);} }
void setValue(int v){ int nv=std::clamp(v,minV,maxV); if(nv!=value){ value=nv; onChanged.emit(value);} }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up){ setValue(value+step); return true;} if(k.code==KeyCode::Down){ setValue(value-step); return true;} if(k.isChar()&&std::isdigit((unsigned char)k.text[0])){ setValue(value*10+(k.text[0]-'0')); return true;} if(k.code==KeyCode::Backspace){ setValue(value/10); return true;} return false; }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); if(m.pos.x>=a.right()-3) setValue(value+step); else if(m.pos.x>=a.right()-4) setValue(value-step); return true;} if(m.kind==MouseKind::Wheel){ setValue(value+m.wheelDelta*step); return true;} return false; }
};
/**
* @brief Draggable range slider, horizontal or vertical.
* @details Fields: `value`, `minV`, `maxV`, `vertical`.
* `Slider(value, min, max, vertical)`. `setFromPos(point)` maps a mouse
* position to a value (internal, used by click/drag). Mouse Down/Drag
* sets from position, wheel steps by one; arrow keys step by one; all
* paths clamp to [minV, maxV] and emit `onChanged(value)` on change.
* `draw()` renders a ░ track with █ fill and handle.
*/
struct Slider : Widget{
int value=0, minV=0, maxV=100; bool vertical=false; const Config* cfg=nullptr; Signal<int> onChanged;
Slider(int v=0,int mn=0,int mx=100,bool vert=false):value(v),minV(mn),maxV(mx),vertical(vert){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={20,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170); if(hasStyleOverride) s=styleOverride; double frac=maxV>minV?double(value-minV)/(maxV-minV):0;
if(!vertical){ c.fill(a,"░",s); int pos=a.x+(int)(frac*std::max(0,a.w-1)); int fillW=(int)(frac*a.w); CellStyle f=s; f.bg=Color::rgb(34,120,60); for(int x=a.x;x<a.x+fillW;x++) c.set(x,a.y,"█",f); CellStyle h=s; h.bold=true; c.set(pos,a.y,"█",h); }
else { for(int y=a.y;y<a.bottom();y++) c.set(a.x,y,"░",s); int pos=a.bottom()-1-(int)(frac*std::max(0,a.h-1)); CellStyle f=s; f.bg=Color::rgb(34,120,60); for(int y=pos;y<a.bottom();y++) c.set(a.x,y,"█",f); c.set(a.x,pos,"█",s); }
if(focused){ /* bold handle */ } }
void setFromPos(Point p){ Rect a=absoluteBounds(); double f=0; if(!vertical&&a.w>1) f=double(p.x-a.x)/(a.w-1); else if(vertical&&a.h>1) f=1.0-double(p.y-a.y)/(a.h-1); f=std::clamp(f,0.0,1.0); int nv=minV+(int)std::round(f*(maxV-minV)); if(nv!=value){value=nv; onChanged.emit(value);} }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down||m.kind==MouseKind::Drag){ setFromPos(m.pos); return true;} if(m.kind==MouseKind::Wheel){ value=std::clamp(value+m.wheelDelta,minV,maxV); onChanged.emit(value); return true;} return false; }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Left||k.code==KeyCode::Down){ value=std::clamp(value-1,minV,maxV); onChanged.emit(value); return true;} if(k.code==KeyCode::Right||k.code==KeyCode::Up){ value=std::clamp(value+1,minV,maxV); onChanged.emit(value); return true;} return false; }
};
/**
* @brief Read-only completion bar (alias Gauge). Fields: `value`, `maxV`,
* `label` (empty label draws "NN%").
* @details `ProgressBar(value, max)`; `draw()` fills proportionally to
* value/maxV (values above maxV simply fill the bar) and centres the
* percentage or label. No input handling.
*/
struct ProgressBar : Widget{
int value=0, maxV=100; std::string label; const Config* cfg=nullptr;
ProgressBar(int v=0,int mx=100):value(v),maxV(mx){}
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(255,255,255); s.bg=cfg?cfg->uiColor("progressTrack",Color::rgb(80,80,80)):Color::rgb(80,80,80); if(hasStyleOverride) s=styleOverride; c.fill(a,"░",s); double f=maxV>0?double(value)/maxV:0; int w=(int)(f*a.w); CellStyle fstyle=s; fstyle.bg=cfg?cfg->uiColor("progressFill",Color::rgb(34,120,60)):Color::rgb(34,120,60); for(int x=0;x<w;x++) c.set(a.x+x,a.y,"█",fstyle); std::string t=label.empty()?(std::to_string((int)(f*100))+"%"):label; CellStyle ts=s; ts.bg=Color::def(); int tx=a.x+std::max(0,(a.w-(int)t.size())/2); c.drawText(tx,a.y,ellipsize(t,a.w),ts,a.w); }
};
using Gauge = ProgressBar;
/**
* @brief Line or bar chart over one or more data series.
* @details Fields: `series` (samples per series), `legend` (names drawn
* dim at top), `colors` (cycled per series), `visibleSeries` (per-series
* hide flags; missing entries mean visible), `barMode` (bars instead of
* connected ▄ line points). `draw()` scales to the maximum sample
* across visible series (at least 1) inside a sunken inset; no input.
*/
struct Graph : Widget{
std::vector<std::vector<double>> series; std::vector<std::string> legend; std::vector<Color> colors{Color::rgb(220,40,40),Color::rgb(40,80,220),Color::rgb(40,200,80)}; std::vector<bool> visibleSeries; bool barMode=false; const Config* cfg=nullptr;
Graph(){ prefSize={30,8}; }
void draw(Canvas& c) override { if(cfg) colors={cfg->ttColor("Red"),cfg->ttColor("Blue"),cfg->ttColor("Green"),cfg->ttColor("Orange")}; Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,1,1,1); if(inner.empty()) return; if(colors.empty()) colors.push_back(Color::rgb(220,40,40)); double mx=1; for(auto&s:series) for(double v:s) mx=std::max(mx,v); for(size_t si=0;si<series.size();si++){ if(si<visibleSeries.size()&&!visibleSeries[si]) continue; CellStyle st; st.fg=colors[si%colors.size()]; st.bg=bg.bg;
if(barMode){ for(size_t i=0;i<series[si].size()&&(int)i<inner.w;i++){ int h=(int)(series[si][i]/mx*inner.h); for(int y=0;y<h;y++) c.set(inner.x+(int)i, inner.bottom()-1-y, "█", st); } }
else { for(size_t i=0;i<series[si].size()&&(int)i<inner.w;i++){ if(colors.empty()) colors.push_back(Color::rgb(220,40,40)); int y=inner.bottom()-1-(int)(series[si][i]/mx*(inner.h-1)); c.set(inner.x+(int)i,y,"▄",st); if(i>0){ int py=inner.bottom()-1-(int)(series[si][i-1]/mx*(inner.h-1)); int steps=std::abs(y-py); for(int s2=0;s2<=steps;s2++){ int yy=py+(y>py?s2:-s2); if(yy>=inner.y&&yy<inner.bottom()) c.set(inner.x+(int)i,yy,"▄",st); } } } }
}
if(cfg&&!series.empty()&&colors.size()<3){ /* colours may come from ttColors */ }
if(!legend.empty()&&a.h>2){ std::string leg; for(size_t i=0;i<legend.size();i++){ if(i) leg+=" "; leg+=legend[i]; } CellStyle ls=bg; ls.dim=true; c.drawText(inner.x, inner.y, ellipsize(leg,inner.w), ls, inner.w); }
}
};
/**
* @brief Period scrollbar with arrow ends and a proportional thumb
* (alias HScrollBar; orientation is by constructor, not type).
* @details Fields: `value` (first visible item), `maxV` (total items),
* `page` (visible items), `vertical`. `ScrollBar(vertical)`.
* `setValue(v)` clamps to [0, maxV-page] and emits `onChanged(value)` on
* change. `draw()` renders ▲/▼ (or ◀/▶) ends and a █ thumb sized
* page/maxV. Mouse: wheel steps 3, clicking an arrow steps 1, clicking
* or dragging the track jumps proportionally.
*/
struct ScrollBar : Widget{
int value=0, maxV=100, page=10; bool vertical=true; const Config* cfg=nullptr; Signal<int> onChanged;
ScrollBar(bool vert=true):vertical(vert){ prefSize=vert?Size{1,10}:Size{10,1}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=Color::rgb(170,170,170); s.fg=Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride;
if(vertical){ if(a.h<1) return; c.set(a.x,a.y,cfg?cfg->glyph("up","▲"):"▲",s); if(a.h>1) c.set(a.x,a.bottom()-1,cfg?cfg->glyph("down","▼"):"▼",s); int trackH=std::max(0,a.h-2); int thumbH=std::max(1, maxV>0? trackH*std::max(1,page)/std::max(1,maxV):trackH); int range=std::max(0,maxV-page); int thumbPos= range>0? (trackH-thumbH)*value/range:0; for(int y=0;y<trackH;y++){ bool thumb=y>=thumbPos&&y<thumbPos+thumbH; c.set(a.x,a.y+1+y, thumb?"█":"░", s); } }
else { if(a.w<1) return; c.set(a.x,a.y,cfg?cfg->glyph("left","◀"):"◀",s); if(a.w>1) c.set(a.right()-1,a.y,cfg?cfg->glyph("right","▶"):"▶",s); int trackW=std::max(0,a.w-2); int thumbW=std::max(1, maxV>0? trackW*std::max(1,page)/std::max(1,maxV):trackW); int range=std::max(0,maxV-page); int thumbPos= range>0? (trackW-thumbW)*value/range:0; for(int x=0;x<trackW;x++){ bool thumb=x>=thumbPos&&x<thumbPos+thumbW; c.set(a.x+1+x,a.y, thumb?"█":"░", s); } }
}
void setValue(int v){ int nv=std::clamp(v,0,std::max(0,maxV-page)); if(nv!=value){ value=nv; onChanged.emit(value);} }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); if(m.kind==MouseKind::Wheel){ setValue(value+m.wheelDelta*3); return true; } if(m.kind==MouseKind::Down||m.kind==MouseKind::Drag){ if(vertical){ if(m.pos.y==a.y) setValue(value-1); else if(m.pos.y==a.bottom()-1) setValue(value+1); else { int trackH=std::max(1,a.h-2); double f=double(m.pos.y-(a.y+1))/trackH; setValue((int)(f*maxV)); } } else { if(m.pos.x==a.x) setValue(value-1); else if(m.pos.x==a.right()-1) setValue(value+1); else { int trackW=std::max(1,a.w-2); double f=double(m.pos.x-(a.x+1))/trackW; setValue((int)(f*maxV)); } } return true; } return false; }
};
using HScrollBar = ScrollBar;
/**
* @brief Single-selection list in a sunken inset.
* @details Fields: `items`, `selected` (-1 = none), `scroll` (first
* visible row). Signals: `onSelected(index)` on any selection change,
* `onActivated(index)` on Enter or double-click.
* Methods: `ensureVisible()` scrolls the selection into view;
* `sortItems(asc)` sorts items in place; `onKey()`: Up/Down/PgUp/PgDn/
* Home/End move, Enter activates, a printable character jumps to the
* next item starting with it (typeahead); `onMouse()`: wheel scrolls,
* Down selects the clicked row, DoubleClick activates. `draw()`
* highlights the selected row in blue (bold when focused).
*/
struct ListBox : Widget{
std::vector<std::string> items; int selected=-1, scroll=0; const Config* cfg=nullptr; Signal<int> onSelected; Signal<int> onActivated;
ListBox(){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={20,6}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,0,1,0); for(int row=0;row<inner.h;row++){ int idx=scroll+row; if(idx>=(int)items.size()) break; CellStyle s=bg; if(idx==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} if(focused&&idx==selected) s.bold=true; c.fill({inner.x,inner.y+row,inner.w,1}," ",s); c.drawText(inner.x,inner.y+row,ellipsize(items[(size_t)idx],inner.w),s,inner.w); } }
void ensureVisible(){ if(selected<scroll) scroll=selected; int h=std::max(1,bounds.h); if(selected>=scroll+h) scroll=selected-h+1; if(scroll<0) scroll=0; }
bool onKey(KeyEventData& k) override { if(items.empty()) return false; if(k.code==KeyCode::Up){ selected=std::max(0,(selected<0?0:selected-1)); ensureVisible(); onSelected.emit(selected); return true;} if(k.code==KeyCode::Down){ selected=std::min((int)items.size()-1,selected+1); ensureVisible(); onSelected.emit(selected); return true;} if(k.code==KeyCode::PageDown){ selected=std::min((int)items.size()-1,selected+10); ensureVisible(); onSelected.emit(selected); return true;} if(k.code==KeyCode::PageUp){ selected=std::max(0,selected-10); ensureVisible(); onSelected.emit(selected); return true;} if(k.code==KeyCode::Home){ selected=0; ensureVisible(); return true;} if(k.code==KeyCode::End){ selected=(int)items.size()-1; ensureVisible(); return true;} if(k.code==KeyCode::Enter){ if(selected>=0) onActivated.emit(selected); return true;} if(k.isChar()&&!k.ctrl){ char ch=std::tolower((unsigned char)k.text[0]); for(size_t i=0;i<items.size();i++){ if(!items[i].empty()&&std::tolower((unsigned char)items[i][0])==ch){ selected=(int)i; ensureVisible(); onSelected.emit(selected); return true; } } } return false; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); Rect inner=a.inset(1,0,1,0); if(m.kind==MouseKind::Wheel){ scroll=std::clamp(scroll+m.wheelDelta,0,std::max(0,(int)items.size()-inner.h)); return true;} if(m.kind==MouseKind::Down){ int idx=scroll+(m.pos.y-inner.y); if(idx>=0&&idx<(int)items.size()){ bool dbl=false; (void)dbl; selected=idx; onSelected.emit(selected); return true; } } if(m.kind==MouseKind::DoubleClick){ if(selected>=0) onActivated.emit(selected); return true; } return false; }
void sortItems(bool asc=true){ std::sort(items.begin(),items.end(),[&](auto&x,auto&y){return asc?x<y:x>y;}); }
};
/**
* @brief Grid of selectable cells (OpenTTD WWT_MATRIX).
* @details Fields: `cols`, `rows`, `selected` (row-major index),
* `cells` (default text per cell), `cellDraw` (optional custom painter
* called as cellDraw(canvas, cellRect, index, style) instead of text).
* Arrow keys and mouse Down move the selection (clamped to the grid)
* and emit `onSelected(index)`; `draw()` highlights the selected cell.
*/
struct Matrix : Widget{
int cols=3, rows=3, selected=0; std::vector<std::string> cells; std::function<void(Canvas&,Rect,int,CellStyle)> cellDraw; const Config* cfg=nullptr; Signal<int> onSelected;
Matrix(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,1,1,1); if(inner.empty()||cols<=0||rows<=0) return; int cw=inner.w/cols, ch=inner.h/rows; if(cw<=0||ch<=0) return; for(int r=0;r<rows;r++) for(int col=0;col<cols;col++){ int idx=r*cols+col; Rect cr{inner.x+col*cw, inner.y+r*ch, cw, ch}; CellStyle s=bg; if(idx==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} c.fill(cr," ",s); if(cellDraw) cellDraw(c,cr,idx,s); else if(idx<(int)cells.size()) c.drawText(cr.x,cr.y,ellipsize(cells[(size_t)idx],cr.w),s,cr.w); } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Left) selected=std::max(0,selected-1); else if(k.code==KeyCode::Right) selected=std::min(cols*rows-1,selected+1); else if(k.code==KeyCode::Up) selected=std::max(0,selected-cols); else if(k.code==KeyCode::Down) selected=std::min(cols*rows-1,selected+cols); else return false; onSelected.emit(selected); return true; }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); Rect inner=a.inset(1,1,1,1); int cw=inner.w/std::max(1,cols), ch=inner.h/std::max(1,rows); if(cw>0&&ch>0){ int col=(m.pos.x-inner.x)/cw, row=(m.pos.y-inner.y)/ch; if(col>=0&&col<cols&&row>=0&&row<rows){ selected=row*cols+col; onSelected.emit(selected); return true; } } } return false; }
};
/**
* @brief Data table with clickable, sortable column headers.
* @details Fields: `headers`, `rows` (string cells, ragged rows are
* tolerated), `colWidths` (default 12 per column), `selected`, `scroll`,
* `sortCol` (-1 unsorted), `sortAsc`. `sortBy(col)` sorts, toggling
* direction when the same column is repeated. Keys: Up/Down move (with
* scrolling), Enter emits `onSelected(row)`. Mouse: wheel scrolls,
* header click sorts, row click selects, DoubleClick emits onSelected.
* `draw()` shows a bold header with a ▲/▼ sort marker.
*/
struct Table : Widget{
std::vector<std::string> headers; std::vector<std::vector<std::string>> rows; std::vector<int> colWidths; int selected=0, scroll=0, sortCol=-1; bool sortAsc=true; const Config* cfg=nullptr; Signal<int> onSelected;
Table(){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={40,8}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,0,1,0); if(inner.h<2) return;
// header
CellStyle hs; hs.bg=Color::rgb(170,170,170); hs.fg=Color::rgb(0,0,0); hs.bold=true; c.fill({inner.x,inner.y,inner.w,1}," ",hs); int x=inner.x; for(size_t i=0;i<headers.size();i++){ int w= i<colWidths.size()?colWidths[i]:12; std::string h=headers[i]; if((int)i==sortCol) h+=(sortAsc?" ▲":" ▼"); c.drawText(x,inner.y,ellipsize(h,w),hs,w); x+=w+1; if(x>=inner.right()) break; }
for(int r=0;r<inner.h-1;r++){ int idx=scroll+r; if(idx>=(int)rows.size()) break; CellStyle s=bg; if(idx==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} c.fill({inner.x,inner.y+1+r,inner.w,1}," ",s); int cx=inner.x; for(size_t col=0;col<rows[(size_t)idx].size()&&col<headers.size();col++){ int w= col<colWidths.size()?colWidths[col]:12; c.drawText(cx,inner.y+1+r,ellipsize(rows[(size_t)idx][col],w),s,w); cx+=w+1; if(cx>=inner.right()) break; } }
}
void sortBy(int col){ if(sortCol==col) sortAsc=!sortAsc; else {sortCol=col; sortAsc=true;} std::sort(rows.begin(),rows.end(),[&](auto&x,auto&y){ std::string a=col<(int)x.size()?x[(size_t)col]:"", b=col<(int)y.size()?y[(size_t)col]:""; return sortAsc?a<b:a>b; }); }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up){ selected=std::max(0,selected-1); if(selected<scroll) scroll=selected; return true;} if(k.code==KeyCode::Down){ selected=std::min((int)rows.size()-1,selected+1); if(selected>=scroll+std::max(1,bounds.h-3)) scroll++; return true;} if(k.code==KeyCode::Enter){ onSelected.emit(selected); return true;} return false; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); Rect inner=a.inset(1,0,1,0); if(m.kind==MouseKind::Wheel){ scroll=std::clamp(scroll+m.wheelDelta,0,std::max(0,(int)rows.size()-1)); return true;} if(m.kind==MouseKind::Down){ if(m.pos.y==inner.y){ int x=inner.x; for(size_t i=0;i<headers.size();i++){ int w=i<colWidths.size()?colWidths[i]:12; if(m.pos.x>=x&&m.pos.x<x+w){ sortBy((int)i); return true; } x+=w+1; } } else { int idx=scroll+(m.pos.y-inner.y-1); if(idx>=0&&idx<(int)rows.size()){ selected=idx; onSelected.emit(selected); return true; } } } if(m.kind==MouseKind::DoubleClick){ onSelected.emit(selected); return true;} return false; }
};
/**
* @brief Dropdown selector (alias Dropdown). Fields: `items`, `selected`,
* `open` (dropdown list visible), `editable` (reserved for text entry
* variants), signals `onSelected(index)`, `onTextChanged(text)`.
* @details `text()` returns the selected item or "". Keys: Down opens
* then moves, Up moves, Enter opens/commits (committing emits
* onSelected and closes), Escape closes without emitting. Mouse Down
* toggles; clicking a row of the open list selects, emits, and closes.
* The open list is drawn below the widget (up to 6 rows).
*/
struct ComboBox : Widget{
std::vector<std::string> items; int selected=0; bool open=false, editable=false; const Config* cfg=nullptr; Signal<int> onSelected; Signal<std::string> onTextChanged;
ComboBox(){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={20,1}; }
std::string text() const { return selected>=0&&selected<(int)items.size()?items[(size_t)selected]:""; }
Rect dropdownRect() const { Rect a=absoluteBounds(); return {a.x,a.bottom(),a.w,std::min(6,(int)items.size())}; }
Rect drawClipRect() const override { Rect a=absoluteBounds(); if(!open) return a; Rect dd=dropdownRect(); return {std::min(a.x,dd.x),std::min(a.y,dd.y),std::max(a.right(),dd.right())-std::min(a.x,dd.x),std::max(a.bottom(),dd.bottom())-std::min(a.y,dd.y)}; }
Widget* hitTest(Point abs) override { if(!visible) return nullptr; if(open&&dropdownRect().contains(abs)) return this; return Widget::hitTest(abs); }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); std::string t=text(); c.drawText(a.x+1,a.y,ellipsize(t,std::max(0,a.w-4)),s); c.drawText(a.right()-2,a.y,"▼",s); if(open){ Rect dd{a.x,a.bottom(),a.w,std::min(6,(int)items.size())}; CellStyle ds; ds.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); ds.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); c.drawBox(dd,ds,cfg&&cfg->asciiMode); for(size_t i=0;i<items.size()&&(int)i<dd.h- (dd.h>1?0:0);i++){ CellStyle is=ds; if((int)i==selected){ is.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); is.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} if((int)i<dd.h) c.drawText(dd.x+1,dd.y+(int)i,ellipsize(items[i],dd.w-2),is,dd.w-2); } } }
bool onKey(KeyEventData& k) override { if(items.empty()){ if(k.code==KeyCode::Escape){open=false; return true;} return false; } selected=std::clamp(selected,0,(int)items.size()-1); if(k.code==KeyCode::Down){ if(!open) open=true; else selected=std::min((int)items.size()-1,selected+1); return true;} if(k.code==KeyCode::Up){ selected=std::max(0,selected-1); return true;} if(k.code==KeyCode::Enter){ if(open){ open=false; onSelected.emit(selected);} else open=true; return true;} if(k.code==KeyCode::Escape){ open=false; return true;} return false; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); if(m.kind==MouseKind::Down){ if(open){ Rect dd{a.x,a.bottom(),a.w,std::min(6,(int)items.size())}; if(dd.contains(m.pos)){ int idx=m.pos.y-dd.y; if(idx>=0&&idx<(int)items.size()){ selected=idx; onSelected.emit(selected);} open=false; return true; } } open=!open; return true; } return false; }
};
using Dropdown = ComboBox;
/**
* @brief Flat themed background surface. `draw()` fills the rect with the
* `windowClass` colour (or styleOverride). `layout()` gives every child
* the panel's full bounds — combine with HBox/VBox inside for real layout.
*/
struct Panel : Widget{ const Config* cfg=nullptr; std::string windowClass="grey"; void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } else { s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170);} if(hasStyleOverride) s=styleOverride; c.fill(a," ",s); } void layout() override { for(auto&ch:children_){ ch->bounds={0,0,bounds.w,bounds.h}; ch->layout(); } } };
/** @brief Panel drawn sunken (drawInset) instead of flat. */
struct InsetPanel : Panel{ void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } else { s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(200,200,200);} if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); } };
/** @brief Panel with a boxed border and an optional `title` on the top edge. */
struct Frame : Panel{ std::string title; void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } else { s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170);} if(hasStyleOverride) s=styleOverride; c.drawBox(a,s,cfg&&cfg->asciiMode); if(!title.empty()&&a.w>4) c.drawText(a.x+2,a.y,ellipsize(title,a.w-4),s,a.w-4); } };
/** @brief Do-nothing placeholder widget (WWT_EMPTY). SpacerWidget aliases Spacer. */
struct Empty : Widget{}; using SpacerWidget = Spacer;
/**
* @brief Scrollable viewport over one content widget.
* @details Fields: `vbar` (owned ScrollBar, deleted in the destructor),
* `scrollY`/`scrollX` (X reserved; only Y scrolls), `content` (borrowed,
* set with `setContent(w)` — also add w as a child so it draws).
* `layout()` offsets content by -scrollY and reserves the right column
* for the bar. Wheel scrolls by 3 lines and syncs the bar. draw() itself
* is empty: content and bar draw as children via drawTree().
*/
struct ScrollView : Widget{
ScrollBar* vbar=nullptr; int scrollY=0, scrollX=0; int scrollTarget=0; Widget* content=nullptr; const Config* cfg=nullptr;
ScrollView(){ auto bar=std::make_unique<ScrollBar>(true); vbar=bar.get(); addChild(std::move(bar)); vbar->onChanged.connect([this](int v){ scrollY=v; scrollTarget=v; }); }
void setContent(Widget* w){ content=w; }
void draw(Canvas& c) override { (void)c; if(cfg&&cfg->effectsEnabled&&cfg->smoothScroll){ if(scrollY<scrollTarget) scrollY++; else if(scrollY>scrollTarget) scrollY--; if(vbar&&vbar->value!=scrollY) vbar->value=scrollY; } }
void layout() override { if(content){ content->bounds={0,-scrollY,std::max(0,bounds.w-1),bounds.h}; content->layout(); } if(vbar){ vbar->cfg=cfg; vbar->bounds={std::max(0,bounds.w-1),0,1,bounds.h}; int total=content?std::max(bounds.h,content->bounds.h+scrollY):bounds.h; vbar->maxV=std::max(1,total); vbar->page=std::max(1,bounds.h); } for(auto&ch:children_) if(ch.get()!=content&&ch.get()!=vbar) ch->layout(); }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Wheel){ scrollTarget=std::max(0,scrollTarget+m.wheelDelta*3); if(cfg&&cfg->effectsEnabled&&cfg->smoothScroll){ scrollY+= (scrollTarget>scrollY?1:-1); if(scrollY<0) scrollY=0; } else scrollY=scrollTarget; if(vbar) vbar->setValue(scrollY); return true; } return false; }
void stepEffects(){ if(scrollY<scrollTarget) scrollY++; else if(scrollY>scrollTarget) scrollY--; }
};
/**
* @brief Two-child splitter with a draggable sash (alias Splitter).
* @details Fields: `vertical` (stack instead of side-by-side), `ratio`
* (first child's fraction, kept within 0.1–0.9 while dragging), sashPos
* and dragging (interaction state). `layout()` needs at least two
* children and leaves a 1-cell sash between them; `draw()` paints the
* sash; mouse Down/Drag/Up drives the sash and re-layouts.
*/
struct SplitPane : Widget{
bool vertical=false; double ratio=0.5; int sashPos=0; bool dragging=false;
void layout() override { if(children_.size()<2) return; if(!vertical){ int w1=(int)(bounds.w*ratio); children_[0]->bounds={0,0,w1,bounds.h}; children_[1]->bounds={w1+1,0,std::max(0,bounds.w-w1-1),bounds.h}; } else { int h1=(int)(bounds.h*ratio); children_[0]->bounds={0,0,bounds.w,h1}; children_[1]->bounds={0,h1+1,bounds.w,std::max(0,bounds.h-h1-1)}; } for(auto&c:children_) c->layout(); }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=Color::rgb(120,120,120); s.fg=Color::rgb(0,0,0); if(!vertical){ int x=a.x+(int)(a.w*ratio); for(int y=a.y;y<a.bottom();y++) c.set(x,y,"│",s); } else { int y=a.y+(int)(a.h*ratio); for(int x=a.x;x<a.right();x++) c.set(x,y,"─",s); } }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); if(m.kind==MouseKind::Down){ dragging=true; return true; } if(m.kind==MouseKind::Drag&&dragging){ if(!vertical&&a.w>0) ratio=std::clamp(double(m.pos.x-a.x)/a.w,0.1,0.9); if(vertical&&a.h>0) ratio=std::clamp(double(m.pos.y-a.y)/a.h,0.1,0.9); layout(); return true; } if(m.kind==MouseKind::Up) dragging=false; return false; }
};
using Splitter = SplitPane;
/**
* @brief Tab strip with one visible page child per tab (alias TabBar).
* @details Fields: `tabs` (labels), `active`, signal `onChanged(index)`.
* `layout()` shows only the active child (others visible=false) below
* the strip. Left/Right keys and clicking a tab switch, re-layout, and
* emit onChanged.
*/
struct TabView : Widget{
std::vector<std::string> tabs; int active=0; const Config* cfg=nullptr; Signal<int> onChanged;
TabView(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=Color::rgb(170,170,170); bg.fg=Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; // tab bar
int x=a.x; for(size_t i=0;i<tabs.size();i++){ std::string t=" "+tabs[i]+" "; CellStyle s=bg; if((int)i==active){ s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.bold=true; } int w=(int)t.size()+2; c.fill({x,a.y,w,1}," ",s); c.drawText(x,a.y,t,s,w); x+=w+1; if(x>=a.right()) break; } }
void layout() override { for(size_t i=0;i<children_.size();i++){ children_[i]->visible=((int)i==active); children_[i]->bounds={0,1,bounds.w,std::max(0,bounds.h-1)}; children_[i]->layout(); } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Left){ active=std::max(0,active-1); layout(); onChanged.emit(active); return true;} if(k.code==KeyCode::Right){ active=std::min((int)tabs.size()-1,active+1); layout(); onChanged.emit(active); return true;} if(k.isChar()&&k.ctrl&&k.text=="\t"){ } return false; }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); if(m.pos.y==a.y){ int x=a.x; for(size_t i=0;i<tabs.size();i++){ int w=(int)tabs[i].size()+4; if(m.pos.x>=x&&m.pos.x<x+w){ active=(int)i; layout(); onChanged.emit(active); return true; } x+=w+1; } } } return false; }
};
using TabBar = TabView;
/**
* @brief Expandable tree. `Node{label, children, expanded}`; roots in `roots`.
* @details `flat()` returns the visible (label, depth) rows in display
* order; `nodeAtFlat(index)` maps a visible row back to its Node*
* (nullptr out of range). Keys: Up/Down move, Right/Left expand/collapse
* the selected node, Enter emits `onSelected(label)`. Mouse: Down
* selects (re-clicking a parent toggles it), DoubleClick emits.
* `draw()` indents by depth with ▼/▶ markers and highlights selection.
*/
struct TreeView : Widget{
struct Node{ std::string label; std::vector<Node> children; bool expanded=true; };
std::vector<Node> roots; int selected=0; const Config* cfg=nullptr; Signal<std::string> onSelected;
TreeView(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
std::vector<std::pair<std::string,int>> flat() const { std::vector<std::pair<std::string,int>> out; std::function<void(const Node&,int)> rec=[&](const Node& n,int d){ out.push_back({n.label,d}); if(n.expanded) for(auto&c:n.children) rec(c,d+1); }; for(auto&r:roots) rec(r,0); return out; }
Node* nodeAtFlat(int idx){ int cnt=0; Node* found=nullptr; std::function<void(Node&)> rec=[&](Node& n){ if(found) return; if(cnt==idx){found=&n;return;} cnt++; if(n.expanded) for(auto&c:n.children) rec(c); }; for(auto&r:roots){ rec(r); if(found) break; } return found; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,0,1,0); auto f=flat(); for(int row=0;row<inner.h;row++){ int idx=row; if(idx>=(int)f.size()) break; CellStyle s=bg; if(idx==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} std::string prefix; for(int d=0;d<f[(size_t)idx].second;d++) prefix+=" "; // check if node has children
Node* n=nodeAtFlat(idx); std::string exp=n&&!n->children.empty()?(n->expanded?"▼ ":"▶ "):" "; c.fill({inner.x,inner.y+row,inner.w,1}," ",s); c.drawText(inner.x,inner.y+row,ellipsize(prefix+exp+f[(size_t)idx].first,inner.w),s,inner.w); } }
bool onKey(KeyEventData& k) override { auto f=flat(); if(f.empty()) return false; if(k.code==KeyCode::Up){ selected=std::max(0,selected-1); return true;} if(k.code==KeyCode::Down){ selected=std::min((int)f.size()-1,selected+1); return true;} if(k.code==KeyCode::Right){ Node* n=nodeAtFlat(selected); if(n) n->expanded=true; return true;} if(k.code==KeyCode::Left){ Node* n=nodeAtFlat(selected); if(n) n->expanded=false; return true;} if(k.code==KeyCode::Enter){ auto fl=flat(); if(selected<(int)fl.size()) onSelected.emit(fl[(size_t)selected].first); return true;} return false; }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); Rect inner=a.inset(1,0,1,0); int idx=m.pos.y-inner.y; auto f=flat(); if(idx>=0&&idx<(int)f.size()){ if(idx==selected){ Node* n=nodeAtFlat(idx); if(n&&!n->children.empty()) n->expanded=!n->expanded; } selected=idx; return true; } } if(m.kind==MouseKind::DoubleClick){ auto f=flat(); if(selected<(int)f.size()) onSelected.emit(f[(size_t)selected].first); return true; } return false; }
};
/**
* @brief Grid of glyph+label icons (desktop icons, build pickers).
* @details `Item{glyph, label}`; fields `items`, `selected` (-1 none),
* `cols`. Arrows move by one/row, Enter emits `onActivated(index)`, any
* move emits `onSelected(index)`; mouse Down selects, DoubleClick
* activates. Cells are 3 rows high; overflow rows are not drawn.
*/
struct IconGrid : Widget{
struct Item{ std::string glyph, label; };
std::vector<Item> items; int selected=-1, cols=4; const Config* cfg=nullptr; Signal<int> onActivated; Signal<int> onSelected;
IconGrid(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); if(cols<=0) cols=1; int cw=std::max(8,a.w/cols), ch=3; CellStyle bg; bg.fg=Color::rgb(255,255,255); bg.bg=cfg?cfg->uiColor("iconGridBg",Color::rgb(30,60,40)):Color::rgb(30,60,40); if(hasStyleOverride) bg=styleOverride; for(size_t i=0;i<items.size();i++){ int col=(int)i%cols, row=(int)i/cols; Rect r{a.x+col*cw, a.y+row*ch, cw, ch}; if(r.bottom()>a.bottom()) break; CellStyle s=bg; if((int)i==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} c.fill(r," ",s); c.drawText(r.x+1,r.y,items[i].glyph,s); c.drawText(r.x+1,r.y+1,ellipsize(items[i].label,cw-1),s,cw-1); } }
bool onKey(KeyEventData& k) override { if(items.empty()) return false; if(selected<0) selected=0; if(k.code==KeyCode::Left) selected=std::max(0,selected-1); else if(k.code==KeyCode::Right) selected=std::min((int)items.size()-1,selected+1); else if(k.code==KeyCode::Up) selected=std::max(0,selected-cols); else if(k.code==KeyCode::Down) selected=std::min((int)items.size()-1,selected+cols); else if(k.code==KeyCode::Enter){ onActivated.emit(selected); return true;} else return false; onSelected.emit(selected); return true; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); int cw=std::max(8,a.w/std::max(1,cols)), ch=3; if(m.kind==MouseKind::Down){ int col=(m.pos.x-a.x)/cw, row=(m.pos.y-a.y)/ch; int idx=row*cols+col; if(idx>=0&&idx<(int)items.size()){ selected=idx; onSelected.emit(selected); return true; } } if(m.kind==MouseKind::DoubleClick&&selected>=0){ onActivated.emit(selected); return true; } return false; }
};
/**
* @brief Bottom-bar: left-aligned `sections` followed by a scrolling
* news `ticker`. `tickerOff` is advanced by the owner (demo tick hook);
* draw() wraps the ticker text by that offset. Themed by `windowClass`.
*/
struct StatusBar : Widget{
std::vector<std::string> sections; std::string ticker; int tickerOff=0; const Config* cfg=nullptr; std::string windowClass="grey";
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } else { s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170);} if(hasStyleOverride) s=styleOverride; c.fill(a," ",s); int x=a.x; for(auto&sec:sections){ c.drawText(x,a.y,sec,s); x+=(int)sec.size()+2; if(x>=a.right()) break; } if(!ticker.empty()&&x<a.right()){ std::string t=ticker; if((int)t.size()>a.right()-x){ int off=tickerOff%(int)t.size(); std::string sc=t.substr((size_t)off)+ " "+t.substr(0,(size_t)off); c.drawText(x,a.y,ellipsize(sc,a.right()-x),s,a.right()-x);} else c.drawText(x,a.y,t,s); } }
};
/** @brief Small status pill (alias Indicator): grey normally, red when `urgent` (e.g. an unseen bell). Draw-only. */
struct Badge : Widget{ std::string text; bool urgent=false; const Config* cfg=nullptr; void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.fg=Color::rgb(255,255,255); s.bg=urgent?(cfg?cfg->uiColor("badgeUrgent",Color::rgb(200,30,30)):Color::rgb(200,30,30)):(cfg?cfg->uiColor("badgeBg",Color::rgb(80,80,80)):Color::rgb(80,80,80)); c.fill(a," ",s); c.drawText(a.x,a.y,ellipsize(text,a.w),s,a.w); } };
using Indicator = Badge;
/**
* @brief Popup menu (aliases ContextMenu, PopupMenu).
* @details `Item{label, shortcut, separator, disabled, action}` — a
* separator ignores label/action; a disabled item is greyed and cannot
* fire. Fields: `items`, `selected`, `open`. Keys: Up/Down move
* (skipping separators), Enter fires the item's action then
* `onSelected(label)` and closes, Escape closes silently. Mouse: Move
* highlights, Down fires and closes, Down outside closes. The host
* window/menu button owns showing and hiding the widget itself.
*/
struct Menu : Widget{
struct Item{ std::string label; std::string shortcut; bool separator=false, disabled=false; std::function<void()> action; };
std::vector<Item> items; int selected=0; bool open=false; int revealRows=1000000; const Config* cfg=nullptr; Signal<std::string> onSelected;
Menu(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("menuPaper",Color::rgb(245,245,245)):Color::rgb(245,245,245); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawBox(a,bg,cfg&&cfg->asciiMode); int maxRows=(int)items.size(); if(cfg&&cfg->effectsEnabled&&cfg->menuReveal&&open){ if(revealRows>maxRows) revealRows=0; maxRows=std::min(maxRows,revealRows); if(revealRows<(int)items.size()) revealRows++; } for(size_t i=0;i<items.size()&&(int)i<a.h-1&&(int)i<maxRows;i++){ int y=a.y+(int)i+ (a.h>(int)items.size()?0:0); if(items[i].separator){ CellStyle s=bg; for(int x=a.x+1;x<a.right()-1;x++) c.set(x,y,"─",s); continue; } CellStyle s=bg; if((int)i==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} if(items[i].disabled) s.fg=cfg?cfg->uiColor("disabledText",Color::rgb(150,150,150)):Color::rgb(150,150,150); c.fill({a.x+1,y,a.w-2,1}," ",s); c.drawText(a.x+1,y,ellipsize(items[i].label, a.w-2-(int)items[i].shortcut.size()-1),s); if(!items[i].shortcut.empty()) c.drawText(a.right()-1-(int)items[i].shortcut.size(), y, items[i].shortcut,s); } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up){ do{ selected=(selected+(int)items.size()-1)%std::max(1,(int)items.size()); }while(!items.empty()&&items[(size_t)selected].separator); return true;} if(k.code==KeyCode::Down){ do{ selected=(selected+1)%std::max(1,(int)items.size()); }while(!items.empty()&&items[(size_t)selected].separator); return true;} if(k.code==KeyCode::Enter){ if(selected>=0&&selected<(int)items.size()&&!items[(size_t)selected].disabled){ if(items[(size_t)selected].action) items[(size_t)selected].action(); onSelected.emit(items[(size_t)selected].label);} open=false; return true;} if(k.code==KeyCode::Escape){ open=false; return true;} return false; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); if(m.kind==MouseKind::Move){ int idx=m.pos.y-a.y; if(idx>=0&&idx<(int)items.size()) selected=idx; return true;} if(m.kind==MouseKind::Down){ int idx=m.pos.y-a.y; if(idx>=0&&idx<(int)items.size()&&!items[(size_t)idx].separator&&!items[(size_t)idx].disabled){ selected=idx; if(items[(size_t)idx].action) items[(size_t)idx].action(); onSelected.emit(items[(size_t)idx].label); open=false; return true; } if(!a.contains(m.pos)) open=false; } return false; }
};
using ContextMenu = Menu; using PopupMenu = Menu;
/** @brief Horizontal strip of menu titles. Clicking a title sets `selected` and emits `onSelected(index)`; opening the actual Menu is the host's job. */
struct MenuBar : Widget{
std::vector<std::string> menus; int selected=-1; const Config* cfg=nullptr; Signal<int> onSelected;
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("panelGrey",Color::rgb(170,170,170)):Color::rgb(170,170,170); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.fill(a," ",s); int x=a.x+1; for(size_t i=0;i<menus.size();i++){ CellStyle ms=s; if((int)i==selected){ ms.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); ms.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} std::string t=" "+menus[i]+" "; c.drawText(x,a.y,t,ms,(int)t.size()); x+=(int)t.size()+1; } }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); int x=a.x+1; for(size_t i=0;i<menus.size();i++){ int w=(int)menus[i].size()+2; if(m.pos.x>=x&&m.pos.x<x+w){ selected=(int)i; onSelected.emit(selected); return true; } x+=w+1; } } return false; }
};
/**
* @brief Green TT-style icon-button strip.
* @details Preferred API: `addBtn(label)` creates a child PushButton and
* returns it (borrowed) for signal wiring. `addButton(label)` is a legacy
* alternative kept for compatibility — prefer addBtn. `layout()` packs
* children left to right; with `overflow` set, children that no longer
* fit are hidden (the low-width "switch toolbar" behaviour). draw()
* paints the green background; buttons draw as children.
*/
struct Toolbar : Widget{
std::vector<PushButton*> buttons; bool overflow=false; const Config* cfg=nullptr;
PushButton* addButton(const std::string& lab){ auto* b=emplace<PushButton>(lab); b->cfg=cfg; buttons.push_back(b); return b; }
// Simpler API: use children as buttons directly
PushButton* addBtn(const std::string& lab){ auto* b=emplace<PushButton>(lab); b->cfg=cfg; return b; }
void layout() override { int x=0; for(auto&ch:children_){ int w=ch->measure().w; if(x+w>bounds.w){ if(overflow) ch->visible=false; } else ch->visible=true; ch->bounds={x,0,w,bounds.h}; x+=w+1; ch->layout(); } }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=Color::rgb(34,120,60); s.fg=Color::rgb(255,255,255); if(cfg){ auto w=cfg->windowColor("green"); s.fg=w.fg; s.bg=w.bg; } if(hasStyleOverride) s=styleOverride; c.fill(a," ",s); }
};
/**
* @brief Scrollable view into a text-grid "world" (the TT viewport).
* @details Fields: `world` (rows of glyph cells), camera `camX`/`camY`,
* `painter` (optional custom renderer called as painter(canvas,
* innerRect, camera) replacing the default glyph rendering; 'T' '~' '#'
* get tree/water/building colours by default). Arrow keys and wheel
* move the camera (clamped at 0); clicking emits `onCellClicked(worldPoint)`.
*/
struct ViewportWidget : Widget{
std::vector<std::string> world; int camX=0, camY=0; const Config* cfg=nullptr; std::function<void(Canvas&,Rect,Point)> painter; Signal<Point> onCellClicked;
ViewportWidget(){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={30,10}; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=Color::rgb(40,80,40); bg.fg=Color::rgb(200,255,200); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,1,1,1); if(painter){ painter(c,inner,{camX,camY}); return; } for(int y=0;y<inner.h;y++){ int wy=camY+y; if(wy<0||wy>=(int)world.size()) continue; for(int x=0;x<inner.w;x++){ int wx=camX+x; if(wx<0||wx>=(int)world[(size_t)wy].size()) continue; CellStyle s=bg; char ch=world[(size_t)wy][(size_t)wx]; if(ch=='T') s.fg=Color::rgb(40,200,80); if(ch=='~') s.fg=Color::rgb(80,160,255); if(ch=='#') s.fg=Color::rgb(180,180,180); c.set(inner.x+x,inner.y+y,std::string(1,ch),s); } } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Left) camX=std::max(0,camX-1); else if(k.code==KeyCode::Right) camX++; else if(k.code==KeyCode::Up) camY=std::max(0,camY-1); else if(k.code==KeyCode::Down) camY++; else return false; return true; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); Rect inner=a.inset(1,1,1,1); if(m.kind==MouseKind::Down&&inner.contains(m.pos)){ onCellClicked.emit({camX+(m.pos.x-inner.x), camY+(m.pos.y-inner.y)}); return true; } if(m.kind==MouseKind::Wheel){ camY=std::max(0,camY+m.wheelDelta); return true; } return false; }
};
/**
* @brief Downsampled world overview (the TT smallmap).
* @details Fields: `world`, `viewRect` (world-space viewport rectangle
* outlined in yellow), `filters` (layer name -> visible, for host UIs to
* toggle; drawing currently follows the world glyphs). Clicking centres
* viewRect on the clicked world cell and emits `onJump(worldPoint)`,
* which hosts use to scroll a linked ViewportWidget.
*/
struct MiniMapWidget : Widget{
std::vector<std::string> world; Rect viewRect{0,0,10,5}; std::map<std::string,bool> filters{{"vehicles",true},{"industries",true},{"routes",true},{"vegetation",true},{"owners",true}}; const Config* cfg=nullptr; Signal<Point> onJump;
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=Color::rgb(20,40,20); bg.fg=Color::rgb(200,255,200); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,1,1,1); if(world.empty()) return; for(int y=0;y<inner.h;y++){ int wy=y*(int)world.size()/std::max(1,inner.h); for(int x=0;x<inner.w;x++){ int wx=x*(int)world[0].size()/std::max(1,inner.w); if(wy<(int)world.size()&&wx<(int)world[(size_t)wy].size()){ char ch=world[(size_t)wy][(size_t)wx]; CellStyle s=bg; char dch=ch; auto filt=[&](const char* k){ auto it=filters.find(k); return it==filters.end()||it->second; }; if(ch=='T'&&!filt("vegetation")) dch='.'; if(ch=='#'&&!filt("industries")) dch='.'; if(ch=='~'&&!filt("owners")) dch='.'; if(ch=='~') s.fg=Color::rgb(80,160,255); else if(dch=='T') s.fg=Color::rgb(60,220,100); else if(dch=='#') s.fg=Color::rgb(200,200,200); else if(dch=='.') s.fg=Color::rgb(120,180,120); c.set(inner.x+x,inner.y+y, dch==' '?"░":std::string(1,dch), s); } } }
// view rect
CellStyle vs; vs.fg=Color::rgb(255,255,0); vs.bg=bg.bg; int sx=inner.x+viewRect.x*inner.w/std::max(1,(int)world[0].size()); int sy=inner.y+viewRect.y*inner.h/std::max(1,(int)world.size()); int sw=std::max(2,viewRect.w*inner.w/std::max(1,(int)world[0].size())); int sh=std::max(2,viewRect.h*inner.h/std::max(1,(int)world.size())); for(int x=sx;x<std::min(inner.right(),sx+sw);x++){ c.set(x,sy,"─",vs); c.set(x,std::min(inner.bottom()-1,sy+sh-1),"─",vs);} for(int y=sy;y<std::min(inner.bottom(),sy+sh);y++){ c.set(sx,y,"│",vs); c.set(std::min(inner.right()-1,sx+sw-1),y,"│",vs);} }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); Rect inner=a.inset(1,1,1,1); if(m.kind==MouseKind::Down&&inner.contains(m.pos)&&!world.empty()){ int wx=(m.pos.x-inner.x)*(int)world[0].size()/std::max(1,inner.w); int wy=(m.pos.y-inner.y)*(int)world.size()/std::max(1,inner.h); viewRect.x=wx-viewRect.w/2; viewRect.y=wy-viewRect.h/2; onJump.emit({wx,wy}); return true; } return false; }
};
// VT Parser + TerminalWidget
/**
* @brief VT100/xterm-subset parser turning a byte stream into a cell grid.
* @details State: `cols`/`rows`, cursor `cx`/`cy` (always inside the
* grid — wrapping is deferred via `wrapPending`, never cx == cols),
* `grid` (current screen of CellV{ch, st}), `altGrid` (saved main screen
* while `alt`), current style `cur`, scroll region
* `scrollTop`/`scrollBottom`, saved cursor `savedX`/`savedY`, `onBell`
* (set when a BEL byte is seen; `bellCallback` is invoked too).
* Methods: `VtParser(cols, rows)`; `resize(c, r)` (reallocates both
* grids, clamps cursor); `feed(bytes)` — printable UTF-8 (split
* sequences are buffered in `pendingUtf8`), CR/LF/BS/Tab, ESC 7/8/M,
* OSC (skipped), and CSI via handleCsi; `scrollUp(n, top, bottom)`
* (internal); `putChar(glyph)` (internal write with deferred wrap and
* scroll-region scrolling); `params(s, def)` parses a CSI parameter
* list; `handleCsi(params, final)` implements SGR (colours 30–37/40–47,
* bright 90–107, bold/dim/underline/reverse and resets), H/f, A/B/C/D,
* G, d, J, K, L, M, P, @, S, T, r (scroll region, homes cursor),
* s/u (save/restore cursor), and private h/l for 47/1047/1049
* (alternate screen: saves grid+cursor, clears, homes; leaving restores
* both exactly). Truncated or mutated input never crashes and never
* leaves the cursor out of bounds — fuzz-tested.
*/
struct VtParser{
struct CellV{ std::string ch=" "; CellStyle st; };
int cols=80, rows=24, cx=0, cy=0; std::vector<std::vector<CellV>> grid, altGrid; bool alt=false; CellStyle cur; std::string escBuf, pendingUtf8; bool inEsc=false, inCsi=false; int savedX=0,savedY=0; int scrollTop=0, scrollBottom=23; bool onBell=false; bool wrapPending=false;
std::function<void()> bellCallback;
std::function<void(const std::string&)> responseCallback;
bool inOsc=false;
VtParser(int c=80,int r=24){ cols=std::max(1,c); rows=std::max(1,r); grid.assign((size_t)rows, std::vector<CellV>((size_t)cols)); altGrid.assign((size_t)rows, std::vector<CellV>((size_t)cols)); scrollTop=0; scrollBottom=rows-1; }
void resize(int c,int r){ int nc=std::max(1,c), nr=std::max(1,r); auto copyGrid=[&](std::vector<std::vector<CellV>>& g){ std::vector<std::vector<CellV>> ng((size_t)nr, std::vector<CellV>((size_t)nc)); for(int y=0;y<std::min(nr,(int)g.size());y++) for(int x=0;x<std::min(nc,(int)g[(size_t)y].size());x++) ng[(size_t)y][(size_t)x]=g[(size_t)y][(size_t)x]; g=std::move(ng); };
// preserve alt separately: copy both using current grid for main, altGrid for alt
{ auto old=grid; cols=nc; rows=nr; grid.assign((size_t)nr, std::vector<CellV>((size_t)nc)); for(int y=0;y<std::min(nr,(int)old.size());y++) for(int x=0;x<std::min(nc,(int)old[(size_t)y].size());x++) grid[(size_t)y][(size_t)x]=old[(size_t)y][(size_t)x]; auto oldAlt=altGrid; altGrid.assign((size_t)nr, std::vector<CellV>((size_t)nc)); for(int y=0;y<std::min(nr,(int)oldAlt.size());y++) for(int x=0;x<std::min(nc,(int)oldAlt[(size_t)y].size());x++) altGrid[(size_t)y][(size_t)x]=oldAlt[(size_t)y][(size_t)x]; (void)copyGrid; }
scrollTop=std::clamp(scrollTop,0,rows-1); scrollBottom=std::clamp(scrollBottom,scrollTop,rows-1); if(scrollBottom<scrollTop) scrollBottom=rows-1; cx=std::clamp(cx,0,cols-1); cy=std::clamp(cy,0,rows-1); savedX=std::clamp(savedX,0,cols-1); savedY=std::clamp(savedY,0,rows-1); }
void scrollUp(int n,int top,int bot){ top=std::clamp(top,0,rows-1); bot=std::clamp(bot,top,rows-1); n=std::clamp(n,0,bot-top+1); for(int i=0;i<n;i++){ for(int y=top;y<bot;y++) grid[(size_t)y]=grid[(size_t)y+1]; grid[(size_t)bot].assign((size_t)cols, CellV{}); } }
void scrollDown(int n,int top,int bot){ top=std::clamp(top,0,rows-1); bot=std::clamp(bot,top,rows-1); n=std::clamp(n,0,bot-top+1); for(int i=0;i<n;i++){ for(int y=bot;y>top;y--) grid[(size_t)y]=grid[(size_t)y-1]; grid[(size_t)top].assign((size_t)cols, CellV{}); } }
void putChar(const std::string& ch){ if(wrapPending){ wrapPending=false; cx=0; cy++; } if(cy>scrollBottom){ scrollUp(1,scrollTop,scrollBottom); cy=scrollBottom; } if(cy>=0&&cy<rows&&cx>=0&&cx<cols){ grid[(size_t)cy][(size_t)cx].ch=ch; grid[(size_t)cy][(size_t)cx].st=cur; } if(cx>=cols-1) wrapPending=true; else cx++; }
void feed(const std::string& dataIn){
std::string data=pendingUtf8+dataIn; pendingUtf8.clear();
size_t i=0; while(i<data.size()){
char c=data[i];
if(inOsc){
if(c=='\a'){ inOsc=false; i++; continue; }
if(c=='\033'){ // possible ST: consume next byte if backslash, else restart esc handling
if(i+1<data.size()&&data[i+1]=='\\'){ inOsc=false; i+=2; continue; }
if(i+1>=data.size()){ i=data.size(); continue; }
inOsc=false; continue; // let ESC be processed next iteration
}
i++; continue;
}
if(inEsc){
if(c=='['){ inCsi=true; inEsc=false; escBuf.clear(); i++; continue; }
if(c==']'){ inOsc=true; inEsc=false; i++; continue; }
if(c=='('||c==')'){ i+=2; inEsc=false; continue; }
if(c=='7'){ savedX=cx; savedY=cy; } if(c=='8'){ cx=std::clamp(savedX,0,cols-1); cy=std::clamp(savedY,0,rows-1); } if(c=='M'){ if(cy==scrollTop) scrollDown(1,scrollTop,scrollBottom); else if(cy>0) cy--; } if(c=='D'){ wrapPending=false; cy++; if(cy>scrollBottom){ scrollUp(1,scrollTop,scrollBottom); cy=scrollBottom; } } if(c=='E'){ wrapPending=false; cx=0; cy++; if(cy>scrollBottom){ scrollUp(1,scrollTop,scrollBottom); cy=scrollBottom; } }
inEsc=false; i++; continue;
}
if(inCsi){
if((c>='@'&&c<='~')){ handleCsi(escBuf,c); inCsi=false; escBuf.clear(); i++; continue; } else { escBuf+=c; if(escBuf.size()>4096){ inCsi=false; escBuf.clear(); } i++; continue; }
}
if(c=='\033'){ inEsc=true; i++; continue; }
if(c=='\a'){ if(bellCallback) bellCallback(); onBell=true; i++; continue; }
if(c=='\n'){ wrapPending=false; cy++; cx=0; if(cy>scrollBottom){ scrollUp(1,scrollTop,scrollBottom); cy=scrollBottom; } i++; continue; }
if(c=='\r'){ wrapPending=false; cx=0; i++; continue; }
if(c=='\b'){ cx=std::max(0,cx-1); i++; continue; }
if(c=='\t'){ cx=(cx/8+1)*8; if(cx>=cols) cx=cols-1; i++; continue; }
if((unsigned char)c<0x20){ i++; continue; }
unsigned char uc=(unsigned char)c; size_t len=1; if((uc&0xE0)==0xC0) len=2; else if((uc&0xF0)==0xE0) len=3; else if((uc&0xF8)==0xF0) len=4; if(i+len>data.size()){ pendingUtf8=data.substr(i); break; }
putChar(data.substr(i,len)); i+=len;
}
}
std::vector<int> params(const std::string& s,int def=0){ std::vector<int> o; std::string cur; for(char c: s+";"){ if(c==';'){ o.push_back(cur.empty()?def:atoi(cur.c_str())); cur.clear(); } else cur+=c; } if(o.empty()) o.push_back(def); return o; }
void handleCsi(const std::string& p, char fin){
wrapPending=false;
bool priv=p.size()&&p[0]=='?'; std::string pp=priv?p.substr(1):p; auto ps=params(pp,0);
auto get=[&](size_t idx,int def){ return idx<ps.size()?ps[idx]:def; };
if(fin=='n'){ if(get(0,0)==6&&responseCallback) responseCallback("\033["+std::to_string(cy+1)+";"+std::to_string(cx+1)+"R"); return; }
if(fin=='c'&&!priv){ if(responseCallback) responseCallback("\033[?62c"); return; }
if(fin=='m'){ std::string norm; for(char ch: pp) norm+=(ch==':'?';':ch); auto sps=params(norm,0); if(pp.empty()){ cur=CellStyle{}; } else { for(size_t idx=0;idx<sps.size();idx++){ int code=sps[idx]; if(code==0) cur=CellStyle{}; else if(code==1) cur.bold=true; else if(code==2) cur.dim=true; else if(code==3) cur.italic=true; else if(code==4) cur.underline=true; else if(code==7) cur.reverse=true; else if(code==22){cur.bold=false;cur.dim=false;} else if(code==23) cur.italic=false; else if(code==24) cur.underline=false; else if(code==27) cur.reverse=false; else if(code>=30&&code<=37) cur.fg=Color::indexed(code-30); else if(code==39) cur.fg=Color::def(); else if(code>=40&&code<=47) cur.bg=Color::indexed(code-40); else if(code==49) cur.bg=Color::def(); else if(code>=90&&code<=97) cur.fg=Color::indexed(code-90+8); else if(code>=100&&code<=107) cur.bg=Color::indexed(code-100+8); else if(code==38||code==48){ bool isFg=(code==38); if(idx+1<sps.size()){ int mode=sps[idx+1]; if(mode==5){ if(idx+2<sps.size()){ int v=std::clamp(sps[idx+2],0,255); if(isFg) cur.fg=Color::indexed(v); else cur.bg=Color::indexed(v); idx+=2; } else idx+=1; } else if(mode==2){ if(idx+2<sps.size()&&sps[idx+2]==0&&(idx+5<sps.size()||true)){ /* colon form 38;2;0;r;g;b handled below by generic */ } if(idx+4<sps.size()){ int r=std::clamp(sps[idx+2],0,255), g=std::clamp(sps[idx+3],0,255), b=std::clamp(sps[idx+4],0,255); // skip optional colorspace id in colon form: if extra leading 0 and enough params, params already normalised so 38:2::r:g:b -> 38;2;;r;g;b gives an empty param=0
if(sps[idx+2]==0&&idx+5<sps.size()&&pp.find(':')!=std::string::npos){ r=std::clamp(sps[idx+3],0,255); g=std::clamp(sps[idx+4],0,255); b=std::clamp(sps[idx+5],0,255); idx+=5; } else idx+=4; if(isFg) cur.fg=Color::rgb(r,g,b); else cur.bg=Color::rgb(r,g,b); } else { idx=sps.size(); } } else idx+=1; } } } } return; }
if(fin=='H'||fin=='f'){ cy=std::clamp(get(0,1)-1,0,rows-1); cx=std::clamp((ps.size()>1?get(1,1):1)-1,0,cols-1); return; }
if(fin=='A') cy=std::max(0,cy-std::max(1,get(0,1)));
if(fin=='B') cy=std::min(rows-1,cy+std::max(1,get(0,1)));
if(fin=='C') cx=std::min(cols-1,cx+std::max(1,get(0,1)));
if(fin=='D') cx=std::max(0,cx-std::max(1,get(0,1)));
if(fin=='G') cx=std::clamp(get(0,1)-1,0,cols-1);
if(fin=='d') cy=std::clamp(get(0,1)-1,0,rows-1);
if(fin=='E'){ cy=std::min(rows-1,cy+std::max(1,get(0,1))); cx=0; }
if(fin=='F'){ cy=std::max(0,cy-std::max(1,get(0,1))); cx=0; }
if(fin=='e') cy=std::min(rows-1,cy+std::max(1,get(0,1)));
if(fin=='J'){ int mode=get(0,0); if(mode==2||mode==3){ for(auto&row:grid) for(auto&cell:row) cell=CellV{}; cx=cy=0; } else if(mode==0){ for(int x=cx;x<cols;x++) grid[(size_t)cy][(size_t)x]=CellV{}; for(int y=cy+1;y<rows;y++) for(auto&cell:grid[(size_t)y]) cell=CellV{}; } else if(mode==1){ for(int y=0;y<cy;y++) for(auto&cell:grid[(size_t)y]) cell=CellV{}; for(int x=0;x<=cx;x++) grid[(size_t)cy][(size_t)x]=CellV{}; } }
if(fin=='K'){ int mode=get(0,0); if(mode==0) for(int x=cx;x<cols;x++) grid[(size_t)cy][(size_t)x]=CellV{}; else if(mode==1) for(int x=0;x<=cx;x++) grid[(size_t)cy][(size_t)x]=CellV{}; else for(auto&cell:grid[(size_t)cy]) cell=CellV{}; }
if(fin=='L'){ int n=std::clamp(std::max(1,get(0,1)),1,std::max(1,rows)); if(cy>=scrollTop&&cy<=scrollBottom){ n=std::min(n,scrollBottom-cy+1); for(int i=0;i<n;i++){ grid.insert(grid.begin()+cy, std::vector<CellV>((size_t)cols)); grid.erase(grid.begin()+scrollBottom+1); } } }
if(fin=='M'){ int n=std::clamp(std::max(1,get(0,1)),1,std::max(1,rows)); if(cy>=scrollTop&&cy<=scrollBottom){ n=std::min(n,scrollBottom-cy+1); for(int i=0;i<n;i++){ grid.erase(grid.begin()+cy); grid.insert(grid.begin()+scrollBottom, std::vector<CellV>((size_t)cols)); } } }
if(fin=='P'){ int n=std::clamp(std::max(1,get(0,1)),1,std::max(1,cols)); if(cy>=0&&cy<(int)grid.size()){ auto&row=grid[(size_t)cy]; int nn=std::min(n,std::max(0,cols-cx)); if(nn>0&&cx<(int)row.size()){ row.erase(row.begin()+cx, row.begin()+std::min((int)row.size(),cx+nn)); while((int)row.size()<cols) row.push_back(CellV{}); row.resize((size_t)cols); } } }
if(fin=='@'){ int n=std::clamp(std::max(1,get(0,1)),1,std::max(1,cols)); if(cy>=0&&cy<(int)grid.size()){ auto&row=grid[(size_t)cy]; int nn=std::min(n,std::max(0,cols-cx)); if(nn>0) row.insert(row.begin()+std::min(cx,(int)row.size()), (size_t)nn, CellV{}); row.resize((size_t)cols); } }
if(fin=='S'){ scrollUp(std::clamp(std::max(1,get(0,1)),1,std::max(1,rows)),scrollTop,scrollBottom); }
if(fin=='T'){ if(!priv) scrollDown(std::clamp(std::max(1,get(0,1)),1,std::max(1,rows)),scrollTop,scrollBottom); }
if(fin=='r'){ int top=get(0,1), bot=(ps.size()>1?get(1,rows):rows); if(top>=1&&bot>top&&bot<=rows){ scrollTop=top-1; scrollBottom=bot-1; } else { scrollTop=0; scrollBottom=rows-1; } cx=cy=0; }
if(fin=='s'){ savedX=cx; savedY=cy; } if(fin=='u'){ cx=std::clamp(savedX,0,cols-1); cy=std::clamp(savedY,0,rows-1); }
if(fin=='h'&&priv){ if(get(0,0)==1049||get(0,0)==1047||get(0,0)==47){ altGrid=grid; savedX=cx; savedY=cy; for(auto&row:grid) for(auto&cell:row) cell=CellV{}; cx=cy=0; alt=true; } }
if(fin=='l'&&priv){ if(get(0,0)==1049||get(0,0)==1047||get(0,0)==47){ grid=altGrid; cx=savedX; cy=savedY; alt=false; } }
}
};
// ---------- Terminal Widget + PTY ----------
/**
* @brief A widget hosting a real shell (or any command) on a PTY.
* @details State: `vt` (the VtParser screen), `masterFd`/`childPid`
* (owned PTY + child; -1 when stopped), `shellCmd`, `exited`/`exitMsg`,
* callback `onBell` (fired for child BEL bytes; Application routes it to
* the BellService). The destructor stops the child.
* Methods: `TerminalWidget(cols, rows)`; `start(command)` fork/execs
* `/bin/sh -c command` with TERM=xterm-256color, non-blocking master,
* returns false when no PTY is available (always false off Linux);
* `stop()` closes the master and SIGHUPs the child; `resizePTY()` pushes
* the grid size via TIOCSWINSZ + SIGWINCH; `pollInput()` drains the
* master into vt (non-blocking; sets exited on EOF/EIO or child reap);
* `sendStr(bytes)` writes fully, retrying on EINTR; `fd()` exposes the
* master for Application's poll set.
* Interaction: `draw()` syncs vt to the widget size (resizing the PTY),
* renders cells (default fg/bg substituted), a reversed caret when
* focused, and the exit notice; `onKey()` translates keys to terminal
* bytes (arrows/Home/End/PgUp/PgDn/Insert/Delete/F-keys, Ctrl+letter,
* Alt prefix) — once exited, R restarts the shell and other keys are
* swallowed; `onEvent()` wraps pastes in bracketed-paste markers;
* `onMouse()` maps wheel to arrow keys for the child.
*/
struct TerminalWidget : Widget{
VtParser vt; int masterFd=-1; pid_t childPid=-1; std::string shellCmd="/bin/sh"; bool exited=false; std::string exitMsg; const Config* cfg=nullptr;
std::function<void()> onBell;
TerminalWidget(int cols=80,int rows=24):vt(cols,rows){ focusable=true; focusPolicy=FocusPolicy::Strong; prefSize={40,12}; vt.bellCallback=[this](){ if(onBell) onBell(); }; vt.responseCallback=[this](const std::string& r){ sendStr(r); }; }
~TerminalWidget() override { stop(); }
bool start(const std::string& shell="/bin/sh"){
stop(); shellCmd=shell; exited=false;
struct winsize ws{}; ws.ws_col=(unsigned short)std::max(10,vt.cols); ws.ws_row=(unsigned short)std::max(3,vt.rows); ws.ws_xpixel=0; ws.ws_ypixel=0;
int slave=-1;
#if defined(__linux__)
if(openpty(&masterFd,&slave,nullptr,nullptr,&ws)!=0){ masterFd=-1; return false; }
#else
(void)slave; return false;
#endif
pid_t pid=fork();
if(pid<0){ close(masterFd); close(slave); masterFd=-1; childPid=-1; return false; }
if(pid==0){
close(masterFd); setsid(); ioctl(slave,TIOCSCTTY,0); dup2(slave,0); dup2(slave,1); dup2(slave,2); if(slave>2) close(slave);
setenv("TERM","xterm-256color",1);
execl("/bin/sh","sh","-c",shell.c_str(),(char*)nullptr); _exit(127);
}
close(slave); childPid=pid; int flags=fcntl(masterFd,F_GETFL,0); fcntl(masterFd,F_SETFL,flags|O_NONBLOCK);
return true;
}
std::string outQueue;
void stop(){ if(masterFd>=0){ close(masterFd); masterFd=-1; } outQueue.clear(); if(childPid>0){ kill(childPid,SIGHUP); int st=0; for(int i=0;i<50;i++){ pid_t r=waitpid(childPid,&st,WNOHANG); if(r==childPid||r<0) break; struct timespec ts{0,1000000}; nanosleep(&ts,nullptr); } // final reap attempt
{ pid_t r=waitpid(childPid,&st,WNOHANG); (void)r; } childPid=-1; } }
bool flushOutput(){ if(masterFd<0||outQueue.empty()) return true; while(!outQueue.empty()){ ssize_t n=write(masterFd,outQueue.data(),outQueue.size()); if(n>0){ outQueue.erase(0,(size_t)n); continue; } if(n<0&&errno==EINTR) continue; if(n<0&&(errno==EAGAIN||errno==EWOULDBLOCK)) return false; outQueue.clear(); return false; } return true; }
void resizePTY(){ if(masterFd>=0){ winsize ws{}; ws.ws_col=(unsigned short)vt.cols; ws.ws_row=(unsigned short)vt.rows; ioctl(masterFd,TIOCSWINSZ,&ws); if(childPid>0) kill(childPid,SIGWINCH); } vt.resize(vt.cols,vt.rows); }
void pollInput(){
if(masterFd<0) return;
flushOutput();
if(exited){ // still drain any buffered final output once
}
char buf[4096]; bool eof=false;
while(true){ ssize_t n=read(masterFd,buf,sizeof(buf)); if(n>0){ vt.feed(std::string(buf,(size_t)n)); } else if(n==0){ eof=true; break; } else { if(errno==EAGAIN||errno==EWOULDBLOCK) break; if(errno==EINTR) continue; if(errno==EIO){ eof=true; } break; } }
if(childPid>0){ int st=0; pid_t r=waitpid(childPid,&st,WNOHANG); if(r==childPid){ childPid=-1; eof=true; } }
if(eof){ // final drain after reap
while(true){ ssize_t n=read(masterFd,buf,sizeof(buf)); if(n>0){ vt.feed(std::string(buf,(size_t)n)); continue; } break; }
exited=true; exitMsg="[process exited - press R to restart]";
}
}
void sendStr(const std::string& s){ if(masterFd>=0&&!exited){ if(s.size()>1048576){ /* cap queued paste */ } outQueue+=s; if(outQueue.size()>1048576) outQueue.erase(0,outQueue.size()-1048576); flushOutput(); } }
void draw(Canvas& c) override {
Rect a=absoluteBounds(); CellStyle bg; bg.bg=Color::rgb(0,0,0); bg.fg=Color::rgb(0,255,0); if(hasStyleOverride) bg=styleOverride;
c.fill(a," ",bg);
int cols=std::max(1,a.w), rows=std::max(1,a.h);
if(vt.cols!=cols||vt.rows!=rows){ vt.resize(cols,rows); resizePTY(); }
for(int y=0;y<rows&&y<vt.rows;y++) for(int x=0;x<cols&&x<vt.cols;x++){ auto&cell=vt.grid[(size_t)y][(size_t)x]; CellStyle s=cell.st; if(s.fg.isDefault()) s.fg=Color::rgb(200,200,200); if(s.bg.isDefault()) s.bg=Color::rgb(0,0,0); c.set(a.x+x,a.y+y,cell.ch,s); }
if(!exited&&focused){ if(vt.cy<rows&&vt.cx<cols){ auto cell=c.get(a.x+vt.cx,a.y+vt.cy); CellStyle s=cell.st; s.reverse=!s.reverse; c.set(a.x+vt.cx,a.y+vt.cy,cell.ch.empty()?" ":cell.ch,s); } }
if(exited){ CellStyle s; s.fg=Color::rgb(255,255,0); s.bg=Color::rgb(0,0,0); c.drawText(a.x,a.bottom()-1,ellipsize(exitMsg,a.w),s,a.w); }
}
bool onKey(KeyEventData& k) override {
if(exited){ if(k.isChar()&&(k.text=="r"||k.text=="R")){ int c0=vt.cols,r0=vt.rows; vt=VtParser(c0,r0); vt.bellCallback=[this](){ if(onBell) onBell(); }; vt.responseCallback=[this](const std::string& r){ sendStr(r); }; start(shellCmd); return true; } return true; }
if(k.ctrl&&k.shift&&k.text=="c"){ return false; }
std::string seq;
if(k.code==KeyCode::Enter) seq="\r"; else if(k.code==KeyCode::Backspace) seq="\x7f"; else if(k.code==KeyCode::Tab) seq="\t"; else if(k.code==KeyCode::Escape) seq="\033";
else if(k.code==KeyCode::Up) seq="\033[A"; else if(k.code==KeyCode::Down) seq="\033[B"; else if(k.code==KeyCode::Right) seq="\033[C"; else if(k.code==KeyCode::Left) seq="\033[D";
else if(k.code==KeyCode::Home) seq="\033[H"; else if(k.code==KeyCode::End) seq="\033[F"; else if(k.code==KeyCode::PageUp) seq="\033[5~"; else if(k.code==KeyCode::PageDown) seq="\033[6~";
else if(k.code==KeyCode::Delete) seq="\033[3~"; else if(k.code==KeyCode::Insert) seq="\033[2~";
else if(k.code>=KeyCode::F1&&k.code<=KeyCode::F12){ int n=(int)k.code-(int)KeyCode::F1+1; char buf[16]; if(n<=4) std::snprintf(buf,sizeof(buf),"\033O%c",'P'+n-1); else std::snprintf(buf,sizeof(buf),"\033[%d~", n==5?15:n==6?17:n==7?18:n==8?19:n==9?20:n==10?21:n==11?23:24); seq=buf; }
else if(k.ctrl&&k.isChar()&&!k.text.empty()){ char ch=std::tolower((unsigned char)k.text[0]); if(ch>='a'&&ch<='z') seq=std::string(1,(char)(ch-'a'+1)); else seq=k.text; }
else if(k.alt&&k.isChar()) seq="\033"+k.text;
else if(k.isChar()) seq=k.text;
else return false;
sendStr(seq); return true;
}
bool onEvent(Event& e) override { if(e.type==EventType::Paste&&focused){ sendStr("\033[200~"+e.pasteText.substr(0,1048576)+"\033[201~"); e.handled=true; return true; } return Widget::onEvent(e); }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Wheel){ if(m.wheelDelta>0) sendStr("\033[A\033[A\033[A"); else sendStr("\033[B\033[B\033[B"); return true; } return false; }
int fd() const { return masterFd; }
};
// ---------- Additional widgets ----------
/** @brief Clickable key grid; each key is a 3-cell raised tile. Emits `onKeyPress(glyph)` per click; the bottom row emits a space. Rows are replaceable via `rows`. */
struct OnScreenKeyboard : Widget{
std::vector<std::string> rows{"1234567890","QWERTYUIOP","ASDFGHJKL","ZXCVBNM"}; const Config* cfg=nullptr; Signal<std::string> onKeyPress;
OnScreenKeyboard(){ focusable=true; }
static const std::vector<std::string>& bottomKeys(){ static const std::vector<std::string> k{"Ctrl","Alt"," ","Enter","Bksp","Esc",",",".","/","-"}; return k; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=Color::rgb(170,170,170); bg.fg=Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.fill(a," ",bg); int y=a.y; for(auto&row:rows){ int x=a.x; for(char ch: row){ std::string s(1,ch); CellStyle ks=bg; c.drawBevel({x,y,3,1},ks,true,cfg&&cfg->asciiMode); c.drawText(x+1,y,s,ks); x+=3; if(x>=a.right()) break; } y++; if(y>=a.bottom()) break; } if(y<a.bottom()){ int x=a.x; for(auto&k: bottomKeys()){ int w=k==" "?10:(int)k.size()+2; c.drawText(x,y,"["+(k==" "?"Space":k)+"]",bg,w+1); x+=w+1; if(x>=a.right()) break; } } }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ Rect a=absoluteBounds(); int row=m.pos.y-a.y; if(row>=0&&row<(int)rows.size()){ int idx=(m.pos.x-a.x)/3; if(idx>=0&&idx<(int)rows[(size_t)row].size()){ onKeyPress.emit(std::string(1,rows[(size_t)row][(size_t)idx])); return true; } } if(row>=(int)rows.size()){ int x=a.x; for(auto&k: bottomKeys()){ int w=k==" "?10:(int)k.size()+2; if(m.pos.x>=x&&m.pos.x<x+w+1){ onKeyPress.emit(k); return true; } x+=w+1; } onKeyPress.emit(" "); return true; } } return false; }
};
/**
* @brief Date field "YYYY-MM-DD" (`str()` formats it). Up/Down step the
* day, Left/Right the month, PgUp/PgDn the year; month clamps 1–12 and
* day 1–31 (no per-month day validation), emitting `onChanged` per key.
*/
struct DatePicker : Widget{
int year=2026, month=11, day=4; const Config* cfg=nullptr; Signal<> onChanged;
DatePicker(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
std::string str() const { char buf[32]; std::snprintf(buf,sizeof(buf),"%04d-%02d-%02d",year,month,day); return buf; }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); s.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) s=styleOverride; c.drawInset(a,s,cfg&&cfg->asciiMode); c.drawText(a.x+1,a.y,str(),s); }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up) day++; else if(k.code==KeyCode::Down) day--; else if(k.code==KeyCode::Right) month++; else if(k.code==KeyCode::Left) month--; else if(k.code==KeyCode::PageUp) year++; else if(k.code==KeyCode::PageDown) year--; else return false; month=std::clamp(month,1,12); day=std::clamp(day,1,31); onChanged.emit(); return true; }
};
/**
* @brief The 16 TT colours as a 4-column swatch grid (alias ColorPicker).
* @details Arrows move the selection (rows of 4), Enter or a click picks
* and emits `onPicked(name, colour)` resolved through cfg;
* `selectedName()` / `selectedColor()` read the current choice
* (Color::def() when cfg is unset). Selected swatch is bold+reversed.
*/
struct ColourPicker : Widget{
std::vector<std::string> names{"DarkBlue","PaleGreen","Pink","Yellow","Red","LightBlue","Green","DarkGreen","Blue","Cream","Mauve","Purple","Orange","Brown","Grey","White"}; int selected=0; const Config* cfg=nullptr; Signal<std::string,Color> onPicked;
ColourPicker(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void draw(Canvas& c) override { if(!names.empty()) selected=std::clamp(selected,0,(int)names.size()-1); Rect a=absoluteBounds(); int cols=4; int cw=std::max(6,a.w/cols), ch=2; for(size_t i=0;i<names.size();i++){ int col=(int)i%cols, row=(int)i/cols; Rect r{a.x+col*cw,a.y+row*ch,cw,ch}; CellStyle s; if(cfg) s.bg=cfg->ttColor(names[i]); else s.bg=Color::rgb(128,128,128); s.fg=Color::rgb(0,0,0); if((int)i==selected){ s.bold=true; s.reverse=true; } c.fill(r," ",s); c.drawText(r.x,r.y+ (ch>1?1:0), ellipsize(names[i],cw), s, cw); if((int)i==selected) c.drawText(r.x,r.y,"▣",s); } }
bool onKey(KeyEventData& k) override { if(names.empty()) return false; selected=std::clamp(selected,0,(int)names.size()-1); if(k.code==KeyCode::Left) selected=std::max(0,selected-1); else if(k.code==KeyCode::Right) selected=std::min((int)names.size()-1,selected+1); else if(k.code==KeyCode::Up) selected=std::max(0,selected-4); else if(k.code==KeyCode::Down) selected=std::min((int)names.size()-1,selected+4); else if(k.code==KeyCode::Enter){ if(cfg) onPicked.emit(names[(size_t)selected],cfg->ttColor(names[(size_t)selected])); return true; } else return false; return true; }
bool onMouse(MouseEventData& m) override { if(m.kind==MouseKind::Down){ if(names.empty()) return false; Rect a=absoluteBounds(); int cols=4; int cw=std::max(6,a.w/cols), ch=2; if(cw<=0||ch<=0) return false; int col=(m.pos.x-a.x)/cw, row=(m.pos.y-a.y)/ch; if(col<0||col>=cols||row<0) return false; int idx=row*cols+col; if(idx>=0&&idx<(int)names.size()){ selected=idx; if(cfg) onPicked.emit(names[(size_t)idx],cfg->ttColor(names[(size_t)idx])); return true; } } return false; }
std::string selectedName() const { if(names.empty()) return ""; return names[(size_t)std::clamp(selected,0,(int)names.size()-1)]; }
Color selectedColor() const { return cfg?cfg->ttColor(selectedName()):Color::def(); }
};
using ColorPicker = ColourPicker;
/** @brief Single-line pale-yellow tooltip box holding `text`. Shown/positioned by Application after Config::tooltipDelayMs of hover (and on right-click). Draw-only. */
struct Tooltip : Widget{ std::string text; void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=Color::rgb(255,255,220); s.fg=Color::rgb(0,0,0); c.drawBox(a,s); c.drawText(a.x+1,a.y,ellipsize(text,a.w-2),s,a.w-2); } };
/** @brief Toast popup (alias Toast): `title`, `body`, `ttlMs` lifetime managed by Application, `closable` shows a ✕ glyph. Draw-only; expiry/closing is the host's job. */
struct Notification : Widget{ std::string title, body; int ttlMs=4000; bool closable=true; long long expiresAtMs=0; const Config* cfg=nullptr; void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle s; s.bg=Color::rgb(50,50,50); s.fg=Color::rgb(255,255,255); if(cfg){ auto w=cfg->windowColor("grey"); s.bg=w.bg; s.fg=w.fg; } c.drawBox(a,s); c.drawText(a.x+1,a.y,ellipsize(title,a.w-3),s); if(a.h>1) c.drawText(a.x+1,a.y+1,ellipsize(body,a.w-2),s); if(closable) c.drawText(a.right()-2,a.y,cfg?cfg->glyph("close","✕"):"✕",s); } };
using Toast = Notification;
/**
* @brief Modal-dialog content: `title`, wrapped `message`, `buttons`
* labels, `selected` button index, `windowClass` semantic colour.
* @details `Dialog(title, message)`; `onResult(buttonIndex)` is the
* host's to emit when it wires the buttons (Dialog draws title+message;
* button widgets are composed by the host window). Prefer MessageBox.
*/
struct Dialog : Widget{
std::string title, message; std::vector<std::string> buttons{"OK"}; int selected=0; Signal<int> onResult; const Config* cfg=nullptr; std::string windowClass="grey";
std::vector<PushButton*> buttonWidgets;
Dialog(std::string t="",std::string m=""):title(std::move(t)),message(std::move(m)){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void ensureButtons(){ if(!buttonWidgets.empty()||buttons.empty()) return; for(size_t i=0;i<buttons.size();i++){ auto* b=emplace<PushButton>(buttons[i]); b->cfg=cfg; buttonWidgets.push_back(b); int idx=(int)i; b->onPressed.connect([this,idx](){ selected=idx; onResult.emit(idx); }); } layoutButtons(); }
void layoutButtons(){ ensureButtons(); Rect a=bounds; int y=std::max(0,a.h-2); int x=1; for(auto* b: buttonWidgets){ int w=b->measure().w; b->bounds={x,y,w,1}; x+=w+1; } }
void layout() override { ensureButtons(); layoutButtons(); for(auto& ch: children_) ch->layout(); }
void draw(Canvas& c) override { ensureButtons(); Rect a=absoluteBounds(); CellStyle s; if(cfg){ auto w=cfg->windowColor(windowClass); s.fg=w.fg; s.bg=w.bg; } else { s.fg=Color::rgb(0,0,0); s.bg=Color::rgb(170,170,170);} c.drawBox(a,s,cfg&&cfg->asciiMode); c.drawText(a.x+1,a.y,ellipsize(title,a.w-2),s); auto lines=wrapText(message,a.w-2); for(size_t i=0;i<lines.size()&&(int)i<a.h-3;i++) c.drawText(a.x+1,a.y+1+(int)i,lines[i],s,a.w-2); }
bool onKey(KeyEventData& k) override { ensureButtons(); if(buttons.empty()) return false; selected=std::clamp(selected,0,(int)buttons.size()-1); if(k.code==KeyCode::Left){ selected=std::max(0,selected-1); return true; } if(k.code==KeyCode::Right){ selected=std::min((int)buttons.size()-1,selected+1); return true; } if(k.code==KeyCode::Tab){ selected=(selected+1)%(int)buttons.size(); return true; } if(k.code==KeyCode::Enter){ onResult.emit(selected); return true; } if(k.code==KeyCode::Escape){ for(size_t i=0;i<buttons.size();i++) if(buttons[i]=="Cancel"||buttons[i]=="No"){ onResult.emit((int)i); return true; } return false; } return false; }
};
/**
* @brief Dialog with TT colour semantics, built by factories:
* `info(t,m)` (blue, [OK]), `errorBox(t,m)` (red, [OK]),
* `question(t,m)` (grey, [Yes, No]). Direct construction
* `MessageBox(title, message, windowClass)` is also available.
*/
struct MessageBox : Dialog{ MessageBox(std::string t="",std::string m="",std::string wc="grey"):Dialog(t,m){ windowClass=wc; } static std::unique_ptr<MessageBox> info(const std::string& t,const std::string& m){ auto d=std::make_unique<MessageBox>(t,m,"blue"); d->buttons={"OK"}; d->ensureButtons(); return d; } static std::unique_ptr<MessageBox> errorBox(const std::string& t,const std::string& m){ auto d=std::make_unique<MessageBox>(t,m,"red"); d->buttons={"OK"}; d->ensureButtons(); return d; } static std::unique_ptr<MessageBox> question(const std::string& t,const std::string& m){ auto d=std::make_unique<MessageBox>(t,m,"grey"); d->buttons={"Yes","No"}; d->ensureButtons(); return d; } };
/**
* @brief Directory listing with directories first.
* @details Fields: `path` ("." when empty), `entries` (refreshed snapshot),
* `selected`, `scroll`, `showHidden` (dotfiles). Signals:
* `onSelected(path)` on click selection, `onActivated(path)` on Enter or
* double-click. Methods: `refresh()` rescans (skipping hidden files
* unless showHidden, sorting directories first then by name, clamping
* selection); `selectedPath()` ("" when empty). Keys Up/Down move;
* wheel scrolls. draw() suffixes directories with '/'.
*/
struct FileList : Widget{
std::string path; std::vector<std::filesystem::directory_entry> entries; int selected=0, scroll=0; bool showHidden=false; const Config* cfg=nullptr; Signal<std::string> onActivated; Signal<std::string> onSelected;
FileList(){ focusable=true; focusPolicy=FocusPolicy::Strong; }
void refresh(){ entries.clear(); std::error_code ec; for(auto&e: std::filesystem::directory_iterator(path.empty()?".":path,ec)){ std::string n=e.path().filename().string(); if(!showHidden&&!n.empty()&&n[0]=='.') continue; entries.push_back(e); } std::sort(entries.begin(),entries.end(),[](auto&a,auto&b){ if(a.is_directory()!=b.is_directory()) return a.is_directory()>b.is_directory(); return a.path().filename().string()<b.path().filename().string(); }); if(selected>=(int)entries.size()) selected=std::max(0,(int)entries.size()-1); }
void draw(Canvas& c) override { Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->uiColor("paper",Color::rgb(255,255,255)):Color::rgb(255,255,255); bg.fg=cfg?cfg->uiColor("paperText",Color::rgb(0,0,0)):Color::rgb(0,0,0); if(hasStyleOverride) bg=styleOverride; c.drawInset(a,bg,cfg&&cfg->asciiMode); Rect inner=a.inset(1,0,1,0); for(int r=0;r<inner.h;r++){ int idx=scroll+r; if(idx>=(int)entries.size()) break; CellStyle s=bg; if(idx==selected){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); s.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255);} std::string name=entries[(size_t)idx].path().filename().string(); if(entries[(size_t)idx].is_directory()) name+="/"; c.fill({inner.x,inner.y+r,inner.w,1}," ",s); c.drawText(inner.x,inner.y+r,ellipsize(name,inner.w),s,inner.w); } }
bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up){ selected=std::max(0,selected-1); if(selected<scroll) scroll=selected; return true;} if(k.code==KeyCode::Down){ selected=std::min((int)entries.size()-1,selected+1); if(selected>=scroll+bounds.h) scroll++; return true;} if(k.code==KeyCode::Enter){ if(selected>=0&&selected<(int)entries.size()) onActivated.emit(entries[(size_t)selected].path().string()); return true;} return false; }
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); Rect inner=a.inset(1,0,1,0); if(m.kind==MouseKind::Wheel){ scroll=std::clamp(scroll+m.wheelDelta,0,std::max(0,(int)entries.size()-1)); return true;} if(m.kind==MouseKind::Down){ int idx=scroll+(m.pos.y-inner.y); if(idx>=0&&idx<(int)entries.size()){ selected=idx; onSelected.emit(entries[(size_t)idx].path().string()); return true; } } if(m.kind==MouseKind::DoubleClick){ if(selected>=0&&selected<(int)entries.size()) onActivated.emit(entries[(size_t)selected].path().string()); return true;} return false; }
std::string selectedPath() const { return selected>=0&&selected<(int)entries.size()?entries[(size_t)selected].path().string():""; }
};
/** @brief Dialog hosting a FileList + path EditBox; OK/Cancel via onResultPath. */
struct FileDialog : Dialog{
FileList* fileList=nullptr; EditBox* pathBox=nullptr; Signal<std::string> onResultPath;
FileDialog(const std::string& t="Open",const std::string& start="."):Dialog(t,""){ buttons={"OK","Cancel"}; auto* fl=emplace<FileList>(); fl->cfg=cfg; fl->path=start; fl->refresh(); fileList=fl; auto* eb=emplace<EditBox>(start); eb->cfg=cfg; pathBox=eb; onResult.connect([this](int idx){ if(idx==0) onResultPath.emit(fileList?fileList->selectedPath():std::string("")); }); ensureButtons(); }
void layout() override { Dialog::layout(); Rect a=bounds; if(pathBox) pathBox->bounds={1,1,std::max(1,a.w-2),1}; if(fileList) fileList->bounds={1,2,std::max(1,a.w-2),std::max(1,a.h-4)}; }
};
// ---------- Window ----------
/**
* @brief A framed, captioned window; the unit WindowManager moves around.
* @details Fields: `title`, `windowClass` (semantic colour), state flags
* `shaded` (rolled to caption), `sticky` (all workspaces + survives
* close-all), `maximized`, `minimized`, `modal`, `resizable`, `closable`,
* `savedRect` (pre-maximize geometry), `workspace`, `urgent` (unseen
* bell; caption draws red), `appName`, `content` (borrowed main child),
* signals `onClose`, `onFocusWin`.
* Methods: `Window(title, windowClass)`; `contentRect()` (inside the
* frame, empty height when shaded; parent-relative {1,1,w-2,h-2});
* `setContent(unique_ptr)` takes ownership, records content, and lays
* out; `layout()` (called on creation, drag, resize, and every render)
* fits content into contentRect() and lays out other children; `draw()` renders bevel, caption (close glyph
* at far left when closable, sticky and shade glyphs at right), centred
* title, and the resize glyph bottom-right — nothing when minimized
* (shadows are the manager's job); hit tests `isCaption(p)`,
* `isCloseBox(p)` (first caption cell), `isShadeBox(p)`,
* `isStickyBox(p)`, `isResizeBox(p)` (bottom-right cell);
* `serialize()`/`deserialize(v)` round-trip title, geometry, shaded,
* sticky, workspace, and windowClass as JSON.
*/
struct Window : Widget{
std::string title; std::string windowClass="grey"; const Config* cfg=nullptr;
bool shaded=false, sticky=false, maximized=false, minimized=false, modal=false, resizable=true, closable=true;
bool closing=false; int popFrames=0; int shadeFrames=0; ///< closeWindow() requested: hidden everywhere, destroyed by processPendingCloses()
Rect savedRect; int workspace=0; bool urgent=false; std::string appName;
Widget* content=nullptr; Signal<> onClose, onFocusWin; std::function<bool()> onCloseRequest; bool forceClose=false;
Window(std::string t="",std::string wc="grey"):title(std::move(t)),windowClass(std::move(wc)){ focusable=true; }
Rect contentRect() const { if(shaded) return {0,1,bounds.w,0}; return {1,1,std::max(0,bounds.w-2), std::max(0,bounds.h-2)}; }
void setContent(std::unique_ptr<Widget> w){ auto* raw=w.get(); addChild(std::move(w)); content=raw; layout(); }
void layout() override { if(content){ content->bounds=contentRect(); content->layout(); } for(auto&c:children_) if(c.get()!=content) c->layout(); }
void draw(Canvas& c) override {
Rect a=absoluteBounds(); if(minimized) return;
bool ascii=cfg&&cfg->asciiMode; WindowColor wc=cfg?cfg->windowColor(windowClass):WindowColor{Color::rgb(0,0,0),Color::rgb(170,170,170)};
CellStyle body; body.fg=wc.fg; body.bg=wc.bg; if(hasStyleOverride) body=styleOverride;
// shadow drawn by manager
// frame bevel
c.drawBevel({a.x,a.y,a.w, shaded?1:a.h}, body, true, ascii);
// caption
CellStyle cap; cap.bg=wc.bg; cap.fg=wc.fg; if(focused){ cap.bold=true; cap.bg=wc.bg; } if(urgent){ cap.bg=cfg?cfg->uiColor("urgent",Color::rgb(200,30,30)):Color::rgb(200,30,30); cap.fg=cfg?cfg->uiColor("selectionText",Color::rgb(255,255,255)):Color::rgb(255,255,255); }
c.fill({a.x,a.y,a.w,1}," ",cap);
std::string closeGlyph=cfg?cfg->glyph("close","[X]"):"[X]";
if(closable) c.drawText(a.x,a.y,ascii?"[X]":closeGlyph,cap);
// right boxes (same geometry as captionButtons())
for(auto& btn: captionButtons()){ std::string g=btn.second=="sticky"?(cfg?cfg->glyph("sticky","S"):"S"):btn.second=="shade"?(cfg?cfg->glyph("shade","_"):"_"):btn.second=="close"?(ascii?"[X]":closeGlyph):""; if(btn.second!="close") c.drawText(btn.first.x,a.y,g,cap); }
// title centred
std::string t=ellipsize(title, std::max(0,a.w-8)); int tx=a.x+std::max(0,(a.w-(int)t.size())/2);
c.drawText(tx,a.y,t,cap, (int)t.size());
if(!shaded&&a.h>1){
// resize box
if(resizable) c.drawText(a.right()-1,a.bottom()-1,cfg?cfg->glyph("resize","◢"):"◢",body);
}
}
std::vector<std::pair<Rect,std::string>> captionButtons() const { Rect a=absoluteBounds(); std::vector<std::pair<Rect,std::string>> out; if(closable) out.push_back({{a.x,a.y,1,1},"close"}); int rx=a.right()-1; if(resizable){ out.push_back({{rx,a.y,1,1},"sticky"}); rx-=2; } out.push_back({{rx,a.y,1,1},"shade"}); return out; }
bool isCaption(Point p) const { Rect a=absoluteBounds(); return p.y==a.y&&p.x>=a.x&&p.x<a.right(); }
bool captionHit(Point p, const std::string& act) const { for(auto& b: captionButtons()) if(b.second==act&&b.first.contains(p)) return true; return false; }
bool isCloseBox(Point p) const { return captionHit(p,"close"); }
bool isShadeBox(Point p) const { return captionHit(p,"shade"); }
bool isStickyBox(Point p) const { return captionHit(p,"sticky"); }
bool isResizeBox(Point p) const { Rect a=absoluteBounds(); return resizable&&!shaded&&p.x==a.right()-1&&p.y==a.bottom()-1; }
json::Value serialize() const { json::Object o; o["title"]=json::Value(title); o["x"]=json::Value(bounds.x); o["y"]=json::Value(bounds.y); o["w"]=json::Value(bounds.w); o["h"]=json::Value(bounds.h); o["shaded"]=json::Value(shaded); o["sticky"]=json::Value(sticky); o["workspace"]=json::Value(workspace); o["windowClass"]=json::Value(windowClass); return json::Value(std::move(o)); }
void deserialize(const json::Value& v){ if(auto*t=v.find("title")) title=t->asStr(title); if(auto*x=v.find("x")) bounds.x=x->asInt(); if(auto*y=v.find("y")) bounds.y=y->asInt(); if(auto*w=v.find("w")) bounds.w=w->asInt(); if(auto*h=v.find("h")) bounds.h=h->asInt(); if(auto*s=v.find("shaded")) shaded=s->asBool(); if(auto*s=v.find("sticky")) sticky=s->asBool(); if(auto*w=v.find("workspace")) workspace=w->asInt(); }
};
// ---------- Drag & Drop ----------
/** @brief Data carried by a drag: `type` tag ("text", "file", "colour", "row", ...), `text`, `row` (list source row, -1 otherwise), `colour`, `filePath`. Targets switch on type. */
struct DragPayload{ std::string type; std::string text; int row=-1; Color colour; std::string filePath; };
/**
* @brief State machine for one in-progress drag (owned by WindowManager).
* @details `start(payload, source, at)` begins; `update(pos)` tracks the
* cursor for the ghost; `cancel()` aborts with no delivery (Esc);
* `drop()` ends and returns the payload for the drop target. Fields:
* `active`, `payload`, `pos`, `source` (borrowed origin widget).
*/
struct DragManager{
bool active=false; DragPayload payload; Point pos; Widget* source=nullptr;
bool pending=false; Point startPos{}; int threshold=3; Widget* highlighted=nullptr;
void start(DragPayload p, Widget* src, Point at){ payload=std::move(p); source=src; pos=at; startPos=at; pending=false; highlighted=nullptr; active=true; }
// Deferred start: becomes active only once movement reaches `threshold`.
void startDeferred(DragPayload p, Widget* src, Point at){ payload=std::move(p); source=src; pos=at; startPos=at; pending=true; active=false; highlighted=nullptr; }
bool update(Point p){ pos=p; if(pending&&std::abs(p.x-startPos.x)+std::abs(p.y-startPos.y)>=threshold){ pending=false; active=true; } return active; }
void setHighlight(Widget* w){ highlighted=w; }
void cancel(){ active=false; pending=false; source=nullptr; highlighted=nullptr; }
DragPayload drop(){ auto p=payload; active=false; pending=false; source=nullptr; highlighted=nullptr; return p; }
};
// ---------- Bell ----------
/**
* @brief Routes bell requests per Config, with rate limiting.
* @details Wiring: `cfg` and `term` are set by Application; `nowMs` is
* advanced by the event loop; `onUrgent(source)` notifies the host (e.g.
* mark a window urgent). `ring(source)` — sources "app", "terminal",
* "error" — ignores error bells when bellOnError is off, collapses
* bursts within 100 ms, writes one audible BEL when bellAudible, and
* arms the visual flash until nowMs + bellVisualMs when bellVisual.
* `visualActive(now)` reports whether the flash is still on.
*/
struct BellService{
const Config* cfg=nullptr; Terminal* term=nullptr; long long lastBellMs=-1000000; int visualUntilMs=0; long long nowMs=0;
std::function<void(const std::string&)> onUrgent;
void ring(const std::string& source="app"){
if(!cfg) return;
if(source=="error"&&!cfg->bellOnError) return;
if(nowMs-lastBellMs<100) return;
lastBellMs=nowMs;
if(cfg->bellAudible&&term) term->bell();
if(cfg->bellVisual) visualUntilMs=(int)(nowMs+cfg->bellVisualMs);
if(onUrgent) onUrgent(source);
}
bool visualActive(long long now) const { return now<visualUntilMs; }
};
// ---------- WindowManager ----------
/**
* @brief Owns all windows and every window-level interaction.
* @details State: `windows` (owned, in z-order back-to-front),
* `focusedWin`/`focusedWidget` (borrowed), `workArea` (screen minus
* panels), `currentWorkspace`, drag session fields (`dragWin`,
* `dragOff`, `dragging`, `resizing`, `dragOrig`, `dragStart`), hooks
* `onWindowClosed`/`onWindowOpened`, and the `dragManager`.
* Methods: `addWindow(unique_ptr)` (assigns cfg, focuses, fires hook);
* `createWindow(title, windowClass, rect)` -> borrowed Window* (placed
* on the current workspace); `closeWindow(w)` (emits onClose, erases,
* refocuses the top remaining window; w must not be used afterwards);
* `focusWindow(w)` (raises to front, clears urgent/minimized, sets the
* focused flags); `setFocus(widget)` (widget-level focus bookkeeping);
* `visibleWindows()` (non-minimized, current workspace or sticky);
* `windowAt(p)` (topmost visible window at a point, shade-aware);
* `closeAllNonSticky()` (Delete-key behaviour, current workspace);
* `snapRect(r)` (in/out: snap to work area and other windows within
* Config::snapDistance); `constrain(r)` (min size 10x2, caption stays
* reachable); drag lifecycle `startDrag(w,p)`, `startResize(w,p)`,
* `updateDrag(p, snap)`, `endDrag()`, `cancelDrag()` (restores the
* original geometry); `maximize(w)` toggles savedRect <-> workArea;
* `switchWorkspace(i)` (clamped, refocuses top visible);
* `tasklist()` (windows for the taskbar: current workspace or sticky).
*/
struct WindowManager{
const Config* cfg=nullptr; std::vector<std::unique_ptr<Window>> windows; Window* focusedWin=nullptr; Widget* focusedWidget=nullptr;
Rect workArea{0,1,80,22}; int currentWorkspace=0;
// drag state
Window* dragWin=nullptr; Point dragOff; bool dragging=false, resizing=false; Rect dragOrig; Point dragStart;
std::function<void(Window*)> onWindowClosed, onWindowOpened;
std::vector<Window*> pendingClose; ///< windows marked Window::closing awaiting safe destruction
/// @brief True when `x` is window `w` or one of its descendants.
static bool isInWindow(Widget* x, const Window* w){ for(Widget* c=x;c;c=c->parent) if(c==(const Widget*)w) return true; return false; }
/// @brief True between closeWindow() and destruction (window already hidden/inert).
bool isPendingClose(const Window* w) const { return w && w->closing; }
DragManager dragManager;
void addWindow(std::unique_ptr<Window> w){ w->cfg=cfg; if(cfg&&cfg->effectsEnabled&&cfg->popEffect&&!cfg->reducedMotion) w->popFrames=3; w->layout(); Window* raw=w.get(); windows.push_back(std::move(w)); focusWindow(raw); if(onWindowOpened) onWindowOpened(raw); }
Window* createWindow(const std::string& title,const std::string& wc,Rect r){ auto w=std::make_unique<Window>(title,wc); w->bounds=r; w->workspace=currentWorkspace; Window* raw=w.get(); addWindow(std::move(w)); return raw; }
/**
* @brief Request that a window be closed. Destruction is DEFERRED:
* the window is marked closing (hidden from visibleWindows/tasklist/
* windowAt/render), all manager references into it are dropped, and
* onClose + onWindowClosed fire while it is still alive; the object is
* destroyed by processPendingCloses() at a safe point. This makes it
* safe to call from inside the window's own widget handlers (a Cancel
* button closing its own window), which synchronous destruction was not.
* Unknown, already-closing, or already-destroyed pointers are a no-op,
* so stale stored Window* (menu/console toggles) cannot crash it.
*/
void closeWindow(Window* w){
if(!w) return;
auto it=std::find_if(windows.begin(),windows.end(),[&](auto& p){return p.get()==w;});
if(it==windows.end()||w->closing) return;
if(w->onCloseRequest&&!w->forceClose&&!w->onCloseRequest()) return;
w->closing=true; pendingClose.push_back(w);
if(focusedWidget&&isInWindow(focusedWidget,w)){ focusedWidget->focused=false; focusedWidget=nullptr; }
if(dragWin==w){ dragging=false; resizing=false; dragWin=nullptr; }
if(kbWin==w){ kbMoveActive=false; kbWin=nullptr; }
if(dragManager.active&&isInWindow(dragManager.source,w)) dragManager.cancel();
w->onClose.emit(); // apps drop their widget pointers here
if(onWindowClosed) onWindowClosed(w); // Application purges focus/hover/terminal refs here
if(focusedWin==w){ focusedWin=nullptr; for(int i=(int)windows.size()-1;i>=0;--i) if(!windows[(size_t)i]->closing){ focusWindow(windows[(size_t)i].get()); break; } }
}
/**
* @brief Destroy every window marked by closeWindow(). Safe points:
* Application calls this at the top of render() and once per event-loop
* iteration; headless users call it after dispatching the close event.
* Refocuses the top remaining window afterwards.
*/
void processPendingCloses(){
if(pendingClose.empty()) return;
std::vector<Window*> dead; dead.swap(pendingClose);
for(Window* w: dead) windows.erase(std::remove_if(windows.begin(),windows.end(),[&](std::unique_ptr<Window>& p){return p.get()==w;}),windows.end());
if(focusedWin&&focusedWin->closing) focusedWin=nullptr;
if(!focusedWin){ for(int i=(int)windows.size()-1;i>=0;--i) if(!windows[(size_t)i]->closing){ focusWindow(windows[(size_t)i].get()); break; } }
}
void focusWindow(Window* w){ if(!w||w->closing) return; { auto it0=std::find_if(windows.begin(),windows.end(),[&](auto& p){return p.get()==w;}); if(it0==windows.end()) return; } focusedWin=w; w->urgent=false; w->minimized=false; // raise
auto it=std::find_if(windows.begin(),windows.end(),[&](auto& p){return p.get()==w;}); if(it!=windows.end()){ auto up=std::move(*it); windows.erase(it); windows.push_back(std::move(up)); focusedWin=(windows.back().get()); }
for(auto&win:windows) win->focused=false;
if(focusedWin) focusedWin->focused=true;
}
void setFocus(Widget* w){ if(focusedWidget) focusedWidget->focused=false; focusedWidget=w; if(w){ w->focused=true; w->onFocus.emit(); } }
std::vector<Window*> visibleWindows(){ std::vector<Window*> o; for(auto&w:windows) if(!w->closing&&!w->minimized&&(w->workspace==currentWorkspace||w->sticky)) o.push_back(w.get()); return o; }
Window* windowAt(Point p){ auto vis=visibleWindows(); for(int i=(int)vis.size()-1;i>=0;--i){ Rect a=vis[(size_t)i]->bounds; Rect abs{a.x,a.y,a.w, vis[(size_t)i]->shaded?1:a.h}; if(abs.contains(p)) return vis[(size_t)i]; } return nullptr; }
void closeAllNonSticky(){ std::vector<Window*> toClose; for(auto&w:windows) if(!w->sticky&&w->workspace==currentWorkspace) toClose.push_back(w.get()); for(auto*w:toClose) closeWindow(w); }
void snapRect(Rect& r){ if(!cfg) return; int d=cfg->snapDistance; if(std::abs(r.x-workArea.x)<=d) r.x=workArea.x; if(std::abs(r.y-workArea.y)<=d) r.y=workArea.y; if(std::abs(r.right()-workArea.right())<=d) r.x=workArea.right()-r.w; if(std::abs(r.bottom()-workArea.bottom())<=d) r.y=workArea.bottom()-r.h; for(auto&w:windows){ if(w->bounds.x==r.x&&w->bounds.y==r.y) continue; if(std::abs(r.x-w->bounds.right())<=d) r.x=w->bounds.right(); if(std::abs(r.right()-w->bounds.x)<=d) r.x=w->bounds.x-r.w; if(std::abs(r.y-w->bounds.bottom())<=d) r.y=w->bounds.bottom(); if(std::abs(r.bottom()-w->bounds.y)<=d) r.y=w->bounds.y-r.h; } }
Rect constrain(Rect r){ r.w=std::max(10,r.w); r.h=std::max(2,r.h); r.x=std::clamp(r.x, workArea.x-r.w+5, workArea.right()-3); r.y=std::clamp(r.y, workArea.y, workArea.bottom()-1); return r; }
bool isMember(Window* w) const { return w&&std::any_of(windows.begin(),windows.end(),[&](auto& p){return p.get()==w;}); }
void cascade(){ int x=workArea.x, y=workArea.y; for(auto* w: visibleWindows()){ w->bounds.x=x; w->bounds.y=y; w->bounds=constrain(w->bounds); x+=2; y+=1; if(x>workArea.right()-10){x=workArea.x; y=workArea.y;} w->layout(); } }
void tile(){ auto vis=visibleWindows(); if(vis.empty()) return; int n=(int)vis.size(); int cols=(int)std::ceil(std::sqrt((double)n)); int rows=(n+cols-1)/cols; int cw=workArea.w/std::max(1,cols), ch=workArea.h/std::max(1,rows); for(int i=0;i<n;i++){ vis[(size_t)i]->bounds={workArea.x+(i%cols)*cw, workArea.y+(i/cols)*ch, std::max(10,cw), std::max(2,ch)}; vis[(size_t)i]->layout(); } }
bool kbMoveActive=false; Window* kbWin=nullptr;
void startKeyboardMove(Window* w){ if(!isMember(w)||w->closing) return; kbWin=w; kbMoveActive=true; dragOrig=w->bounds; }
bool keyboardMove(KeyEventData& k){ if(!kbMoveActive||!isMember(kbWin)||kbWin->closing) return false; Rect b=kbWin->bounds; if(k.code==KeyCode::Left) b.x-= k.shift?0:1; else if(k.code==KeyCode::Right) b.x+= k.shift?0:1; else if(k.code==KeyCode::Up) b.y-= k.shift?0:1; else if(k.code==KeyCode::Down) b.y+= k.shift?0:1; else if(k.code==KeyCode::Enter){ kbMoveActive=false; kbWin=nullptr; return true; } else if(k.code==KeyCode::Escape){ kbWin->bounds=dragOrig; kbMoveActive=false; kbWin=nullptr; return true; } else return false; if(k.shift){ if(k.code==KeyCode::Left) b.w=std::max(10,b.w-1); if(k.code==KeyCode::Right) b.w++; if(k.code==KeyCode::Up) b.h=std::max(2,b.h-1); if(k.code==KeyCode::Down) b.h++; } kbWin->bounds=constrain(b); kbWin->layout(); return true; }
void startDrag(Window* w, Point p){ if(!isMember(w)||w->closing) return; dragWin=w; dragging=true; dragOrig=w->bounds; dragStart=p; dragOff={p.x-w->bounds.x,p.y-w->bounds.y}; }
void startResize(Window* w, Point p){ if(!isMember(w)||w->closing) return; dragWin=w; resizing=true; dragOrig=w->bounds; dragStart=p; }
void updateDrag(Point p, bool altSnap=true){ if(!dragWin) return; if(dragging){ Rect nr=dragWin->bounds; nr.x=p.x-dragOff.x; nr.y=p.y-dragOff.y; if(altSnap) snapRect(nr); dragWin->bounds=constrain(nr); dragWin->layout(); } if(resizing){ Rect nr=dragWin->bounds; nr.w=std::max(12, dragOrig.w+(p.x-dragStart.x)); nr.h=std::max(3, dragOrig.h+(p.y-dragStart.y)); dragWin->bounds=constrain(nr); dragWin->layout(); } }
void endDrag(){ dragging=false; resizing=false; dragWin=nullptr; }
void cancelDrag(){ if(dragWin) dragWin->bounds=dragOrig; endDrag(); }
void maximize(Window* w){ if(!w||w->closing||!isMember(w)) return; if(w->maximized){ w->bounds=w->savedRect; w->maximized=false; } else { w->savedRect=w->bounds; w->bounds=workArea; w->maximized=true; } w->layout(); }
void switchWorkspace(int ws){ currentWorkspace=std::clamp(ws,0, (cfg?cfg->workspaceCount:4)-1); focusedWin=nullptr; for(auto&w:windows) w->focused=false; auto vis=visibleWindows(); if(!vis.empty()) focusWindow(vis.back()); }
std::vector<Window*> tasklist(){ std::vector<Window*> o; for(auto&w:windows) if(!w->closing&&(w->workspace==currentWorkspace||w->sticky)) o.push_back(w.get()); return o; }
};
// ---------- IApp / Registry ----------
struct WindowManagerFwd;
class Application;
/**
* @brief An embeddable program hosted by the desktop.
* @details Implementations provide `name()` (menu/tasklist identity),
* optionally `glyph()` (panel icon, default "▣"), and
* `createWindow(wm, app)` which builds one or more windows through the
* WindowManager. `onActivate()`/`onClose()` are optional lifecycle hooks.
* Instances are created fresh by AppRegistry factories per launch.
* OWNERSHIP: the framework does not retain the IApp instance - callers
* typically destroy it as soon as createWindow() returns, while the
* windows (and their widget callbacks) live on. Widget lambdas must
* therefore capture the widgets they use (owned by the window), never
* `this`; a [this] capture in a widget callback is a use-after-free.
*/
struct IApp{
virtual ~IApp()=default; virtual std::string name() const =0; virtual std::string glyph() const { return "▣"; }
virtual void createWindow(WindowManager& wm, Application& app)=0; virtual void onActivate(){} virtual void onClose(){}
};
/**
* @brief Name -> factory registry for IApp programs.
* @details `add(name, glyph, factory)` registers (later registrations
* with the same name are shadowed by the first in find()); `find(name)`
* returns the Entry* or nullptr. Factories must return a fresh instance
* per call; the registry never owns live app instances.
*/
struct AppRegistry{
struct Entry{ std::string name, glyph; std::function<std::unique_ptr<IApp>()> factory; };
std::vector<Entry> entries;
void add(const std::string& n,const std::string& g,std::function<std::unique_ptr<IApp>()> f){ entries.push_back({n,g,std::move(f)}); }
Entry* find(const std::string& n){ for(auto&e:entries) if(e.name==n) return &e; return nullptr; }
};
// ---------- VirtualTerminal for tests ----------
/**
* @brief Headless screen used by tests (and usable by embedders):
* a Canvas plus accessors. `VirtualTerminal(w, h)`;
* `text()` (whole grid), `line(y)`, `cellAt(x,y)` (glyph + style),
* `find(text)` -> (x,y) or (-1,-1). No TTY is ever touched.
*/
struct VirtualTerminal{
Canvas canvas; int w=80,h=24; VirtualTerminal(int w_=80,int h_=24):w(w_),h(h_){ canvas.resize(w,h); }
std::string text() const { return canvas.text(); } std::string line(int y) const { return canvas.textLine(y); } Cell cellAt(int x,int y) const { return canvas.get(x,y); }
std::pair<int,int> find(const std::string& t) const { return canvas.findText(t); }
};
// ---------- Desktop ----------
/**
* @brief The wallpaper root widget: patterned background plus icon grid.
* @details Fields: `icons` ((glyph, label) pairs laid out in 14x3 cells),
* `selectedIcon`, rubber-band state (`rubberStart`, `rubber`, `rubberEnd`).
* draw() paints the Config wallpaper pattern ("shade"/"dots"/"none",
* '.' in ascii mode), icons (selected highlighted), and the rubber band.
* Mouse: Down selects the icon under the cursor (or clears) and starts a
* rubber band, Drag extends it, Up ends it, DoubleClick emits
* `onIconActivated(label)`; wheel is left to the Application (workspace
* switching).
*/
struct Desktop : Widget{
std::vector<std::pair<std::string,std::string>> icons; // glyph,label
int selectedIcon=-1; const Config* cfg=nullptr; Signal<std::string> onIconActivated;
Point rubberStart; bool rubber=false; Point rubberEnd;
void draw(Canvas& c) override {
Rect a=absoluteBounds(); CellStyle bg; bg.bg=cfg?cfg->wallpaperColor:Color::rgb(30,60,40); bg.fg=Color::rgb(80,120,80); if(hasStyleOverride) bg=styleOverride;
std::string pat="░"; if(cfg&&cfg->wallpaperPattern=="none") pat=" "; else if(cfg&&cfg->wallpaperPattern=="dots") pat="·"; else if(cfg&&cfg->asciiMode) pat=".";
for(int y=a.y;y<a.bottom();y++) for(int x=a.x;x<a.right();x++){ if((x+y)%2==0) c.set(x,y,pat,bg); else c.set(x,y," ",bg); }
int cols=std::max(1,a.w/14); int cw=14, ch=3;
for(size_t i=0;i<icons.size();i++){ int col=(int)i%cols, row=(int)i/cols; Rect r{a.x+1+col*cw, a.y+1+row*ch, cw-1, ch}; CellStyle s; s.fg=Color::rgb(255,255,255); s.bg=bg.bg; if((int)i==selectedIcon){ s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); } c.fill(r," ",s); c.drawText(r.x,r.y,icons[i].first,s); c.drawText(r.x,r.y+1,ellipsize(icons[i].second,cw-2),s,cw-2); }
if(rubber){ CellStyle s; s.fg=Color::rgb(255,255,255); s.bg=cfg?cfg->uiColor("selection",Color::rgb(36,80,180)):Color::rgb(36,80,180); int x1=std::min(rubberStart.x,rubberEnd.x), x2=std::max(rubberStart.x,rubberEnd.x), y1=std::min(rubberStart.y,rubberEnd.y), y2=std::max(rubberStart.y,rubberEnd.y); for(int x=x1;x<=x2;x++){ c.set(x,y1,"─",s); c.set(x,y2,"─",s);} for(int y=y1;y<=y2;y++){ c.set(x1,y,"│",s); c.set(x2,y,"│",s);} }
}
bool onMouse(MouseEventData& m) override { Rect a=absoluteBounds(); int cols=std::max(1,a.w/14); int cw=14, ch=3;
if(m.kind==MouseKind::Down){ int col=(m.pos.x-a.x-1)/cw, row=(m.pos.y-a.y-1)/ch; int idx=row*cols+col; if(idx>=0&&idx<(int)icons.size()&&col>=0&&row>=0){ selectedIcon=idx; rubberStart=m.pos; rubber=true; rubberEnd=m.pos; return true; } selectedIcon=-1; rubberStart=m.pos; rubber=true; rubberEnd=m.pos; return true; }
if(m.kind==MouseKind::Drag&&rubber){ rubberEnd=m.pos; return true; }
if(m.kind==MouseKind::Up){ bool wasRubber=rubber; rubber=false; if(wasRubber&&selectedIcon>=0){ /* click */ } return true; }
if(m.kind==MouseKind::DoubleClick&&selectedIcon>=0&&selectedIcon<(int)icons.size()){ onIconActivated.emit(icons[(size_t)selectedIcon].second); return true; }
if(m.kind==MouseKind::Wheel&&cfg){ /* workspace switch handled by app */ return false; }
return false; }
};
// ---------- Application ----------
/**
* @brief Owns the whole session and runs the single poll() event loop.
* @details Owned/wired state: `cfg` (moved in), `theme`, `terminal`,
* `parser`, `wm`, `registry`, `bell` (cfg+terminal wired in the ctor),
* double buffers `front`/`back`, `running`, `quitReason`, hooks
* `onTickExtra()` (per-frame, demo drives clock/ticker/tasklist here)
* and `onGlobalEvent(Event&)` (console toggle, window menu, ...),
* borrowed scene pointers `desktop`, `topPanel`, `bottomPanel`,
* focus/hover/capture bookkeeping (`focusedWidget`, `hovered`,
* `captured`, last-click triple for double-click detection), the shared
* `tooltipWidget`/`tooltipVisible`/`tooltipPos`, owned `notifications`
* (max 4, newest kept), borrowed `terminals`, and `tickMs`.
* Methods: `Application(Config)`; `setFocused(w)`/`focused()` keep
* Application and WindowManager focus in sync and emit onFocus;
* `registerTerminal(t)` wires a terminal's bell (suppressed while that
* terminal is focused when configured); `bellRing(source)` rings the
* BellService; `notify(title, body)` pushes a toast;
* `quit(reason)` ends run() after the current frame.
* `run()` — init terminal (headless-safe: without a TTY it still pumps
* events and renders in memory), then per iteration: poll stdin + every
* terminal fd (50 ms), feed InputParser, poll terminal outputs, detect
* resize by size polling, dispatch a Tick event, call onTickExtra,
* render into front and write diffRender(front, back) when on a TTY;
* restores the terminal and returns 0 on exit.
* `render(c)` paints, back to front: desktop, top panel, windows in
* z-order with drop shadows, bottom panel, notifications top-right,
* tooltip, drag ghost, and the visual-bell frame flash.
* `dispatchTick(e)` handles tooltip timing; `dispatch(e)` is the full
* router: global hook first, Resize re-layout, Paste to the focused
* widget, Key (terminal/edit global-focus rules, Alt+Tab rotate,
* Delete close-all, Ctrl+Q, F12/~ console, Tab traversal, Esc cancelling
* drags), Mouse (hover Enter/Leave, drag-and-drop delivery, caption
* close/shade/sticky/resize/maximize, wheel-over-caption shade, window
* drag/resize sessions, click focus, double-click synthesis, then
* target-then-parent bubbling to the hit widget).
*/
class Application{
public:
Config cfg; Theme theme; Terminal terminal; InputParser parser; WindowManager wm; AppRegistry registry; BellService bell;
Canvas front, back; bool running=false; std::string quitReason;
std::function<void()> onTickExtra; std::function<void(Event&)> onGlobalEvent;
Desktop* desktop=nullptr; Widget* topPanel=nullptr; Widget* bottomPanel=nullptr;
Widget* focusedWidget=nullptr; Widget* hovered=nullptr; Widget* captured=nullptr;
Point lastMouse; std::chrono::steady_clock::time_point lastClick; Point lastClickPos; Widget* lastClickWidget=nullptr;
Tooltip tooltipWidget; bool tooltipVisible=false; Point tooltipPos; long long hoverSinceMs=0;
std::vector<std::unique_ptr<Notification>> notifications;
std::vector<TerminalWidget*> terminals;
long long tickMs=0; TerminalWidget* urgentSrc=nullptr;
bool keyMatches(const std::string& action, const KeyEventData& k) const { std::string want=cfg.binding(action,""); if(want.empty()) return false; return k.name()==want; }
Window* windowForWidget(Widget* wgt) const { for(auto& wp: wm.windows){ if(WindowManager::isInWindow(wgt,wp.get())) return wp.get(); } return nullptr; }
void stepEffects(){ // stepped animations advanced once per tick
bool fx=cfg.effectsEnabled&&!cfg.reducedMotion;
for(auto& wp: wm.windows){ Window* w=wp.get(); if(!fx){ w->popFrames=0; w->shadeFrames=0; continue; } if(cfg.popEffect&&w->popFrames>0) w->popFrames--; if(cfg.shadeSlide&&w->shadeFrames>0) w->shadeFrames--; }
std::function<void(Widget*)> rec=[&](Widget* wgt){ if(!wgt) return; if(auto* sv=dynamic_cast<ScrollView*>(wgt)){ if(fx&&cfg.smoothScroll) sv->stepEffects(); } for(auto& ch: wgt->children()) rec(ch.get()); };
for(auto& wp: wm.windows) rec(wp.get());
if(desktop) rec(desktop);
if(topPanel) rec(topPanel);
if(bottomPanel) rec(bottomPanel);
}
explicit Application(Config c):cfg(std::move(c)),theme(&cfg){ wm.cfg=&cfg; bell.cfg=&cfg; bell.term=&terminal; tooltipWidget.visible=false;
// Every close (close box, Delete, app code) funnels through here while
// the window is still alive: drop every Application pointer into it so
// nothing dereferences the freed widgets afterwards (the segfault this
// prevents: dispatchTick reading hovered->tooltip of a closed editor).
wm.onWindowClosed=[this](Window* w){ purgeWindowRefs(w); };
bell.onUrgent=[this](const std::string& src){ (void)src; Window* target=nullptr; if(urgentSrc) target=windowForWidget((Widget*)urgentSrc); if(!target&&focusedWidget) target=windowForWidget(focusedWidget); if(target&&target!=wm.focusedWin) target->urgent=true; };
}
/**
* @brief Drop all Application references into a closing window:
* focused/hovered/captured/last-click widgets inside it are cleared,
* the tooltip is hidden, and TerminalWidgets inside it are unregistered
* (their PTYs stop being polled before the widget is destroyed).
* Called from WindowManager::closeWindow via onWindowClosed, while `w`
* and its children are still alive. Public for tests.
*/
void purgeWindowRefs(Window* w){
if(!w) return;
auto inside=[&](Widget* x){ return x&&WindowManager::isInWindow(x,w); };
if(inside(focusedWidget)){ focusedWidget->focused=false; focusedWidget=nullptr; wm.focusedWidget=nullptr; }
if(inside(hovered)){ hovered=nullptr; tooltipVisible=false; }
if(inside(captured)) captured=nullptr;
if(inside(lastClickWidget)) lastClickWidget=nullptr;
terminals.erase(std::remove_if(terminals.begin(),terminals.end(),[&](TerminalWidget* tw){ return inside((Widget*)tw); }),terminals.end());
}
void setFocused(Widget* w){ if(focusedWidget) focusedWidget->focused=false; focusedWidget=w; wm.focusedWidget=w; if(w){ w->focused=true; w->onFocus.emit(); } }
Widget* focused(){ return focusedWidget; }
void registerTerminal(TerminalWidget* t){ if(!t) return; if(std::find(terminals.begin(),terminals.end(),t)==terminals.end()) terminals.push_back(t); t->onBell=[this,t](){ if(cfg.bellSuppressFocused&&focusedWidget==(Widget*)t) return; urgentSrc=t; bell.ring("terminal"); urgentSrc=nullptr; }; }
void bellRing(const std::string& src="app"){ bell.ring(src); }
void notify(const std::string& title,const std::string& body){ auto n=std::make_unique<Notification>(); n->title=title; n->body=body; n->cfg=&cfg; n->expiresAtMs=tickMs+n->ttlMs; notifications.push_back(std::move(n)); if(notifications.size()>4) notifications.erase(notifications.begin()); }
int run(){
auto sz=terminal.size(); int W=sz.first, H=sz.second;
front.resize(W,H); back.resize(W,H); back.clear();
bool isTTY=terminal.init();
running=true;
auto lastTick=std::chrono::steady_clock::now();
// initial layout handled by demo via onTickExtra setup? demo sets desktop bounds before run
while(running){
// poll fds: pointer+fd kept paired so skipped fds cannot misindex
struct TermFd{ TerminalWidget* t; int fd; };
std::vector<TermFd> pairs; for(auto*t:terminals) if(t&&t->fd()>=0) pairs.push_back({t,t->fd()});
std::vector<pollfd> fds; fds.push_back({STDIN_FILENO,POLLIN,0});
for(auto& pr: pairs) fds.push_back({pr.fd,POLLIN,0});
int timeout=50; int r=poll(fds.data(),fds.size(),timeout);
if(r==0){ auto evs=parser.flushPending(); for(auto& e: evs) dispatch(e); }
auto now=std::chrono::steady_clock::now(); double dt=std::chrono::duration<double>(now-lastTick).count(); lastTick=now; tickMs+= (long long)(dt*1000);
bell.nowMs=tickMs;
if(r>0){
if(fds[0].revents&POLLIN){
char buf[8192]; ssize_t n=read(STDIN_FILENO,buf,sizeof(buf)); if(n>0){ auto evs=parser.feed(std::string(buf,(size_t)n)); for(auto&e:evs) dispatch(e); }
else if(n==0){ /* stdin closed in non-tty */ if(!isTTY) running=false; }
}
for(size_t i=0;i<pairs.size();i++){ if(i+1<fds.size()&&(fds[i+1].revents&(POLLIN|POLLHUP|POLLERR))){ TerminalWidget* t=pairs[i].t; // re-validate after any stdin dispatch may have closed windows
if(std::find(terminals.begin(),terminals.end(),t)!=terminals.end()&&t->fd()==pairs[i].fd) t->pollInput(); } }
// writability flush for queued terminal output
for(auto& pr: pairs){ if(std::find(terminals.begin(),terminals.end(),pr.t)!=terminals.end()&&pr.t->fd()==pr.fd) pr.t->flushOutput(); }
}
// SIGWINCH check via size poll
auto curSize=terminal.size(); if(curSize.first!=W||curSize.second!=H){ W=curSize.first; H=curSize.second; front.resize(W,H); back.resize(W,H); back.clear(); Event e=Event::makeResize(W,H); dispatch(e); }
// tick
Event tick=Event::makeTick(dt); dispatchTick(tick);
wm.processPendingCloses();
if(onTickExtra) onTickExtra();
// render
front.clear(); render(front);
std::string out=diffRender(front,back);
if(!out.empty()&&isTTY) terminal.writeStr(out);
back=front;
if(!isTTY){ // headless: run once then exit to avoid busy loop in tests
// if not tty, still loop but break after first frame if stdin closed
// continue; main will quit via event
if(!running) break;
// prevent infinite spin when stdin is pipe closed
// check stdin EOF handled above
}
}
terminal.restore();
return 0;
}
void quit(const std::string& reason=""){ quitReason=reason; running=false; }
void render(Canvas& c){
wm.processPendingCloses(); // safe destruction point: never inside a widget handler
Rect screen{0,0,c.width(),c.height()};
if(desktop){ desktop->bounds=screen; desktop->draw(c); }
if(topPanel){ topPanel->layout(); topPanel->drawTree(c); }
// windows in z order: re-layout every frame so a moved/resized window
// can never leave its content at the old place (parent-relative bounds)
for(auto& wptr0: wm.windows) wptr0->layout();
for(auto& wptr: wm.windows){
Window* w=wptr.get(); if(w->closing||w->minimized) continue; if(!(w->workspace==wm.currentWorkspace||w->sticky)) continue;
// shadow
if(cfg.dropShadow&&cfg.effectsEnabled&&!w->shaded){ Rect a=w->bounds; CellStyle sh; sh.fg=Color::rgb(0,0,0); sh.bg=Color::rgb(0,0,0); for(int y=a.y+1;y<std::min(c.height(),a.bottom()+1);y++) for(int x=a.right();x<std::min(c.width(),a.right()+1);x++) c.set(x,y,"░",sh); for(int x=a.x+1;x<std::min(c.width(),a.right()+1);x++) c.set(x,std::min(c.height()-1,a.bottom()),"░",sh); }
if(cfg.effectsEnabled&&cfg.popEffect&&w->popFrames>0){ Rect saved=w->bounds; int insetBy=w->popFrames; w->bounds=w->bounds.inset(insetBy,insetBy); w->layout(); w->drawTree(c); w->bounds=saved; w->layout(); } else w->drawTree(c);
}
if(bottomPanel){ bottomPanel->layout(); bottomPanel->drawTree(c); }
// notifications top-right
int ny= (topPanel?topPanel->bounds.h:1); for(size_t i=0;i<notifications.size();i++){ auto&n=notifications[i]; n->bounds={std::max(0,c.width()-36), ny+(int)i*3, 35,3}; n->draw(c); }
// tooltip
if(tooltipVisible&&hovered&&!hovered->tooltip.empty()){ tooltipWidget.text=hovered->tooltip; tooltipWidget.bounds={std::min(c.width()-22,lastMouse.x+1), std::min(c.height()-1,lastMouse.y+1), std::min(30,(int)hovered->tooltip.size()+2),1}; tooltipWidget.draw(c); }
// drag ghost
if(wm.dragManager.active){ CellStyle s; s.bg=Color::rgb(255,255,0); s.fg=Color::rgb(0,0,0); std::string g=wm.dragManager.payload.text.empty()?wm.dragManager.payload.type:wm.dragManager.payload.text; c.drawText(wm.dragManager.pos.x,wm.dragManager.pos.y,ellipsize(g,20),s,20); }
// visual bell flash
if(bell.visualActive(tickMs)){ CellStyle s; s.bg=cfg.uiColor("paper",Color::rgb(255,255,255)); s.fg=cfg.uiColor("paperText",Color::rgb(0,0,0)); for(int x=0;x<c.width();x++){ c.set(x,0," ",s); c.set(x,c.height()-1," ",s);} }
}
void dispatchTick(Event& e){ (void)e;
stepEffects();
notifications.erase(std::remove_if(notifications.begin(),notifications.end(),[&](auto& n){ return n->expiresAtMs>0&&tickMs>=n->expiresAtMs; }),notifications.end());
if(hovered&&!hovered->tooltip.empty()){ if(tickMs-hoverSinceMs>cfg.tooltipDelayMs) tooltipVisible=true; }
}
Window* modalWindow() const { Window* m=nullptr; for(auto& w: wm.windows) if(w->modal&&!w->closing&&!w->minimized&&(w->workspace==wm.currentWorkspace||w->sticky)) m=w.get(); return m; }
void dispatch(Event& e){
if(onGlobalEvent) onGlobalEvent(e);
if(e.type==EventType::Resize){ if(desktop) desktop->layout(); if(topPanel) topPanel->layout(); if(bottomPanel) bottomPanel->layout(); for(auto&w:wm.windows){ if(w->maximized) w->bounds=wm.workArea; w->layout(); } return; }
// Modal blocking: key/mouse input goes only to the topmost modal window.
if(Window* mw=modalWindow()){
bool inModal = focusedWidget&&WindowManager::isInWindow(focusedWidget,mw);
if(e.type==EventType::Key&&!inModal&&!(wm.focusedWin==mw&&mw->content)){
if(mw->content){ Event ev=e; mw->content->onEvent(ev); e.handled=ev.handled; }
e.handled=true; return;
}
if(e.type==EventType::Mouse&&e.mouse.kind!=MouseKind::Move){
if(!mw->bounds.contains(e.mouse.pos)){ e.handled=true; return; }
}
}
if(e.type==EventType::Paste){ if(focusedWidget){ Event pe=e; focusedWidget->onEvent(pe); if(pe.handled) { e.handled=true; return; } } return; }
if(e.type==EventType::Key){
bool editFocused=dynamic_cast<EditBox*>(focusedWidget)!=nullptr||dynamic_cast<TextEditor*>(focusedWidget)!=nullptr;
bool termFocused=dynamic_cast<TerminalWidget*>(focusedWidget)!=nullptr;
bool isQuit=keyMatches("quit",e.key); bool isConsole=keyMatches("console",e.key)||(e.key.isChar()&&e.key.text=="~"&&cfg.binding("console","F12")=="F12");
bool isSwitch=keyMatches("switchWindow",e.key); bool isCloseAll=keyMatches("closeAll",e.key);
if(wm.keyboardMove(e.key)) return;
if(keyMatches("keyboardMove",e.key)&&wm.focusedWin){ wm.startKeyboardMove(wm.focusedWin); return; }
if(keyMatches("cascade",e.key)){ wm.cascade(); return; }
if(keyMatches("tile",e.key)){ wm.tile(); return; }
if(termFocused&&focusedWidget){
if(isQuit){ quit(cfg.binding("quit","Ctrl+Q")); return; }
if(isConsole){ Event c=Event::makeCustom("consoleToggle"); if(onGlobalEvent) onGlobalEvent(c); return; }
Event ev=e; if(focusedWidget->onEvent(ev)){ e.handled=true; return; }
// unhandled terminal keys fall through only to global switch/close handling below, never re-dispatched to focused widget
if(!isSwitch&&!isCloseAll) return;
}
if(editFocused&&focusedWidget){
if(e.key.code==KeyCode::Escape){ setFocused(nullptr); return; }
if(isQuit){ quit(cfg.binding("quit","Ctrl+Q")); return; }
if(isConsole){ Event c=Event::makeCustom("consoleToggle"); if(onGlobalEvent) onGlobalEvent(c); return; }
Event ev=e; if(focusedWidget->onEvent(ev)){ e.handled=true; return; }
return; // edit consumed-or-not: never fall through to closeAll/content re-dispatch
}
if(isSwitch){ auto vis=wm.tasklist(); if(vis.size()>1){ Window* next=vis[0]; int idx=-1; for(size_t i=0;i<vis.size();i++) if(vis[i]==wm.focusedWin) idx=(int)i; next=vis[(size_t)((idx+1)%(int)vis.size())]; wm.focusWindow(next); if(next->content) setFocused(next->content); } return; }
if(isCloseAll){ wm.closeAllNonSticky(); return; }
if(isQuit){ quit(cfg.binding("quit","Ctrl+Q")); return; }
if(isConsole){ Event c=Event::makeCustom("consoleToggle"); if(onGlobalEvent) onGlobalEvent(c); return; }
if(e.key.code==KeyCode::Tab){
// focus traversal within focused window
std::vector<Widget*> focusables; std::function<void(Widget*)> collect=[&](Widget* w){ if(!w||!w->visible) return; if(w->focusable&&w->enabled) focusables.push_back(w); for(auto&ch:w->children()) collect(ch.get()); };
if(wm.focusedWin) collect(wm.focusedWin); else if(desktop) collect(desktop);
if(!focusables.empty()){ int idx=-1; for(size_t i=0;i<focusables.size();i++) if(focusables[i]==focusedWidget) idx=(int)i; int ni=e.key.shift? (idx<=0?(int)focusables.size()-1:idx-1) : (idx+1)%(int)focusables.size(); setFocused(focusables[(size_t)ni]); }
return;
}
if(e.key.code==KeyCode::Escape){
if(wm.dragManager.active){ wm.dragManager.cancel(); return; }
if(wm.dragging||wm.resizing){ wm.cancelDrag(); return; }
tooltipVisible=false;
}
if(focusedWidget){ Event ev=e; if(focusedWidget->onEvent(ev)) return; }
if(wm.focusedWin&&wm.focusedWin->content){ Event ev=e; wm.focusedWin->content->onEvent(ev); }
return;
}
if(e.type==EventType::Mouse){
Point p=e.mouse.pos; lastMouse=p;
if(e.mouse.kind==MouseKind::Down){ for(size_t ni=0;ni<notifications.size();ni++){ auto& n=notifications[ni]; Rect nb=n->bounds; if(n->closable&&nb.contains(p)&&p.x>=nb.right()-2){ notifications.erase(notifications.begin()+(long)ni); e.handled=true; return; } } }
// mouse capture: route Drag/Move/Up to the press owner regardless of hit-test
if(captured&&!wm.dragging&&!wm.resizing&&(e.mouse.kind==MouseKind::Drag||e.mouse.kind==MouseKind::Move||e.mouse.kind==MouseKind::Up||e.mouse.kind==MouseKind::DragEnd)){
Widget* cap=captured; Event ev=e; bool handled=cap->onEvent(ev); if(handled) e.handled=true;
if(e.mouse.kind==MouseKind::Up||e.mouse.kind==MouseKind::DragEnd) captured=nullptr;
return;
}
// update hover
Widget* hit=nullptr;
// windows topmost first for hit
auto vis=wm.visibleWindows();
// check notifications close etc simplified
for(int i=(int)vis.size()-1;i>=0;--i){ Window* w=vis[(size_t)i]; if(auto*h=w->hitTest(p)){ hit=h; break; } }
if(!hit&&topPanel) hit=topPanel->hitTest(p);
if(!hit&&bottomPanel) hit=bottomPanel->hitTest(p);
if(!hit&&desktop) hit=desktop->hitTest(p);
if(hit!=hovered){ if(hovered){ Event le=Event::makeMouse(MouseKind::Leave,p); hovered->onEvent(le); } hovered=hit; hoverSinceMs=tickMs; tooltipVisible=false; if(hovered){ Event en=Event::makeMouse(MouseKind::Enter,p); hovered->onEvent(en); } }
// drag manager update
if(wm.dragManager.active||wm.dragManager.pending){ wm.dragManager.update(p); wm.dragManager.setHighlight(hit); if(e.mouse.kind==MouseKind::Up){ if(wm.dragManager.active&&hit) { Event de; de.type=EventType::Drop; de.pasteText=wm.dragManager.payload.text; de.dragType=wm.dragManager.payload.type; de.dragText=wm.dragManager.payload.text; de.dragFile=wm.dragManager.payload.filePath; de.dragRow=wm.dragManager.payload.row; hit->onEvent(de); } wm.dragManager.drop(); return; } if(e.key.code==KeyCode::Escape){ wm.dragManager.cancel(); return; } }
// window caption handling
if(e.mouse.kind==MouseKind::Down){
Window* w=wm.windowAt(p);
if(w){
wm.focusWindow(w); if(w->content) { /* focus content later if hit is content */ }
if(w->isCloseBox(p)&&w->closable){ wm.closeWindow(w); return; }
if(w->isShadeBox(p)){ w->shaded=!w->shaded; if(cfg.effectsEnabled&&cfg.shadeSlide) w->shadeFrames=3; w->layout(); return; }
if(w->isStickyBox(p)){ w->sticky=!w->sticky; return; }
if(w->isResizeBox(p)&&w->resizable){ wm.startResize(w,p); captured=w; return; }
if(w->isCaption(p)){
// double click caption -> maximize
auto now=std::chrono::steady_clock::now(); long long ms=std::chrono::duration_cast<std::chrono::milliseconds>(now-lastClick).count();
if(ms<cfg.doubleClickMs&&lastClickWidget==(Widget*)w){ wm.maximize(w); lastClick=std::chrono::steady_clock::time_point{}; return; }
lastClick=now; lastClickWidget=w;
if(e.mouse.button==2){ /* right click window menu handled by demo via global */ Event ce=Event::makeCustom("windowMenu"); ce.mouse=e.mouse; if(onGlobalEvent) onGlobalEvent(ce); return; }
if(e.mouse.button==0){ wm.startDrag(w,p); captured=w; return; }
if(e.mouse.kind==MouseKind::Wheel){ }
}
// border resize: bottom/right edge
Rect a=w->bounds; if(w->resizable&&(p.x==a.right()-1||p.y==a.bottom()-1)){ wm.startResize(w,p); captured=w; return; }
}
}
if(e.mouse.kind==MouseKind::Wheel){
// wheel over caption shade
Window* w=wm.windowAt(p); if(w&&w->isCaption(p)){ w->shaded=!w->shaded; if(cfg.effectsEnabled&&cfg.shadeSlide) w->shadeFrames=3; w->layout(); return; }
}
if((e.mouse.kind==MouseKind::Drag||e.mouse.kind==MouseKind::Move)&&(wm.dragging||wm.resizing)){ wm.updateDrag(p); if(e.mouse.kind==MouseKind::Up||e.mouse.kind==MouseKind::DragEnd) wm.endDrag(); return; }
if(e.mouse.kind==MouseKind::Up){ if(wm.dragging||wm.resizing){ wm.endDrag(); captured=nullptr; return; } }
// deliver to hit widget, capture->target->bubble simplified: target first then parents
if(hit){
// focus on click if focusable
if(e.mouse.kind==MouseKind::Down&&hit->focusable) setFocused(hit);
else if(e.mouse.kind==MouseKind::Down){ // find focusable ancestor
Widget* cur=hit; while(cur&&!cur->focusable) cur=cur->parent; if(cur) setFocused(cur);
}
// capture phase: root->target onCapture before bubbling
{ std::vector<Widget*> chain; Widget* cc=hit; while(cc){ chain.push_back(cc); cc=cc->parent; } std::reverse(chain.begin(),chain.end()); bool capHandled=false; for(auto* wgt: chain){ Event cev=e; if(wgt->onCapture(cev)){ e.handled=true; capHandled=true; break; } } if(capHandled) return; }
if(cfg.focusFollowsMouse&&hit){ Widget* cur2=hit; while(cur2&&!dynamic_cast<Window*>(cur2)) cur2=cur2->parent; if(cur2&&wm.focusedWin!=(Window*)cur2) wm.focusWindow((Window*)cur2); }
// double click detection
if(e.mouse.kind==MouseKind::Down){ auto now=std::chrono::steady_clock::now(); long long ms=std::chrono::duration_cast<std::chrono::milliseconds>(now-lastClick).count(); if(ms<cfg.doubleClickMs&&hit==lastClickWidget&&std::abs(p.x-lastClickPos.x)<=1&&std::abs(p.y-lastClickPos.y)<=1){ Event de=Event::makeMouse(MouseKind::DoubleClick,p,e.mouse.button); de.mouse.wheelDelta=e.mouse.wheelDelta; Widget* cur=hit; while(cur){ Event ev=de; if(cur->onEvent(ev)) break; cur=cur->parent; } lastClick=std::chrono::steady_clock::time_point{}; return; } lastClick=now; lastClickPos=p; lastClickWidget=hit; }
Widget* cur=hit; Event ev=e; // bubble
bool handled=false; while(cur){ Event copy=ev; if(cur->onEvent(copy)){ ev.handled=true; handled=true; break; } cur=cur->parent; }
if(e.mouse.kind==MouseKind::Down&&handled) captured=hit;
return;
} else {
if(e.mouse.kind==MouseKind::Down&&desktop){ Event ev=e; desktop->onEvent(ev); }
}
return;
}
}
};
// Helpers for demo
/** @brief Local time formatted with a strftime format (panel clock). */
inline std::string nowTimeStr(const std::string& fmt){
std::time_t t=std::time(nullptr); char buf[64]; std::tm tmv{}; localtime_r(&t,&tmv); std::strftime(buf,sizeof(buf),fmt.c_str(),&tmv); return buf;
}
/** @brief "$USER@hostname" for the status bar; user defaults to "user". */
inline std::string userHostStr(){ const char* u=getenv("USER"); if(!u) u="user"; char hn[128]; gethostname(hn,sizeof(hn)); return std::string(u)+"@"+hn; }
/**
* @brief CPU busy percentage between successive calls, from /proc/stat.
* @details Stateful (function-local previous totals): the first call
* returns 0; later calls return 100 * (1 - idleDelta/totalDelta).
* Returns 0 when /proc/stat is unreadable.
*/
inline double cpuUsage(){
static long long prevTotal=0, prevIdle=0; std::ifstream in("/proc/stat"); std::string cpu; long long user=0,nice=0,sys=0,idle=0,iowait=0,irq=0,soft=0,steal=0; if(in>>cpu>>user>>nice>>sys>>idle>>iowait>>irq>>soft>>steal){ long long total=user+nice+sys+idle+iowait+irq+soft+steal; long long idleAll=idle+iowait; double usage=0; if(prevTotal>0){ long long dt=total-prevTotal, di=idleAll-prevIdle; if(dt>0) usage=100.0*(1.0-double(di)/dt); } prevTotal=total; prevIdle=idleAll; return usage; } return 0;
}
/** @brief "AVAIL/TOTAL MB free" from /proc/meminfo (MemAvailable/MemTotal); zeros when unreadable. */
inline std::string memFreeStr(){ std::ifstream in("/proc/meminfo"); std::string k; long long v=0; std::string u; long long total=0,avail=0; while(in>>k>>v>>u){ if(k=="MemTotal:") total=v; if(k=="MemAvailable:") avail=v; } char buf[64]; std::snprintf(buf,sizeof(buf),"%lld/%lld MB free", avail/1024, total/1024); return buf; }
} // namespace ttgui