#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 #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(__linux__) #include #endif namespace ttgui { // ---------- JSON ---------- namespace json { struct Value; using Array = std::vector; using Object = std::map; /** * @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 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(v); } bool isBool() const { return std::holds_alternative(v); } bool isNum() const { return std::holds_alternative(v); } bool isStr() const { return std::holds_alternative(v); } bool isArr() const { return std::holds_alternative(v); } bool isObj() const { return std::holds_alternative(v); } bool asBool(bool d=false) const { auto*p=std::get_if(&v); return p?*p:d; } double asNum(double d=0) const { auto*p=std::get_if(&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(&v); return p?*p:d; } const Array* asArr() const { return std::get_if(&v); } const Object* asObj() const { return std::get_if(&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 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 stringVal(){ if(peek()!='"') {err="expected string"; return std::nullopt;} get(); std::string out; while(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>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 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 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;imsg=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<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=y&&p.y= 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 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 windowColors; std::map ttColors; std::map uiColors; ///< widget base colours by role: paper, paperText, selection, selectionText, disabledText, menuPaper, iconGridBg, badgeBg, badgeUrgent, urgent, progressTrack, progressFill std::map 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 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 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 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(in)), std::istreambuf_iterator()); 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<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 class Signal{ std::vector>> slots; int nextId=1; public: int connect(std::function 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 cells; Rect clipRect; std::vector 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;ytext.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 findText(const std::string& needle) const { for(int y=0;y& 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 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 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 flushPending(){ std::vector 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 flushEsc(){ return flushPending(); } bool hasPendingEsc() const { return buf=="\033"; } std::vector feed(const std::string& data){ std::vector out; buf+=data; size_t i=0; while(ikMaxPaste){ 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(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[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: [=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+1buf.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 split(const std::string& s,char d){ std::vector 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)` -> borrowed child pointer (sets * parent, takes ownership), `emplace(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 onKeySignal; Signal 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 ch){ ch->parent=this; children_.push_back(std::move(ch)); return children_.back().get(); } template T* emplace(A&&... a){ auto up=std::make_unique(std::forward(a)...); T* raw=up.get(); addChild(std::move(up)); return raw; } const std::vector>& 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> 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 wrapText(const std::string& t, int w){ std::vector lines; if(w<=0) return lines; std::istringstream iss(t); std::string word, line; // simple: split by \n then wrap std::vector 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;ibounds={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;iuiColor("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 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 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 buttons; int selectedIndex=-1; RadioButton* addRadio(const std::string& l){ auto* r=emplace(l); r->onSelected.connect([this,r](){ select(r); }); buttons.push_back(r); return r; } void select(RadioButton* r){ for(size_t i=0;iselected=(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 undoStack; Signal 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(cursor-off,(size_t)inner-1); if(a.x+1+(int)cx50) 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(cursor0) cursor--; return true; } if(k.code==KeyCode::Right){ if(cursortext.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 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;iuiColor("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 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;si0) 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+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 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 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;x1) 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> series; std::vector legend; std::vector colors{Color::rgb(220,40,40),Color::rgb(40,80,220),Color::rgb(40,200,80)}; std::vector 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;si0){ 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&&yy2){ std::string leg; for(size_t i=0;i 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=thumbPos&&yglyph("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=thumbPos&&x items; int selected=-1, scroll=0; const Config* cfg=nullptr; Signal onSelected; Signal 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=(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+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=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?xy;}); } }; /** * @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 cells; std::function cellDraw; const Config* cfg=nullptr; Signal 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;ruiColor("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=0&&row headers; std::vector> rows; std::vector colWidths; int selected=0, scroll=0, sortCol=-1; bool sortAsc=true; const Config* cfg=nullptr; Signal 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=inner.right()) break; } for(int r=0;r=(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=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?ab; }); } bool onKey(KeyEventData& k) override { if(k.code==KeyCode::Up){ selected=std::max(0,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=x&&m.pos.x=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 items; int selected=0; bool open=false, editable=false; const Config* cfg=nullptr; Signal onSelected; Signal 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;i1?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=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(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(scrollYscrollTarget) 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(scrollYscrollTarget) 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;y0) 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 tabs; int active=0; const Config* cfg=nullptr; Signal 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;iuiColor("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;ivisible=((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=x&&m.pos.x children; bool expanded=true; }; std::vector roots; int selected=0; const Config* cfg=nullptr; Signal onSelected; TreeView(){ focusable=true; focusPolicy=FocusPolicy::Strong; } std::vector> flat() const { std::vector> out; std::function 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 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=(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;dchildren.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 items; int selected=-1, cols=4; const Config* cfg=nullptr; Signal onActivated; Signal 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;ia.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 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()&&xa.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 action; }; std::vector items; int selected=0; bool open=false; int revealRows=1000000; const Config* cfg=nullptr; Signal 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(int)items.size()?0:0); if(items[i].separator){ CellStyle s=bg; for(int x=a.x+1;xuiColor("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 menus; int selected=-1; const Config* cfg=nullptr; Signal 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;iuiColor("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=x&&m.pos.x