Files

167 lines
13 KiB
Markdown
Raw Permalink Normal View History

# Agentic Specification for HTab application: C++ Spreadsheet Engine & GemUI (X11) Frontend
## 1. Objective
Design and implement a lightweight, high-performance spreadsheet application in **C++17/20** with a native **X11 GUI** built on the **GemUI** framework (as used in the ANODE desktop ~/proj/anode).
The application must:
1. Decouple the headless calculation engine (`libcalc`) from the X11/GemUI frontend so the engine can be compiled and unit-tested independently.
2. Implement a complete reactive formula engine with a **100-function library** (OpenFormula Small Group / Pocket Excel baseline + `SUMIFS`, `COUNTIFS`, and `FILTER` with dynamic array spilling).
3. Support **CSV (RFC 4180)** as the primary interoperability format, alongside a lightweight native format for saving formulas, formatting, and multi-sheet workbooks.
4. Scale cleanly down to **240x296** resolution (PDA/Pocket PC class displays) while remaining fully usable via keyboard and pointer.
---
## 2. Project Architecture
Organize the repository into strict, modular boundaries:
* `engine/` — Headless C++ static library (`libcalc`) with zero X11/GemUI dependencies.
* `value.hpp/.cpp` — Cell value variant (Number, String, Boolean, Empty, Error, Array2D).
* `lexer.hpp/.cpp` & `parser.hpp/.cpp` — Formula tokenizer and Pratt/Shunting-yard AST parser.
* `evaluator.hpp/.cpp` — AST evaluator, type coercion, and error propagation.
* `functions/` — Modular implementations of the 100-function library.
* `dag.hpp/.cpp` — Dependency graph, topological sort, cycle detection, and spill-range tracking.
* `workbook.hpp/.cpp` — Multi-sheet model, sparse cell storage, structural edits, and Undo/Redo command stack.
* `io_csv.hpp/.cpp` — RFC 4180 CSV importer/exporter.
* `io_native.hpp/.cpp` — Native workbook serialization (JSON or compact text/binary) preserving formulas, column widths, and number formats.
* `ui/` — X11 + GemUI frontend linking against `libcalc`.
* `app_window.hpp/.cpp` — Main GemUI window, adaptive layout manager (desktop to 240x296).
* `grid_widget.hpp/.cpp` — Virtualized 2D grid canvas/widget, selection model, inline editor, fill-handle.
* `formula_bar.hpp/.cpp` — Synchronized address indicator + formula input bar.
* `tests/` — Automated unit test suite (Catch2, GoogleTest, or minimal custom harness) covering parser quirks, DAG recalculation, spilling, structural shifts, CSV round-tripping, and all 100 functions.
---
## 3. Core Calculation Engine (`libcalc`) Specifications
### 3.1 Data Model & Display Separation
* **Sparse Storage:** Store cells in a sparse structure (e.g., hash map keyed by `(row, col)` or row-indexed B-tree) to keep memory footprint minimal on constrained hardware.
* **Dual Cell State:** Every cell stores its **raw input** (string) and its **evaluated value** (`Value`).
* **Primitives:**
* `double` (IEEE 754 floating-point)
* `std::string` (UTF-8)
* `bool`
* `Empty`
* `Error` (first-class values that propagate through formulas): `#DIV/0!`, `#VALUE!`, `#NAME?`, `#N/A`, `#REF!`, `#NUM!`, `#CYCLE!`, `#SPILL!`
* `Array2D` (for range evaluation and dynamic array results)
* **Dates & Times:** Store as serial numbers (days since epoch; fractional part represents time of day) so date arithmetic works natively.
* **Number Formatting:** Separate formatting strings (General, Fixed decimal, Currency, Percentage, Date/Time) from underlying numeric values.
### 3.2 Addressing, Ranges & Referential Integrity
* **A1 Notation:** Columns `A..Z, AA..ZZ...`, 1-based rows, rectangular ranges (`A1:C10`), and cross-sheet references (`Sheet2!A1`, `'My Sheet'!A1:B5`).
* **Relative & Absolute Anchors:** Support `A1`, `$A1`, `A$1`, `$A$1`. Copy/paste and fill-handle operations must rewrite relative references accordingly.
* **Structural Edits:** Inserting or deleting rows/columns must automatically rewrite all affected cell references and ranges across all sheets. Deleting a cell referenced by a formula must replace that reference with `#REF!`.
* **Undo / Redo:** Implement a Command pattern stack capturing both cell edits and structural mutations (row/col insert/delete, sheet rename/delete).
### 3.3 Operator Precedence & Spreadsheet Quirks
Implement exact spreadsheet operator precedence (highest to lowest; parentheses `()` override all):
| Priority | Operator | Description | Associativity |
| :--- | :--- | :--- | :--- |
| **1** | `:` , ` ` , `,` | Range (`A1:B2`), intersection (space), union (`,`) | Left-to-right |
| **2** | `-` , `+` | Unary negation / unary plus | Right-to-left |
| **3** | `%` | Postfix percent (divides by 100) | Left-to-right |
| **4** | `^` | Exponentiation | **Left-to-right** |
| **5** | `*` , `/` | Multiplication and division | Left-to-right |
| **6** | `+` , `-` | Addition and subtraction | Left-to-right |
| **7** | `&` | Text concatenation | Left-to-right |
| **8** | `=`, `<>`, `<`, `>`, `<=`, `>=` | Comparison operators | Left-to-right |
**Mandatory Parser Quirks:**
1. Unary minus binds tighter than exponentiation: `=-2^2` MUST evaluate to `4`, while `=0-2^2` evaluates to `-4`.
2. Exponentiation is left-associative: `=2^3^2` MUST evaluate to `64`.
### 3.4 Dependency Graph (DAG) & Dynamic Array Spilling
* **Incremental Recalculation:** Maintain forward (dependents) and backward (precedents) edges. On edit, mark only downstream cells dirty and recalculate in topological order.
* **Cycle Detection:** Detect circular dependencies during topological sort and assign `#CYCLE!` without hanging.
* **Dynamic Array Spilling (for `FILTER`):**
* When a formula evaluates to an `Array2D`, spill its values into adjacent empty cells starting from the origin cell.
* If any target cell in the spill rectangle is non-empty, set the origin cell to `#SPILL!` and do not overwrite existing data.
* Track spill-range ownership so editing a blocking cell clears `#SPILL!`, and downstream formulas referencing spilled cells recalculate properly.
---
## 4. Complete 100-Function Library
Implement all 100 functions below (`[param]` = optional, `...` = variadic).
### Math & Trig (27)
`ABS(number)`, `ACOS(number)`, `ASIN(number)`, `ATAN(number)`, `ATAN2(x_num, y_num)`, `COS(number)`, `DEGREES(angle)`, `EXP(number)`, `FACT(number)`, `INT(number)`, `LN(number)`, `LOG(number, [base])`, `LOG10(number)`, `MOD(number, divisor)`, `PI()`, `POWER(number, power)`, `PRODUCT(number1, [number2, ...])`, `RADIANS(angle)`, `RAND()`, `ROUND(number, num_digits)`, `SIN(number)`, `SQRT(number)`, `SUM(number1, [number2, ...])`, `SUMIF(range, criteria, [sum_range])`, `SUMIFS(sum_range, criteria_range1, criteria1, [criteria_range2, criteria2, ...])`, `TAN(number)`, `TRUNC(number, [num_digits])`
### Logical (6)
`AND(logical1, [logical2, ...])`, `FALSE()`, `IF(logical_test, value_if_true, [value_if_false])`, `NOT(logical)`, `OR(logical1, [logical2, ...])`, `TRUE()`
### Statistical (12)
`AVERAGE(number1, [number2, ...])`, `COUNT(value1, [value2, ...])`, `COUNTA(value1, [value2, ...])`, `COUNTBLANK(range)`, `COUNTIF(range, criteria)`, `COUNTIFS(criteria_range1, criteria1, [criteria_range2, criteria2, ...])`, `MAX(number1, [number2, ...])`, `MIN(number1, [number2, ...])`, `STDEV(number1, [number2, ...])`, `STDEVP(number1, [number2, ...])`, `VAR(number1, [number2, ...])`, `VARP(number1, [number2, ...])`
### Lookup & Reference (8)
`CHOOSE(index_num, value1, [value2, ...])`, `COLUMNS(array)`, `FILTER(array, include, [if_empty])`, `HLOOKUP(lookup_value, table_array, row_index_num, [range_lookup])`, `INDEX(array, row_num, [column_num])`, `MATCH(lookup_value, lookup_array, [match_type])`, `ROWS(array)`, `VLOOKUP(lookup_value, table_array, col_index_num, [range_lookup])`
### Text (14)
`EXACT(text1, text2)`, `FIND(find_text, within_text, [start_num])`, `LEFT(text, [num_chars])`, `LEN(text)`, `LOWER(text)`, `MID(text, start_num, num_chars)`, `PROPER(text)`, `REPLACE(old_text, start_num, num_chars, new_text)`, `REPT(text, number_times)`, `RIGHT(text, [num_chars])`, `SUBSTITUTE(text, old_text, new_text, [instance_num])`, `T(value)`, `TRIM(text)`, `UPPER(text)`
### Date & Time (11)
`DATE(year, month, day)`, `DATEVALUE(date_text)`, `DAY(serial_number)`, `HOUR(serial_number)`, `MINUTE(serial_number)`, `MONTH(serial_number)`, `NOW()`, `SECOND(serial_number)`, `TIME(hour, minute, second)`, `TIMEVALUE(time_text)`, `YEAR(serial_number)`
### Financial (10)
`DDB(cost, salvage, life, period, [factor])`, `FV(rate, nper, pmt, [pv], [type])`, `IRR(values, [guess])`, `NPER(rate, pmt, pv, [fv], [type])`, `NPV(rate, value1, [value2, ...])`, `PMT(rate, nper, pv, [fv], [type])`, `PV(rate, nper, pmt, [fv], [type])`, `RATE(nper, pmt, pv, [fv], [type], [guess])`, `SLN(cost, salvage, life)`, `SYD(cost, salvage, life, per)`
### Database (12)
Implement one shared `filterDatabase(database, criteria)` helper (same row = AND, different rows = OR) powering all 12 functions with signature `(database, field, criteria)`:
`DAVERAGE`, `DCOUNT`, `DCOUNTA`, `DGET`, `DMAX`, `DMIN`, `DPRODUCT`, `DSTDEV`, `DSTDEVP`, `DSUM`, `DVAR`, `DVARP`
---
## 5. Persistence & CSV Interoperability
* **CSV (Primary Interop):**
* Full RFC 4180 compliance (quoted fields, embedded commas, escaped `""`, CRLF/LF handling).
* Import: Auto-parse numeric, boolean, and formula (`=...`) strings into typed cells.
* Export: Export active sheet's evaluated values by default, with an option to export raw formulas.
* **Native Format:** Provide a clean JSON (or compact text) save/load format for multi-sheet workbooks, preserving raw formulas, column widths, row heights, and number formats.
---
## 6. X11 / GemUI Frontend & 240x296 Responsive Design
### 6.1 GemUI / X11 Integration
* Inspect the local GemUI headers/build setup in the workspace before writing UI code so all widget classes, event loops, themes, and X11 drawing primitives match the installed GemUI API (ANODE desktop conventions).
* **Virtualized Grid Rendering:** Render *only* the cells intersecting the visible viewport. Never allocate per-cell GemUI widgets; draw grid lines, headers, selection highlights, and clipped cell text directly onto a custom GemUI/X11 drawable surface with double-buffering to prevent flicker.
### 6.2 Compact Layout Budget (240x296 Support)
The UI must adapt gracefully from desktop resolutions down to **240x296** without clipping controls or losing functionality:
* **Compact Mode Threshold:** When window width <= 320px or height <= 360px, switch to Compact Mode:
* **Top Chrome (~40-48px total):** Merge menu access into a compact single-row toolbar/menu trigger and a single-line **Formula Bar** (`[A1] [=SUM(A1:A5)]`). Hide verbose icon toolbars.
* **Grid Viewport (~220-230px height):** Use compact row headers (width ~24px), compact column headers (height ~16px), and tight cell padding (default col width ~48-56px, row height ~16-18px) so at least 3-4 columns and 10+ rows are visible simultaneously at 240x296.
* **Bottom Chrome (~18-20px):** Compact scrollable sheet-tab strip (`S1`, `S2`, `+`) sharing a single row with a minimal horizontal scrollbar.
* **Zero-Overlap Dialogs:** File open/save (CSV/Native) and format dialogs must fit within 240x296.
### 6.3 Ergonomics & Keyboard-First Navigation
* `Arrow keys`: Move active cell; auto-scroll viewport to keep active cell visible.
* `Shift + Arrows`: Extend range selection.
* `Enter` / `Tab`: Commit edit and move down / right (`Shift+Enter` / `Shift+Tab` for reverse).
* `Esc`: Cancel active edit and restore previous value.
* Typing directly on a selected cell immediately enters edit mode; `F2` edits in place.
* `Ctrl+C` / `Ctrl+X` / `Ctrl+V`: Internal copy/paste with relative reference translation, plus X11 clipboard integration (TSV/CSV text) for pasting to/from external apps.
* `Ctrl+Z` / `Ctrl+Y`: Undo / Redo.
* Pointer support: Click to select, drag to select range, drag header borders to resize columns/rows, drag selection corner fill-handle to auto-fill.
---
## 7. Coding Standards & Constraints
* **No emojis in code, comments, commit messages, or UI strings.**
* **Warning-free C++17/20:** Compile with `-Wall -Wextra -Wpedantic`.
* **No external bloated dependencies:** Keep `libcalc` dependency-free (C++ standard library only). Link only against X11 and GemUI for the frontend.
* **Deterministic tests:** All engine features must be verified by automated tests before moving to the UI phase.
---
## 8. Phased Implementation Plan
Execute in this exact order, verifying each phase with builds and tests before proceeding:
1. **Phase 1 — Core Engine & Parser:** Implement `Value`, sparse `Sheet`/`Workbook`, `Lexer`, `Parser` (with precedence quirks), and `Evaluator`. Add unit tests for `=-2^2`, `=2^3^2`, error propagation, and type coercion.
2. **Phase 2 — DAG, Structural Edits & Spilling:** Implement dependency graph, topological sort, `#CYCLE!` detection, row/col insert/delete reference rewriting, Undo/Redo, and dynamic array spilling (`#SPILL!`).
3. **Phase 3 — 100-Function Library:** Implement all 8 function categories (Math/Trig, Logical, Statistical, Lookup/Ref including `FILTER`, Text, Date/Time, Financial, and the shared Database engine). Write unit tests covering every function.
4. **Phase 4 — CSV & Native I/O:** Implement RFC 4180 CSV import/export and native workbook serialization with round-trip tests.
5. **Phase 5 — GemUI / X11 Frontend:** Inspect GemUI APIs, build the virtualized grid widget, formula bar, keyboard/clipboard navigation, and Compact Mode layout.
6. **Phase 6 — 240x296 Verification:** Launch and test the application explicitly constrained to a `240x296` window (e.g., via Xephyr/Xvfb or window geometry flags), verifying grid scrolling, formula editing, sheet switching, and CSV import/export.