commit 395f458fee49f7a8865504a3aafacce00f1ef58c Author: Luxferre Date: Mon Nov 30 17:45:17 2026 +0200 Initial commit: HTab spreadsheet engine and GemUI X11 frontend diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fc77574 --- /dev/null +++ b/.gitignore @@ -0,0 +1,4 @@ +build/ +*.o +*.a +*.so diff --git a/.gitmodules b/.gitmodules new file mode 100644 index 0000000..4d74e20 --- /dev/null +++ b/.gitmodules @@ -0,0 +1,3 @@ +[submodule "libgemui"] + path = libgemui + url = https://code.luxferre.top/luxferre/libgemui.git diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9773947 --- /dev/null +++ b/Makefile @@ -0,0 +1,309 @@ +# HTab Spreadsheet Engine & GemUI X11 Frontend +# Strict POSIX-compatible Makefile. + +.POSIX: + +PREFIX = /usr/local +DESTDIR = +CC = cc +CXX = c++ +AR = ar +STRIP = strip +PKG_CONFIG = pkg-config +GEMUI_DIR = libgemui +GEMUI_STATIC = 1 +GEMUI_DEPS = build/libgemui/libgemui.a +STRIP_BIN = 1 +CFLAGS = -O2 +CXXFLAGS = -O2 +LDFLAGS = + +GEMUI_PKG_DEPS = x11 xext xft xinerama xrandr cairo pangocairo pango harfbuzz fontconfig freetype2 +BASE_CXXFLAGS = -std=c++20 -Wall -Wextra -Wpedantic -I. + +CALC_OBJS = \ + build/engine/value.o \ + build/engine/address.o \ + build/engine/format.o \ + build/engine/lexer.o \ + build/engine/parser.o \ + build/engine/evaluator.o \ + build/engine/dag.o \ + build/engine/workbook.o \ + build/engine/io_csv.o \ + build/engine/io_native.o \ + build/engine/functions/registry.o \ + build/engine/functions/helpers.o \ + build/engine/functions/math_trig.o \ + build/engine/functions/logical.o \ + build/engine/functions/statistical.o \ + build/engine/functions/lookup.o \ + build/engine/functions/text.o \ + build/engine/functions/datetime.o \ + build/engine/functions/financial.o \ + build/engine/functions/database.o + +TEST_OBJS = \ + build/tests/test_main.o \ + build/tests/test_phase1.o \ + build/tests/test_phase2.o \ + build/tests/test_phase3.o \ + build/tests/test_phase4.o + +UI_OBJS = \ + build/ui/main.o \ + build/ui/clipboard.o \ + build/ui/formula_bar.o \ + build/ui/grid_widget.o \ + build/ui/app_window.o + +all: calc htab + +help: + @printf 'HTab build & install targets:\n' + @printf ' make Build libcalc.a and htab\n' + @printf ' make calc Build headless engine library (build/libcalc.a)\n' + @printf ' make htab Build X11/GemUI application (build/htab)\n' + @printf ' make test Build and run unit tests (build/htab_tests)\n' + @printf ' make rebuild Clean and rebuild all targets\n' + @printf ' make clean Remove build/ directory\n' + @printf ' make install Install htab binary to %s/bin/htab\n' "$(PREFIX)" + @printf ' make uninstall Remove installed htab binary\n' + @printf '\nOptions (override on command line):\n' + @printf ' PREFIX=%-18s Install / pkg-config prefix\n' "$(PREFIX)" + @printf ' DESTDIR=%-17s Staging directory for packaging\n' "$(DESTDIR)" + @printf ' CC=%-22s C compiler (for libgemui)\n' "$(CC)" + @printf ' CXX=%-21s C++ compiler\n' "$(CXX)" + @printf ' AR=%-22s Archiver\n' "$(AR)" + @printf ' PKG_CONFIG=%-14s pkg-config command\n' "$(PKG_CONFIG)" + @printf ' GEMUI_DIR=%-15s libgemui submodule/source directory\n' "$(GEMUI_DIR)" + @printf ' GEMUI_STATIC=%-12s 1=static libgemui.a (default), 0=dynamic libgemui.so\n' "$(GEMUI_STATIC)" + @printf ' GEMUI_DEPS=%-14s Archive target for build/htab (empty if GEMUI_STATIC=0)\n' "$(GEMUI_DEPS)" + @printf ' STRIP=%-19s Strip utility\n' "$(STRIP)" + @printf ' STRIP_BIN=%-15s 1=strip build/htab (default), 0=keep symbols\n' "$(STRIP_BIN)" + @printf ' CFLAGS=%-18s C compiler flags\n' "$(CFLAGS)" + @printf ' CXXFLAGS=%-16s C++ optimization/debug flags\n' "$(CXXFLAGS)" + @printf ' LDFLAGS=%-17s Linker flags\n' "$(LDFLAGS)" + +calc: build/libcalc.a + +htab: build/htab + +rebuild: + $(MAKE) clean + $(MAKE) PREFIX="$(PREFIX)" CC="$(CC)" CXX="$(CXX)" AR="$(AR)" STRIP="$(STRIP)" PKG_CONFIG="$(PKG_CONFIG)" GEMUI_DIR="$(GEMUI_DIR)" GEMUI_STATIC="$(GEMUI_STATIC)" GEMUI_DEPS="$(GEMUI_DEPS)" STRIP_BIN="$(STRIP_BIN)" CFLAGS="$(CFLAGS)" CXXFLAGS="$(CXXFLAGS)" LDFLAGS="$(LDFLAGS)" all + +clean: + rm -rf build + +# --- Headless Calculation Engine (libcalc) --- +build/engine/value.o: engine/value.cpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/value.cpp -o build/engine/value.o + +build/engine/address.o: engine/address.cpp engine/address.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/address.cpp -o build/engine/address.o + +build/engine/format.o: engine/format.cpp engine/format.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/format.cpp -o build/engine/format.o + +build/engine/lexer.o: engine/lexer.cpp engine/lexer.hpp engine/address.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/lexer.cpp -o build/engine/lexer.o + +build/engine/parser.o: engine/parser.cpp engine/parser.hpp engine/lexer.hpp engine/address.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/parser.cpp -o build/engine/parser.o + +build/engine/evaluator.o: engine/evaluator.cpp engine/evaluator.hpp engine/functions/registry.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/evaluator.cpp -o build/engine/evaluator.o + +build/engine/dag.o: engine/dag.cpp engine/dag.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/dag.cpp -o build/engine/dag.o + +build/engine/workbook.o: engine/workbook.cpp engine/workbook.hpp engine/dag.hpp engine/evaluator.hpp engine/format.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/workbook.cpp -o build/engine/workbook.o + +build/engine/io_csv.o: engine/io_csv.cpp engine/io_csv.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/io_csv.cpp -o build/engine/io_csv.o + +build/engine/io_native.o: engine/io_native.cpp engine/io_native.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/io_native.cpp -o build/engine/io_native.o + +build/engine/functions/registry.o: engine/functions/registry.cpp engine/functions/registry.hpp engine/evaluator.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/registry.cpp -o build/engine/functions/registry.o + +build/engine/functions/helpers.o: engine/functions/helpers.cpp engine/functions/helpers.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/helpers.cpp -o build/engine/functions/helpers.o + +build/engine/functions/math_trig.o: engine/functions/math_trig.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/math_trig.cpp -o build/engine/functions/math_trig.o + +build/engine/functions/logical.o: engine/functions/logical.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/logical.cpp -o build/engine/functions/logical.o + +build/engine/functions/statistical.o: engine/functions/statistical.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/statistical.cpp -o build/engine/functions/statistical.o + +build/engine/functions/lookup.o: engine/functions/lookup.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/lookup.cpp -o build/engine/functions/lookup.o + +build/engine/functions/text.o: engine/functions/text.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/text.cpp -o build/engine/functions/text.o + +build/engine/functions/datetime.o: engine/functions/datetime.cpp engine/format.hpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/datetime.cpp -o build/engine/functions/datetime.o + +build/engine/functions/financial.o: engine/functions/financial.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/financial.cpp -o build/engine/functions/financial.o + +build/engine/functions/database.o: engine/functions/database.cpp engine/functions/helpers.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/engine/functions + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c engine/functions/database.cpp -o build/engine/functions/database.o + +build/libcalc.a: $(CALC_OBJS) + @mkdir -p build + rm -f build/libcalc.a + $(AR) rcs build/libcalc.a $(CALC_OBJS) + +# --- Automated Unit Test Suite --- +build/tests/test_main.o: tests/test_main.cpp tests/test_framework.hpp + @mkdir -p build/tests + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c tests/test_main.cpp -o build/tests/test_main.o + +build/tests/test_phase1.o: tests/test_phase1.cpp tests/test_framework.hpp engine/address.hpp engine/format.hpp engine/lexer.hpp engine/parser.hpp engine/value.hpp engine/workbook.hpp + @mkdir -p build/tests + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c tests/test_phase1.cpp -o build/tests/test_phase1.o + +build/tests/test_phase2.o: tests/test_phase2.cpp tests/test_framework.hpp engine/address.hpp engine/workbook.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/tests + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c tests/test_phase2.cpp -o build/tests/test_phase2.o + +build/tests/test_phase3.o: tests/test_phase3.cpp tests/test_framework.hpp engine/functions/registry.hpp engine/evaluator.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/tests + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c tests/test_phase3.cpp -o build/tests/test_phase3.o + +build/tests/test_phase4.o: tests/test_phase4.cpp tests/test_framework.hpp engine/io_csv.hpp engine/io_native.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp + @mkdir -p build/tests + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -c tests/test_phase4.cpp -o build/tests/test_phase4.o + +build/htab_tests: $(TEST_OBJS) build/libcalc.a + $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -o build/htab_tests $(TEST_OBJS) build/libcalc.a $(LDFLAGS) + +test: build/htab_tests + ./build/htab_tests + +# --- GemUI / X11 Frontend --- +build/ui_flags.sh: Makefile + @mkdir -p build build/ui build/libgemui + @set -e; \ + pc_path="$(PREFIX)/lib/pkgconfig"; \ + if [ -n "$${PKG_CONFIG_PATH:-}" ]; then pc_path="$$pc_path:$$PKG_CONFIG_PATH"; fi; \ + for dir in /usr/local/lib/pkgconfig /usr/local/libdata/pkgconfig /usr/pkg/lib/pkgconfig /usr/lib/pkgconfig /usr/share/pkgconfig; do \ + if [ -d "$$dir" ]; then pc_path="$$pc_path:$$dir"; fi; \ + done; \ + gemui_cflags=$$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --cflags $(GEMUI_PKG_DEPS)); \ + need_rpath=0; \ + if [ "$(GEMUI_STATIC)" = "1" ]; then \ + if [ -f "$(GEMUI_DIR)/gemui.h" ] && [ -f "$(GEMUI_DIR)/gemui.c" ]; then \ + raw_cflags="-I$(GEMUI_DIR) $$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --cflags cairo x11)"; \ + raw_libs="build/libgemui/libgemui.a $$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --libs $(GEMUI_PKG_DEPS))"; \ + else \ + gemui_libdir=$$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --variable=libdir gemui 2>/dev/null || printf '%s/lib' "$(PREFIX)"); \ + if [ -f "$$gemui_libdir/libgemui.a" ]; then \ + raw_cflags=$$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --cflags gemui cairo x11); \ + raw_libs="$$gemui_libdir/libgemui.a $$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --libs $(GEMUI_PKG_DEPS))"; \ + else \ + printf 'htab: error: libgemui sources not found in %s and static libgemui.a not found in %s.\n' "$(GEMUI_DIR)" "$$gemui_libdir" >&2; \ + printf 'Run "git submodule update --init" or install libgemui.a (or pass GEMUI_STATIC=0).\n' >&2; \ + exit 1; \ + fi; \ + fi; \ + else \ + need_rpath=1; \ + raw_cflags=$$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --cflags gemui cairo x11); \ + raw_libs=$$(PKG_CONFIG_PATH="$$pc_path" $(PKG_CONFIG) --libs gemui cairo x11); \ + fi; \ + ui_cflags=""; \ + for tok in $$raw_cflags; do \ + case "$$tok" in \ + -I*) ui_cflags="$$ui_cflags -isystem $${tok#-I}" ;; \ + *) ui_cflags="$$ui_cflags $$tok" ;; \ + esac; \ + done; \ + ui_libs="$$raw_libs"; \ + if [ "$$need_rpath" = "1" ]; then \ + case " $$ui_libs " in \ + *" -Wl,-rpath,$(PREFIX)/lib "*) ;; \ + *) ui_libs="$$ui_libs -Wl,-rpath,$(PREFIX)/lib" ;; \ + esac; \ + fi; \ + case " $$ui_libs " in \ + *" -lm "*) ;; \ + *) ui_libs="$$ui_libs -lm" ;; \ + esac; \ + printf "GEMUI_CFLAGS='%s'\nUI_CFLAGS='%s'\nUI_LIBS='%s'\n" "$$gemui_cflags" "$$ui_cflags" "$$ui_libs" > build/ui_flags.sh.tmp; \ + mv -f build/ui_flags.sh.tmp build/ui_flags.sh + +build/libgemui/gemui.o: $(GEMUI_DIR)/gemui.c $(GEMUI_DIR)/gemui.h $(GEMUI_DIR)/gemui_internal.h $(GEMUI_DIR)/gemui_scale.h build/ui_flags.sh + @mkdir -p build/libgemui + . ./build/ui_flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -I$(GEMUI_DIR) -DANODE_PREFIX="\"$(PREFIX)\"" $$GEMUI_CFLAGS -c $(GEMUI_DIR)/gemui.c -o build/libgemui/gemui.o + +build/libgemui/gemui_filedialog.o: $(GEMUI_DIR)/gemui_filedialog.c $(GEMUI_DIR)/gemui.h $(GEMUI_DIR)/gemui_internal.h build/ui_flags.sh + @mkdir -p build/libgemui + . ./build/ui_flags.sh && $(CC) $(CFLAGS) -std=c11 -Wall -Wextra -I$(GEMUI_DIR) $$GEMUI_CFLAGS -c $(GEMUI_DIR)/gemui_filedialog.c -o build/libgemui/gemui_filedialog.o + +build/libgemui/libgemui.a: build/libgemui/gemui.o build/libgemui/gemui_filedialog.o + @mkdir -p build/libgemui + rm -f build/libgemui/libgemui.a + $(AR) rcs build/libgemui/libgemui.a build/libgemui/gemui.o build/libgemui/gemui_filedialog.o + +build/ui/main.o: ui/main.cpp ui/app_window.hpp ui/clipboard.hpp ui/formula_bar.hpp ui/grid_widget.hpp ui/text_edit.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp build/ui_flags.sh + @mkdir -p build/ui + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) $$UI_CFLAGS -c ui/main.cpp -o build/ui/main.o + +build/ui/clipboard.o: ui/clipboard.cpp ui/clipboard.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp build/ui_flags.sh + @mkdir -p build/ui + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) $$UI_CFLAGS -c ui/clipboard.cpp -o build/ui/clipboard.o + +build/ui/formula_bar.o: ui/formula_bar.cpp ui/formula_bar.hpp ui/text_edit.hpp build/ui_flags.sh + @mkdir -p build/ui + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) $$UI_CFLAGS -c ui/formula_bar.cpp -o build/ui/formula_bar.o + +build/ui/grid_widget.o: ui/grid_widget.cpp ui/grid_widget.hpp ui/text_edit.hpp engine/workbook.hpp engine/address.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp build/ui_flags.sh + @mkdir -p build/ui + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) $$UI_CFLAGS -c ui/grid_widget.cpp -o build/ui/grid_widget.o + +build/ui/app_window.o: ui/app_window.cpp ui/app_window.hpp ui/clipboard.hpp ui/formula_bar.hpp ui/grid_widget.hpp ui/text_edit.hpp engine/workbook.hpp engine/address.hpp engine/io_csv.hpp engine/io_native.hpp engine/parser.hpp engine/lexer.hpp engine/value.hpp build/ui_flags.sh + @mkdir -p build/ui + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) $$UI_CFLAGS -c ui/app_window.cpp -o build/ui/app_window.o + +build/htab: $(UI_OBJS) build/libcalc.a $(GEMUI_DEPS) build/ui_flags.sh + . ./build/ui_flags.sh && $(CXX) $(CXXFLAGS) $(BASE_CXXFLAGS) -o build/htab $(UI_OBJS) build/libcalc.a $(LDFLAGS) $$UI_LIBS + @if [ "$(STRIP_BIN)" = "1" ]; then printf '%s build/htab\n' "$(STRIP)"; $(STRIP) build/htab; fi + +install: htab + mkdir -p "$(DESTDIR)$(PREFIX)/bin" + cp build/htab "$(DESTDIR)$(PREFIX)/bin/htab" + chmod 755 "$(DESTDIR)$(PREFIX)/bin/htab" + +uninstall: + rm -f "$(DESTDIR)$(PREFIX)/bin/htab" + +.PHONY: all help calc htab test rebuild install uninstall clean diff --git a/README.md b/README.md new file mode 100644 index 0000000..7e73f60 --- /dev/null +++ b/README.md @@ -0,0 +1,67 @@ +# HTab + +**HTab** (short for *Hacker's Tables*) is a fast, lightweight standalone X11 spreadsheet built in C++20. It pairs an engine library (`libcalc`) with ANODE's `libgemui` toolkit (statically linked by default so `htab` runs cleanly outside ANODE on any X11 desktop), scaling from HiDPI screens down to `240x296` pocket displays. + +## Features + +- **Fast formula engine (`libcalc`)**: Incremental dependency graph recalculation, circular reference detection (`#CYCLE!`), dynamic array spilling (`#SPILL!`), and full Undo/Redo across edits and structural shifts. +- **100 built-in functions**: Math & Trig (27), Logical (6), Statistical (12), Lookup & Reference including `FILTER` spilling (8), Text (14), Date & Time (11), Financial (10), and Database `D*` functions (12). +- **CSV and multi-sheet save files**: Full RFC 4180 CSV import/export (evaluated values or raw formulas) alongside a clean `.htab` JSON format that keeps formulas, multiple sheets, column widths, row heights, and number formats. +- **Responsive X11 UI**: Automatically reads ANODE/X11 DPI scaling (`Xft.dpi`, `theme.scale`, `theme.touchMode`) on desktop displays and switches into Compact Mode at `<= 320x360` (tested down to `240x296`). + +## Build & Install + +HTab uses a strict POSIX `Makefile`. + +### Prerequisites + +- C++20 compiler (`g++` or `clang++`), C11 compiler (`cc`), and `ar` +- For the GUI (`htab`): `pkg-config`, standard X11/Cairo/Pango/HarfBuzz/Fontconfig/FreeType development libraries, and the bundled `libgemui/` Git submodule (`git clone --recursive` or `git submodule update --init`). `libgemui.a` is built and statically linked by default (`GEMUI_STATIC=1`) so `htab` needs no ANODE runtime files (pass `GEMUI_STATIC=0 GEMUI_DEPS=""` for system shared `libgemui.so`). The calculation engine and tests (`make calc`, `make test`) require only the C++20 standard library. + +### Commands + +```sh +git submodule update --init # Fetch the libgemui submodule if not cloned with --recursive +make -j # Build build/libcalc.a, build/libgemui/libgemui.a, and build/htab +make test # Build and run the headless engine unit tests (no X11 needed) +sudo make install # Install the htab binary to /usr/local/bin/htab +``` + +Run `make help` for additional options (`PREFIX`, `DESTDIR`, `CC`, `CXX`, `CFLAGS`, `CXXFLAGS`, `GEMUI_DIR`, `GEMUI_STATIC`, `GEMUI_DEPS`, `STRIP_BIN`, `make rebuild`, `make clean`, `make uninstall`). `build/htab` is stripped by default (pass `STRIP_BIN=0 CXXFLAGS="-O0 -g"` for debug symbols). + +## Running HTab + +```sh +./build/htab # Start with a blank workbook +./build/htab budget.htab # Open a saved workbook +./build/htab data.csv # Import a CSV file +./build/htab --geometry 240x296 # Launch constrained to 240x296 compact mode +``` + +## Quick Controls + +| Task | How to do it | +|---|---| +| Move / select cells | `Arrow keys`, `Shift + Arrows`, or click and drag | +| Go to cell / range | Click the active cell box (e.g. `A1`) or press `Ctrl+G` | +| Edit a cell | Type directly, press `F2`, double-click a cell, or click the formula bar | +| Confirm / cancel edit | `Enter` / `Tab` to confirm (`Shift` reverses), `Esc` to cancel | +| Copy / Cut / Paste | `Ctrl+C`, `Ctrl+X`, `Ctrl+V` (supports formulas and external TSV text), or right-click a cell | +| Undo / Redo | `Ctrl+Z`, `Ctrl+Y`, or toolbar `Undo` / `Redo` (`<` / `>`) | +| Add / remove rows & cols | Toolbar `+Row`, `-Row`, `+Col`, `-Col`, right-click a header or cell, or `F10` Menu | +| Add / switch / rename sheets | Click `+` to add, click tab or `Ctrl+PgUp` / `Ctrl+PgDn` to switch, right-click tab to rename | +| Close a sheet | Click `x` on the tab, middle-click the tab, right-click tab -> `Close Sheet`, or `F10` -> `Delete Sheet` | +| Auto-fill series or formulas | Drag the small square handle at the bottom-right corner of the selection | +| Resize columns or rows | Drag the border line between column letters or row numbers | +| Open full menu | Press `F10` or click `Menu` (`New`, `Open`, `Save`, `Export CSV`, `Format`, `Quit`) | +| Keyboard hints | Press `F1` or `F10` -> `Keyboard Hints (F1)` | +| Quit HTab | `Ctrl+Q`, `F10` -> `Quit`, or window close (prompts to save if modified) | + +## Documentation + +- [USER_GUIDE.md](USER_GUIDE.md) — Complete walkthrough of formulas, dynamic spilling, shortcuts, file formats, DPI scaling, and all 100 functions. +- [design.md](design.md) — Technical architecture and specification. + +## Credits + +Created by Luxferre in 2026, released into the public domain with no warranties. diff --git a/USER_GUIDE.md b/USER_GUIDE.md new file mode 100644 index 0000000..ff9d99f --- /dev/null +++ b/USER_GUIDE.md @@ -0,0 +1,231 @@ +# HTab User Guide + +Welcome to **HTab**. This guide covers everyday spreadsheet tasks, formulas, dynamic spilling, file import/export, display scaling, and every built-in function. + +--- + +## 1. Starting HTab + +Launch HTab from a terminal or launcher: + +```sh +htab [OPTIONS] [FILE] +``` + +Options: +- `-g WxH`, `--geometry WxH`: Open with a specific initial window size, such as `--geometry 960x640` or `--geometry 240x296`. +- `-h`, `--help`: Print command-line help and exit. +- `FILE`: Optional `.htab` (native multi-sheet JSON) or `.csv` file to load at startup. + +### Display Scaling & Compact Mode + +HTab automatically reads your ANODE / X11 display theme and DPI settings (`Xft.dpi`, `theme.scale`, `theme.baseFontSize`, `theme.touchMode`, and live `xrdb` updates via `SIGUSR1` or `XA_RESOURCE_MANAGER`). + +- **Desktop Mode**: Displays the full toolbar (`Menu`, `Open`, `Save`, `CSV`, `Undo`, `Redo`, `Fmt`, `+Row`, `-Row`, `+Col`, `-Col`), formula bar, grid with `A..` columns and numbered rows, selection summary (`N` and `Sum`), and full sheet tab names with `x` close buttons. +- **Compact Mode**: When the logical window size is `<= 320px` wide or `<= 360px` tall (including explicit `--geometry 240x296`), HTab switches automatically to a condensed layout: + - Top bar shows `Menu`, `<` (Undo), `>` (Redo), `Fmt`, and filename. + - Formula bar stays on a single line (`[A1] [=formula]`). + - Sheet tabs abbreviate `Sheet1` to `S1` (showing `x` on the active tab when multiple sheets exist) alongside a compact horizontal scrollbar. + +--- + +## 2. Navigating & Editing the Grid + +### Selecting & Moving +- **Click** a cell to select it; **click and drag** (or hold **`Shift + Arrow keys`**) to select a rectangular range. +- **Arrow keys**: Move one cell; the viewport scrolls automatically when moving near an edge. +- **`Enter` / `Shift+Enter`**: Confirm an edit and move down / up. +- **`Tab` / `Shift+Tab`**: Confirm an edit and move right / left. +- **`PageUp` / `PageDown`**: Jump 10 rows up / down. +- **`Home` / `Ctrl+Home`**: Jump to column `A` on the current row / jump to `A1`. +- **Go To Cell / Range**: Click the active cell box (`A1`) in the formula bar, press **`Ctrl+G`**, or choose **`F10` -> `Go To Cell...`** and enter a cell (`C25`), cross-sheet address (`Sheet2!B4` or `'Sales Data'!A1`), or range (`A1:C10`). +- **Mouse wheel**: Scroll vertically over the grid, or horizontally over the horizontal scrollbar. + +### Entering & Formatting Data +- **Start editing**: Begin typing immediately on any selected cell, press **`F2`**, double-click the cell, or click the formula bar input box. +- **Cancel editing**: Press **`Esc`** to discard changes and restore the previous content. +- **Clear cells**: Select one or more cells and press **`Delete`** or **`BackSpace`**, or right-click and choose **Clear Cell(s)**. +- **Auto-detected types**: + - Leading `=` starts a formula (`=SUM(A1:A5)`). + - Leading `'` forces literal text (for example `'00123` keeps leading zeros). + - Numbers, percentages (`25%` -> `0.25` with percentage format), `TRUE` / `FALSE`, and error literals (`#N/A`, etc.) are typed automatically. +- **Number formatting**: Select cells, click **`Fmt`** (or right-click -> **Format Cell...**, or **`F10`** -> **Format Cell...**) and pick a preset: + - `General` + - `Fixed (0.00)` + - `Integer (#,##0)` + - `Currency ($#,##0.00)` + - `Percentage (0.00%)` + - `Date (yyyy-mm-dd)` + - `Time (hh:mm:ss)` + +### Copy, Cut, Paste & Auto-Fill +- **`Ctrl+C` / `Ctrl+X` / `Ctrl+V`** (or right-click **Copy** / **Cut** / **Paste**): + - Within HTab, pasting a copied formula automatically shifts relative references (`A1`) while keeping `$`-locked anchors (`$A1`, `A$1`, `$A$1`) fixed. + - Copies are also published to the X11 clipboard (`CLIPBOARD` and `PRIMARY`) as tab-separated values (TSV) so you can paste into or out of external applications. +- **Fill handle**: Drag the small highlighted square at the bottom-right corner of the selection box down, up, left, or right: + - Extending 2 or more plain numbers continues the linear trend (for example `10, 20` fills `30, 40, 50`). + - Extending formulas shifts relative cell references along the fill direction. + +### Resizing Columns & Rows +- Move the pointer onto the divider line between column letters (or row numbers) and **drag** to resize. Resizing is saved in `.htab` files and supports Undo/Redo (`Ctrl+Z` / `Ctrl+Y`). + +--- + +## 3. Rows, Columns, and Sheets + +### Inserting & Deleting Rows or Columns +- **Desktop toolbar**: Click **`+Row`**, **`-Row`**, **`+Col`**, or **`-Col`**. +- **Right-click context menu**: + - Right-click any **row number** for `Insert Row Above`, `Insert Row Below`, `Delete Row`, `Format Cell...`. + - Right-click any **column letter** for `Insert Column Left`, `Insert Column Right`, `Delete Column`, `Format Cell...`. + - Right-click any **data cell** for quick `Insert Row Above`, `Delete Row`, `Insert Column Left`, `Delete Column` alongside clipboard/format actions. +- **Menu (`F10`)**: Choose `Insert Row`, `Delete Row`, `Insert Column`, or `Delete Column`. + +When multiple rows or columns are selected, `-Row` / `-Col` (and context menu `Delete Row` / `Delete Column`) removes the entire selected span. All formulas across every sheet are updated automatically: ranges expand or shrink as needed, and formulas pointing directly to a deleted cell become `#REF!`. Press `Ctrl+Z` to undo any structural edit cleanly. + +### Managing Sheets +- **Add a sheet**: Click **`+`** next to the sheet tabs, right-click any sheet tab -> **`Add Sheet`**, or open **`F10`** -> **`Add Sheet`**. +- **Switch sheets**: Click a sheet tab or press **`Ctrl+PageUp`** / **`Ctrl+PageDown`**. +- **Rename a sheet**: Right-click a sheet tab -> **`Rename Sheet...`**, or **`F10`** -> **`Rename Sheet...`**. +- **Close / delete a sheet**: + - Click the **`x`** button on the sheet tab (available whenever there is more than one sheet; in Compact Mode, shown on the active tab). + - Or **middle-click** a sheet tab. + - Or **right-click** a sheet tab -> **`Close Sheet`**. + - Or open **`F10`** -> **`Delete Sheet`**. + - Note: The last remaining sheet in a workbook cannot be deleted. Deleting a sheet can be undone with `Ctrl+Z`. + +--- + +## 4. Writing Formulas + +### Cell & Range Addressing +- **Single cell**: `A1`, `Z10`, `AA1` +- **Anchors**: `$A$1` (locked row & col), `$A1` (locked col), `A$1` (locked row) +- **Range**: `A1:C10` +- **Cross-sheet reference**: `Sheet2!B2` or `'Sales Data'!A1:C10` (use single quotes around sheet names with spaces or punctuation; double any apostrophe inside a quoted sheet name as `''`) + +### Operator Precedence (Highest to Lowest) +1. **Reference operators**: `:` (range), space ` ` (intersection, e.g. `A1:C3 B2:D4`), `,` (union inside parentheses, e.g. `SUM((A1:A2, C1:C2))`) +2. **Unary signs**: `-`, `+` (right-to-left; `=-2^2` evaluates to `4`, whereas `=0-2^2` evaluates to `-4`) +3. **Percent**: `%` postfix (divides by `100`, e.g. `=50%` -> `0.5`) +4. **Exponentiation**: `^` (left-associative; `=2^3^2` evaluates to `64`) +5. **Multiply / Divide**: `*`, `/` +6. **Add / Subtract**: `+`, `-` +7. **Text concatenation**: `&` (e.g. `="Row " & 5` -> `"Row 5"`) +8. **Comparisons**: `=`, `<>`, `<`, `>`, `<=`, `>=` (text comparisons are case-insensitive) + +### Error Values +| Error | Meaning | +|---|---| +| `#DIV/0!` | Division by zero or invalid domain such as `ATAN2(0, 0)` | +| `#VALUE!` | Wrong argument type, mismatched array sizes, or formula syntax error | +| `#NAME?` | Unknown function name or undefined identifier | +| `#N/A` | Value not found (for example `VLOOKUP`, `MATCH`, or empty `FILTER` with no fallback) | +| `#REF!` | Reference points to a deleted row, column, or sheet | +| `#NUM!` | Invalid numeric domain or convergence failure (for example `SQRT(-1)`) | +| `#CYCLE!` | Circular formula dependency detected | +| `#SPILL!` | Dynamic array result blocked by one or more non-empty cells | + +--- + +## 5. Dynamic Array Spilling (`FILTER`) + +Formulas returning a 2D array (such as `FILTER` or array arithmetic like `=A1:A3*2`) automatically **spill** their values into adjacent empty cells below and to the right of the formula cell. + +Example: filter rows in `A2:C5` where column `B` is `"East"` and column `C` is at least `100`: + +```text +=FILTER(A2:C5, (B2:B5="East")*(C2:C5>=100), "None") +``` + +- If every cell in the destination rectangle is empty, HTab fills them automatically (shaded lightly to indicate spilled ownership). Downstream formulas such as `=SUM(E1:E4)` update whenever the spilled output changes. +- If any destination cell already contains data, the formula cell displays `#SPILL!` without overwriting your existing cell. Once you clear the blocking cell, the array spills automatically. + +--- + +## 6. Files, CSV, and Menus + +Press **`F10`** or click **`Menu`** (or use the desktop **`Open`**, **`Save`**, and **`CSV`** toolbar buttons) to access file and workbook commands: +- **New Workbook** (`Ctrl+N`): Replace the current workbook with a fresh single-sheet workbook. +- **Open File...** (`Ctrl+O`): Open GemUI's interactive file browser to load `.htab` / `.json` workbooks or `.csv` files (auto-detected by extension). +- **Save (.htab)...** (`Ctrl+S`): Save directly if already working in a `.htab` / `.json` file, or open GemUI's Save browser to choose a folder and filename (auto-appending `.htab` if omitted). +- **Export CSV (Values)...** (`Ctrl+E`): Export the active sheet to RFC 4180 CSV with evaluated values (including spilled cells) and formatted display strings. +- **Export CSV (Formulas)...**: Export the active sheet to RFC 4180 CSV keeping raw `=...` formulas intact. +- **Go To Cell...** (`Ctrl+G`): Open the address prompt to jump directly to a cell, range, or worksheet target. +- **Keyboard Hints (`F1`)**: Display the built-in scrollable shortcut reference overlay. +- **Quit** (`Ctrl+Q`, `F10` -> `Quit`, or closing the window): Exits immediately when saved, or prompts to **Save**, **Discard**, or **Cancel** if there are unsaved changes. + +### Using the File Open / Save Browser +- **Navigate folders:** Click **`Up`** (`Alt+Up`), **`~`** (`Alt+Home`), or double-click a directory row (such as `..`). You can also use **`Up` / `Down` / `PageUp` / `PageDown`** and press **`Enter`**. +- **Filters & hidden files:** Click **`.*`** (or press `Ctrl+H`) to show or hide dotfiles; click the extension filter badge (e.g., `.htab,.csv,.json`) to switch between matching files and all files (`All (*)`). +- **Path & overwrite safety:** Type a filename (with `~/` expansion and `Ctrl+V` clipboard paste) or click a file in the list. In Save/Export mode, saving over an existing file prompts for **`Overwrite`** / **`Back`** confirmation before modifying the file. + +--- + +## 7. Keyboard Shortcuts Reference + +| Shortcut | Context | Action | +|---|---|---| +| `F1` | Grid / Edit | Show or hide Keyboard Hints | +| `Arrow keys` | Grid | Move active cell | +| `Shift + Arrows` | Grid | Extend cell selection | +| `Enter` / `Shift+Enter` | Grid / Edit | Move down / up (commits active edit) | +| `Tab` / `Shift+Tab` | Grid / Edit | Move right / left (commits active edit) | +| `PageUp` / `PageDown` | Grid | Move 10 rows up / down | +| `Home` / `Ctrl+Home` | Grid | Jump to column `A` / jump to `A1` | +| `Ctrl+G` | Grid / Edit | Go to cell or range (also click active cell box) | +| `F2` | Grid | Edit active cell in place | +| `Esc` | Edit / Modal | Cancel edit or close active menu/dialog | +| `Delete` / `BackSpace` | Grid | Clear selected cells | +| `Ctrl+C` / `Ctrl+X` / `Ctrl+V` | Grid | Copy / Cut / Paste (with relative reference translation) | +| `Ctrl+Z` / `Ctrl+Y` | Grid | Undo / Redo | +| `Ctrl+N` / `Ctrl+O` / `Ctrl+S` | Grid | New / Open / Save `.htab` | +| `Ctrl+E` | Grid | Export active sheet to CSV (Values) | +| `Ctrl+Q` | Grid / Edit | Quit HTab (prompts to save if unsaved) | +| `Ctrl+PageUp` / `Ctrl+PageDown` | Grid | Switch to previous / next sheet | +| `F10` | Grid | Open main Menu | + +--- + +## 8. Complete Function Reference (100 Functions) + +Optional parameters are shown in `[brackets]`; `...` indicates repeatable arguments. + +### 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, ...])` + +Wildcards `*` (any characters), `?` (single character), and `~*`/`~?`/`~~` (escaped literals), along with operators `=`, `<>`, `<`, `<=`, `>`, `>=`, work across `SUMIF`, `SUMIFS`, `COUNTIF`, `COUNTIFS`, and Database criteria. + +### 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) +Dates and times are stored as serial day numbers (integer day + fractional time of day): +`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) +All database functions share the signature `(database, field, criteria)`, where `database` includes header labels in its top row, `field` is either a column header name or a 1-based column index, and `criteria` is a header-matched criteria table where cells on the **same row** are ANDed and **separate rows** are ORed: + +`DAVERAGE`, `DCOUNT`, `DCOUNTA`, `DGET`, `DMAX`, `DMIN`, `DPRODUCT`, `DSTDEV`, `DSTDEVP`, `DSUM`, `DVAR`, `DVARP` + +Example criteria range `E1:F3` (`(Tree="Apple" AND Height>10) OR Tree="Cherry"`): + +```text +E1: Tree | F1: Height +E2: Apple | F2: >10 +E3: Cherry | F3: +``` + +`DSUM(A1:C6, "Yield", E1:F3)` sums the `Yield` column across all matching rows. diff --git a/design.md b/design.md new file mode 100644 index 0000000..4be483d --- /dev/null +++ b/design.md @@ -0,0 +1,167 @@ +# 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. diff --git a/engine/address.cpp b/engine/address.cpp new file mode 100644 index 0000000..eb4ccf8 --- /dev/null +++ b/engine/address.cpp @@ -0,0 +1,385 @@ +#include "engine/address.hpp" +#include "engine/lexer.hpp" +#include "engine/value.hpp" + +#include +#include +#include +#include + +namespace htab { + +std::string col_to_letters(int col) { + if (col < 0) return ""; + std::string rev; + int n = col; + while (n >= 0) { + rev.push_back(static_cast('A' + (n % 26))); + n = n / 26 - 1; + } + return std::string(rev.rbegin(), rev.rend()); +} + +int letters_to_col(std::string_view s) { + if (s.empty() || s.size() > 3) return -1; + int64_t val = 0; + for (char ch : s) { + if (!std::isalpha(static_cast(ch))) return -1; + int d = std::toupper(static_cast(ch)) - 'A' + 1; + val = val * 26 + d; + } + int col = static_cast(val - 1); + if (col < 0 || col >= kMaxCols) return -1; + return col; +} + +static bool needs_sheet_quoting(const std::string& name) { + if (name.empty()) return false; + if (std::isdigit(static_cast(name[0]))) return true; + if (iequals_ascii(name, "TRUE") || iequals_ascii(name, "FALSE")) return true; + for (char ch : name) { + unsigned char uc = static_cast(ch); + if (!(std::isalnum(uc) || ch == '_' || ch == '.')) { + return true; + } + } + // If sheet name looks like a valid cell address (e.g. "A1"), quote it. + if (parse_cell_ref(name).has_value()) { + return true; + } + return false; +} + +std::string format_sheet_prefix(const std::string& sheet_name) { + if (sheet_name.empty()) return ""; + if (!needs_sheet_quoting(sheet_name)) { + return sheet_name + "!"; + } + std::string out = "'"; + for (char ch : sheet_name) { + if (ch == '\'') out += "''"; + else out.push_back(ch); + } + out += "'!"; + return out; +} + +std::string format_cell_ref(const CellRef& r) { + if (r.invalid) { + return "#REF!"; + } + std::string out = format_sheet_prefix(r.sheet_name); + if (r.abs_col) out.push_back('$'); + out += col_to_letters(r.col); + if (r.abs_row) out.push_back('$'); + out += std::to_string(r.row + 1); + return out; +} + +std::string format_range_ref(const RangeRef& r) { + if (r.invalid || r.start.invalid || r.end.invalid) { + return "#REF!"; + } + CellRef s = r.start; + if (s.sheet_name.empty() && !r.sheet_name.empty()) { + s.sheet_name = r.sheet_name; + } + CellRef e = r.end; + e.sheet_name.clear(); + return format_cell_ref(s) + ":" + format_cell_ref(e); +} + +std::optional parse_cell_ref(std::string_view text) { + if (text.empty()) return std::nullopt; + CellRef ref; + size_t pos = 0; + + if (text[0] == '\'') { + pos = 1; + std::string sheet; + bool closed = false; + while (pos < text.size()) { + if (text[pos] == '\'') { + if (pos + 1 < text.size() && text[pos + 1] == '\'') { + sheet.push_back('\''); + pos += 2; + } else { + ++pos; + closed = true; + break; + } + } else { + sheet.push_back(text[pos++]); + } + } + if (!closed || pos >= text.size() || text[pos] != '!' || sheet.empty()) { + return std::nullopt; + } + ++pos; + ref.sheet_name = std::move(sheet); + } else { + size_t bang = text.find('!'); + if (bang != std::string_view::npos) { + if (bang == 0) return std::nullopt; + ref.sheet_name = std::string(text.substr(0, bang)); + pos = bang + 1; + } + } + + if (pos >= text.size()) return std::nullopt; + if (text[pos] == '$') { + ref.abs_col = true; + ++pos; + } + size_t col_start = pos; + while (pos < text.size() && std::isalpha(static_cast(text[pos]))) { + ++pos; + } + if (pos == col_start) return std::nullopt; + int col = letters_to_col(text.substr(col_start, pos - col_start)); + if (col < 0) return std::nullopt; + ref.col = col; + + if (pos < text.size() && text[pos] == '$') { + ref.abs_row = true; + ++pos; + } + size_t row_start = pos; + int64_t row1 = 0; + while (pos < text.size() && std::isdigit(static_cast(text[pos]))) { + row1 = row1 * 10 + (text[pos] - '0'); + if (row1 > kMaxRows) return std::nullopt; + ++pos; + } + if (pos == row_start || pos != text.size() || row1 < 1) { + return std::nullopt; + } + ref.row = static_cast(row1 - 1); + return ref; +} + +namespace { + +struct TextReplacement { + size_t start = 0; + size_t end = 0; + std::string text; +}; + +std::string apply_replacements(const std::string& src, std::vector reps) { + if (reps.empty()) return src; + std::sort(reps.begin(), reps.end(), [](const TextReplacement& a, const TextReplacement& b) { + return a.start < b.start; + }); + std::string out; + out.reserve(src.size() + 32); + size_t cursor = 0; + for (const auto& r : reps) { + if (r.start < cursor) continue; + out.append(src, cursor, r.start - cursor); + out.append(r.text); + cursor = r.end; + } + out.append(src, cursor, src.size() - cursor); + return out; +} + +bool rewrite_interval(int& lo, int& hi, bool is_insert, int index, int count, int max_limit) { + if (count <= 0) return true; + if (is_insert) { + if (index <= lo) { + lo += count; + hi += count; + } else if (index <= hi) { + hi += count; + } + return lo >= 0 && hi < max_limit; + } + // Delete [index, index + count - 1] + int del_start = index; + int del_end = index + count - 1; + if (del_end < lo) { + lo -= count; + hi -= count; + return lo >= 0; + } + if (del_start > hi) { + return true; + } + if (del_start <= lo && del_end >= hi) { + return false; // entire range deleted -> #REF! + } + if (del_start <= lo && del_end < hi) { + lo = del_start; + hi -= count; + return true; + } + if (del_start > lo && del_end >= hi) { + hi = del_start - 1; + return lo <= hi; + } + // Deleted strictly inside (lo, hi) + hi -= count; + return lo <= hi; +} + +bool rewrite_point(int& coord, bool is_insert, int index, int count, int max_limit) { + if (count <= 0) return true; + if (is_insert) { + if (coord >= index) { + coord += count; + if (coord >= max_limit) return false; + } + return true; + } + if (coord >= index && coord < index + count) { + return false; + } + if (coord >= index + count) { + coord -= count; + } + return true; +} + +} // namespace + +std::string translate_formula_refs(const std::string& formula, int drow, int dcol) { + if (formula.empty() || formula[0] != '=' || (drow == 0 && dcol == 0)) { + return formula; + } + auto tokens = Lexer::tokenize(formula, true); + std::vector reps; + for (const auto& tok : tokens) { + if (tok.kind != TokenKind::CellRef) continue; + CellRef r = tok.ref_val; + int nr = r.abs_row ? r.row : (r.row + drow); + int nc = r.abs_col ? r.col : (r.col + dcol); + if (nr < 0 || nr >= kMaxRows || nc < 0 || nc >= kMaxCols) { + r.invalid = true; + } else { + r.row = nr; + r.col = nc; + } + reps.push_back({tok.start, tok.end, format_cell_ref(r)}); + } + return apply_replacements(formula, std::move(reps)); +} + +std::string rewrite_formula_structural(const std::string& formula, + const std::string& current_sheet, + const std::string& target_sheet, + StructuralOp op, + int index, + int count, + const std::string& new_name) { + if (formula.empty() || formula[0] != '=') { + return formula; + } + auto tokens = Lexer::tokenize(formula, true); + std::vector reps; + + for (size_t i = 0; i < tokens.size(); ++i) { + // Handle range pair: CellRef : CellRef + if (tokens[i].kind == TokenKind::CellRef && + i + 2 < tokens.size() && + tokens[i + 1].kind == TokenKind::Colon && + tokens[i + 2].kind == TokenKind::CellRef) { + CellRef lhs = tokens[i].ref_val; + CellRef rhs = tokens[i + 2].ref_val; + std::string eff_lhs = lhs.sheet_name.empty() ? current_sheet : lhs.sheet_name; + std::string eff_rhs = rhs.sheet_name.empty() ? eff_lhs : rhs.sheet_name; + + bool match_lhs = iequals_ascii(eff_lhs, target_sheet); + bool match_rhs = iequals_ascii(eff_rhs, target_sheet); + + if (op == StructuralOp::RenameSheet) { + if (!lhs.sheet_name.empty() && iequals_ascii(lhs.sheet_name, target_sheet)) { + lhs.sheet_name = new_name; + reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(lhs)}); + } + if (!rhs.sheet_name.empty() && iequals_ascii(rhs.sheet_name, target_sheet)) { + rhs.sheet_name = new_name; + reps.push_back({tokens[i + 2].start, tokens[i + 2].end, format_cell_ref(rhs)}); + } + i += 2; + continue; + } + + if (op == StructuralOp::DeleteSheet) { + if ((!lhs.sheet_name.empty() && match_lhs) || (!rhs.sheet_name.empty() && match_rhs)) { + reps.push_back({tokens[i].start, tokens[i + 2].end, "#REF!"}); + } + i += 2; + continue; + } + + if (match_lhs && match_rhs) { + bool is_row = (op == StructuralOp::InsertRow || op == StructuralOp::DeleteRow); + bool is_insert = (op == StructuralOp::InsertRow || op == StructuralOp::InsertCol); + int lo = is_row ? std::min(lhs.row, rhs.row) : std::min(lhs.col, rhs.col); + int hi = is_row ? std::max(lhs.row, rhs.row) : std::max(lhs.col, rhs.col); + bool rev = is_row ? (lhs.row > rhs.row) : (lhs.col > rhs.col); + bool ok = rewrite_interval(lo, hi, is_insert, index, count, is_row ? kMaxRows : kMaxCols); + if (!ok) { + reps.push_back({tokens[i].start, tokens[i + 2].end, "#REF!"}); + } else { + if (is_row) { + lhs.row = rev ? hi : lo; + rhs.row = rev ? lo : hi; + } else { + lhs.col = rev ? hi : lo; + rhs.col = rev ? lo : hi; + } + reps.push_back({tokens[i].start, tokens[i + 2].end, + format_cell_ref(lhs) + ":" + format_cell_ref(rhs)}); + } + i += 2; + continue; + } + // Different sheets in range endpoints: fall through to handle independently + } + + if (tokens[i].kind == TokenKind::CellRef) { + CellRef ref = tokens[i].ref_val; + std::string eff_sheet = ref.sheet_name.empty() ? current_sheet : ref.sheet_name; + if (!iequals_ascii(eff_sheet, target_sheet)) continue; + + if (op == StructuralOp::RenameSheet) { + if (!ref.sheet_name.empty()) { + ref.sheet_name = new_name; + reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(ref)}); + } + continue; + } + if (op == StructuralOp::DeleteSheet) { + if (!ref.sheet_name.empty()) { + reps.push_back({tokens[i].start, tokens[i].end, "#REF!"}); + } + continue; + } + bool is_row = (op == StructuralOp::InsertRow || op == StructuralOp::DeleteRow); + bool is_insert = (op == StructuralOp::InsertRow || op == StructuralOp::InsertCol); + int coord = is_row ? ref.row : ref.col; + if (!rewrite_point(coord, is_insert, index, count, is_row ? kMaxRows : kMaxCols)) { + reps.push_back({tokens[i].start, tokens[i].end, "#REF!"}); + } else { + if (is_row) ref.row = coord; + else ref.col = coord; + reps.push_back({tokens[i].start, tokens[i].end, format_cell_ref(ref)}); + } + } else if (tokens[i].kind == TokenKind::Error && tokens[i].err_val == ErrorCode::Ref && + tokens[i].ref_val.invalid && !tokens[i].ref_val.sheet_name.empty() && + iequals_ascii(tokens[i].ref_val.sheet_name, target_sheet)) { + if (op == StructuralOp::RenameSheet) { + reps.push_back({tokens[i].start, tokens[i].end, + format_sheet_prefix(new_name) + "#REF!"}); + } else if (op == StructuralOp::DeleteSheet) { + reps.push_back({tokens[i].start, tokens[i].end, "#REF!"}); + } + } + } + + return apply_replacements(formula, std::move(reps)); +} + +} // namespace htab diff --git a/engine/address.hpp b/engine/address.hpp new file mode 100644 index 0000000..7149239 --- /dev/null +++ b/engine/address.hpp @@ -0,0 +1,103 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace htab { + +inline constexpr int kMaxRows = 1048576; +inline constexpr int kMaxCols = 16384; // A..XFD (0..16383) + +struct CellKey { + int row = 0; + int col = 0; + bool operator==(const CellKey&) const = default; +}; + +struct CellKeyHash { + size_t operator()(const CellKey& k) const noexcept { + size_t h1 = std::hash{}(k.row); + size_t h2 = std::hash{}(k.col); + return h1 ^ (h2 + 0x9e3779b97f4a7c15ULL + (h1 << 6) + (h1 >> 2)); + } +}; + +struct GlobalAddr { + int sheet = 0; + int row = 0; + int col = 0; + bool operator==(const GlobalAddr&) const = default; +}; + +struct GlobalAddrHash { + size_t operator()(const GlobalAddr& a) const noexcept { + size_t h = std::hash{}(a.sheet); + h ^= std::hash{}(a.row) + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2); + h ^= std::hash{}(a.col) + 0x9e3779b97f4a7c15ULL + (h << 6) + (h >> 2); + return h; + } +}; + +struct CellRef { + std::string sheet_name; + int row = 0; + int col = 0; + bool abs_row = false; + bool abs_col = false; + bool invalid = false; + + bool operator==(const CellRef&) const = default; +}; + +struct RangeRef { + std::string sheet_name; + CellRef start; + CellRef end; + bool invalid = false; +}; + +struct CellRange { + int sheet = 0; + int r1 = 0; + int c1 = 0; + int r2 = 0; + int c2 = 0; + + bool operator==(const CellRange&) const = default; + + int row_count() const { return r2 - r1 + 1; } + int col_count() const { return c2 - c1 + 1; } + bool contains(int s, int r, int c) const { + return s == sheet && r >= r1 && r <= r2 && c >= c1 && c <= c2; + } +}; + +std::string col_to_letters(int col); +int letters_to_col(std::string_view s); +std::string format_sheet_prefix(const std::string& sheet_name); +std::string format_cell_ref(const CellRef& r); +std::string format_range_ref(const RangeRef& r); +std::optional parse_cell_ref(std::string_view text); + +enum class StructuralOp { + InsertRow, + DeleteRow, + InsertCol, + DeleteCol, + RenameSheet, + DeleteSheet, +}; + +std::string translate_formula_refs(const std::string& formula, int drow, int dcol); +std::string rewrite_formula_structural(const std::string& formula, + const std::string& current_sheet, + const std::string& target_sheet, + StructuralOp op, + int index, + int count, + const std::string& new_name = ""); + +} // namespace htab diff --git a/engine/dag.cpp b/engine/dag.cpp new file mode 100644 index 0000000..62943fa --- /dev/null +++ b/engine/dag.cpp @@ -0,0 +1,626 @@ +#include "engine/dag.hpp" +#include "engine/evaluator.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include +#include + +namespace htab { + +namespace { + +constexpr int64_t kSmallRangeExpandLimit = 4096; + +void extract_deps_walk(const Expr* expr, + int current_sheet, + const Workbook& wb, + std::vector& out_cells, + std::vector& out_ranges) { + if (!expr) return; + switch (expr->kind) { + case Expr::Kind::Literal: + case Expr::Kind::UnknownName: + return; + case Expr::Kind::CellRef: { + const auto& ref = static_cast(expr)->ref; + if (ref.invalid) return; + int s = ref.sheet_name.empty() ? current_sheet : wb.find_sheet(ref.sheet_name); + if (s >= 0) { + out_cells.push_back(GlobalAddr{s, ref.row, ref.col}); + } + return; + } + case Expr::Kind::Range: { + const auto* rng = static_cast(expr); + if (rng->lhs && rng->rhs && + rng->lhs->kind == Expr::Kind::CellRef && + rng->rhs->kind == Expr::Kind::CellRef) { + const auto& lref = static_cast(rng->lhs.get())->ref; + const auto& rref = static_cast(rng->rhs.get())->ref; + if (!lref.invalid && !rref.invalid) { + int ls = lref.sheet_name.empty() ? current_sheet : wb.find_sheet(lref.sheet_name); + int rs = rref.sheet_name.empty() ? ls : wb.find_sheet(rref.sheet_name); + if (ls >= 0 && ls == rs) { + out_ranges.push_back(CellRange{ + ls, + std::min(lref.row, rref.row), + std::min(lref.col, rref.col), + std::max(lref.row, rref.row), + std::max(lref.col, rref.col), + }); + return; + } + } + } + extract_deps_walk(rng->lhs.get(), current_sheet, wb, out_cells, out_ranges); + extract_deps_walk(rng->rhs.get(), current_sheet, wb, out_cells, out_ranges); + return; + } + case Expr::Kind::Unary: + extract_deps_walk(static_cast(expr)->operand.get(), + current_sheet, wb, out_cells, out_ranges); + return; + case Expr::Kind::Percent: + extract_deps_walk(static_cast(expr)->operand.get(), + current_sheet, wb, out_cells, out_ranges); + return; + case Expr::Kind::Binary: { + const auto* b = static_cast(expr); + extract_deps_walk(b->lhs.get(), current_sheet, wb, out_cells, out_ranges); + extract_deps_walk(b->rhs.get(), current_sheet, wb, out_cells, out_ranges); + return; + } + case Expr::Kind::Call: { + const auto* c = static_cast(expr); + for (const auto& arg : c->args) { + extract_deps_walk(arg.get(), current_sheet, wb, out_cells, out_ranges); + } + return; + } + } +} + +bool ranges_overlap(const CellRange& a, const CellRange& b) { + if (a.sheet != b.sheet) return false; + return a.r1 <= b.r2 && b.r1 <= a.r2 && a.c1 <= b.c2 && b.c1 <= a.c2; +} + +} // namespace + +void DependencyGraph::clear() { + cell_precedents_.clear(); + range_precedents_.clear(); + dependents_.clear(); + large_range_dependents_.clear(); + spill_ranges_.clear(); + spill_owner_.clear(); + spill_blocked_by_.clear(); + origin_blockers_.clear(); +} + +void DependencyGraph::remove_cell_deps_only(const GlobalAddr& cell) { + auto cp_it = cell_precedents_.find(cell); + if (cp_it != cell_precedents_.end()) { + for (const auto& p : cp_it->second) { + auto dep_it = dependents_.find(p); + if (dep_it != dependents_.end()) { + dep_it->second.erase(cell); + if (dep_it->second.empty()) dependents_.erase(dep_it); + } + } + cell_precedents_.erase(cp_it); + } + + auto rp_it = range_precedents_.find(cell); + if (rp_it != range_precedents_.end()) { + for (const auto& rng : rp_it->second) { + auto l_it = large_range_dependents_.find(rng.sheet); + if (l_it != large_range_dependents_.end()) { + auto& vec = l_it->second; + vec.erase(std::remove_if(vec.begin(), vec.end(), + [&](const LargeRangeEntry& e) { return e.dependent == cell; }), + vec.end()); + } + } + range_precedents_.erase(rp_it); + } +} + +void DependencyGraph::update_cell_deps(const Workbook& wb, const GlobalAddr& cell, const Expr* ast) { + remove_cell_deps_only(cell); + if (!ast) return; + + std::vector raw_cells; + std::vector raw_ranges; + extract_deps_walk(ast, cell.sheet, wb, raw_cells, raw_ranges); + + std::unordered_set unique_cells; + for (const auto& p : raw_cells) { + unique_cells.insert(p); + } + + std::vector large_ranges; + for (const auto& rng : raw_ranges) { + int64_t cnt = static_cast(rng.row_count()) * rng.col_count(); + if (cnt <= kSmallRangeExpandLimit) { + for (int r = rng.r1; r <= rng.r2; ++r) { + for (int c = rng.c1; c <= rng.c2; ++c) { + unique_cells.insert(GlobalAddr{rng.sheet, r, c}); + } + } + } else { + large_ranges.push_back(rng); + } + } + + if (!unique_cells.empty()) { + auto& cp = cell_precedents_[cell]; + cp.reserve(unique_cells.size()); + for (const auto& p : unique_cells) { + cp.push_back(p); + dependents_[p].insert(cell); + } + } + if (!large_ranges.empty()) { + for (const auto& rng : large_ranges) { + large_range_dependents_[rng.sheet].push_back(LargeRangeEntry{cell, rng}); + } + range_precedents_[cell] = std::move(large_ranges); + } +} + +void DependencyGraph::remove_cell(const GlobalAddr& cell) { + remove_cell_deps_only(cell); + std::vector unused; + clear_spill_for_origin(cell, unused); + clear_blocked_entries_for_origin(cell); +} + +void DependencyGraph::clear_blocked_entries_for_origin(const GlobalAddr& origin) { + auto it = origin_blockers_.find(origin); + if (it == origin_blockers_.end()) return; + for (const auto& b : it->second) { + auto bit = spill_blocked_by_.find(b); + if (bit != spill_blocked_by_.end()) { + bit->second.erase(origin); + if (bit->second.empty()) spill_blocked_by_.erase(bit); + } + } + origin_blockers_.erase(it); +} + +void DependencyGraph::clear_spill_for_origin(const GlobalAddr& origin, + std::vector& affected_cells) { + auto it = spill_ranges_.find(origin); + if (it == spill_ranges_.end()) return; + CellRange sr = it->second; + spill_ranges_.erase(it); + for (int r = sr.r1; r <= sr.r2; ++r) { + for (int c = sr.c1; c <= sr.c2; ++c) { + if (r == origin.row && c == origin.col) continue; + GlobalAddr t{sr.sheet, r, c}; + auto oit = spill_owner_.find(t); + if (oit != spill_owner_.end() && oit->second == origin) { + spill_owner_.erase(oit); + affected_cells.push_back(t); + } + } + } +} + +void DependencyGraph::collect_dependents_of(const GlobalAddr& cell, + std::vector& out) const { + auto dit = dependents_.find(cell); + if (dit != dependents_.end()) { + for (const auto& d : dit->second) out.push_back(d); + } + auto lit = large_range_dependents_.find(cell.sheet); + if (lit != large_range_dependents_.end()) { + for (const auto& entry : lit->second) { + if (entry.range.contains(cell.sheet, cell.row, cell.col)) { + out.push_back(entry.dependent); + } + } + } +} + +bool DependencyGraph::apply_spill_for_cell(Workbook& wb, + const GlobalAddr& origin, + const Value& val, + std::vector& followup_seeds) { + clear_blocked_entries_for_origin(origin); + + if (!val.is_array()) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + for (const auto& c : cleared) { + collect_dependents_of(c, followup_seeds); + } + return false; + } + + const auto& arr = val.as_array(); + if (!arr || arr->rows <= 0 || arr->cols <= 0) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + for (const auto& c : cleared) { + collect_dependents_of(c, followup_seeds); + } + return false; + } + + if (arr->rows == 1 && arr->cols == 1) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + for (const auto& c : cleared) { + collect_dependents_of(c, followup_seeds); + } + return false; + } + + int r2 = origin.row + arr->rows - 1; + int c2 = origin.col + arr->cols - 1; + if (r2 >= kMaxRows || c2 >= kMaxCols) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + for (const auto& c : cleared) { + collect_dependents_of(c, followup_seeds); + } + Cell* cell = wb.sheet_mut(origin.sheet).cells.count(CellKey{origin.row, origin.col}) + ? &wb.sheet_mut(origin.sheet).cells[CellKey{origin.row, origin.col}] + : nullptr; + if (cell) cell->value = Value::make_error(ErrorCode::Spill); + return true; + } + + std::vector blockers; + for (int r = origin.row; r <= r2; ++r) { + for (int c = origin.col; c <= c2; ++c) { + if (r == origin.row && c == origin.col) continue; + const Cell* target_cell = wb.get_cell(origin.sheet, r, c); + if (target_cell && !target_cell->raw_input.empty()) { + blockers.push_back(GlobalAddr{origin.sheet, r, c}); + continue; + } + GlobalAddr t{origin.sheet, r, c}; + auto oit = spill_owner_.find(t); + if (oit != spill_owner_.end() && oit->second != origin) { + blockers.push_back(t); + } + } + } + + if (!blockers.empty()) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + for (const auto& c : cleared) { + collect_dependents_of(c, followup_seeds); + } + auto& ob = origin_blockers_[origin]; + ob = std::move(blockers); + for (const auto& b : ob) { + spill_blocked_by_[b].insert(origin); + } + auto& cells_map = wb.sheet_mut(origin.sheet).cells; + auto cit = cells_map.find(CellKey{origin.row, origin.col}); + if (cit != cells_map.end()) { + cit->second.value = Value::make_error(ErrorCode::Spill); + } + return true; + } + + // Can spill cleanly: diff against previous spill range + CellRange new_rect{origin.sheet, origin.row, origin.col, r2, c2}; + bool range_changed = true; + auto prev_it = spill_ranges_.find(origin); + if (prev_it != spill_ranges_.end() && prev_it->second == new_rect) { + range_changed = false; + } + + if (range_changed) { + std::vector cleared; + clear_spill_for_origin(origin, cleared); + spill_ranges_[origin] = new_rect; + for (int r = new_rect.r1; r <= new_rect.r2; ++r) { + for (int c = new_rect.c1; c <= new_rect.c2; ++c) { + if (r == origin.row && c == origin.col) continue; + GlobalAddr t{origin.sheet, r, c}; + spill_owner_[t] = origin; + collect_dependents_of(t, followup_seeds); + } + } + for (const auto& c : cleared) { + if (!new_rect.contains(c.sheet, c.row, c.col)) { + collect_dependents_of(c, followup_seeds); + } + } + } + return false; +} + +void DependencyGraph::rebuild(Workbook& wb) { + clear(); + std::vector all_formulas; + for (int si = 0; si < wb.sheet_count(); ++si) { + const Sheet& s = wb.sheet(si); + for (const auto& [key, cell] : s.cells) { + if (cell.ast) { + GlobalAddr addr{si, key.row, key.col}; + update_cell_deps(wb, addr, cell.ast.get()); + all_formulas.push_back(addr); + } + } + } + if (!all_formulas.empty()) { + recalculate_from(wb, std::move(all_formulas)); + } +} + +void DependencyGraph::recalculate_from(Workbook& wb, std::vector seeds) { + for (int pass = 0; pass < 32 && !seeds.empty(); ++pass) { + std::unordered_set expanded_seeds; + for (const auto& s : seeds) { + expanded_seeds.insert(s); + auto oit = spill_owner_.find(s); + if (oit != spill_owner_.end()) { + expanded_seeds.insert(oit->second); + } + auto bit = spill_blocked_by_.find(s); + if (bit != spill_blocked_by_.end()) { + for (const auto& blocked_origin : bit->second) { + expanded_seeds.insert(blocked_origin); + } + } + } + + // BFS forward to gather all dirty cells + std::unordered_set dirty; + std::queue bfs; + for (const auto& s : expanded_seeds) { + if (dirty.insert(s).second) { + bfs.push(s); + } + } + + while (!bfs.empty()) { + GlobalAddr u = bfs.front(); + bfs.pop(); + + std::vector next_deps; + collect_dependents_of(u, next_deps); + auto srit = spill_ranges_.find(u); + if (srit != spill_ranges_.end()) { + const CellRange& sr = srit->second; + for (int r = sr.r1; r <= sr.r2; ++r) { + for (int c = sr.c1; c <= sr.c2; ++c) { + if (r == u.row && c == u.col) continue; + collect_dependents_of(GlobalAddr{sr.sheet, r, c}, next_deps); + } + } + } + for (const auto& d : next_deps) { + if (dirty.insert(d).second) { + bfs.push(d); + } + } + } + + // Build subgraph edges among dirty nodes + std::vector nodes(dirty.begin(), dirty.end()); + std::unordered_map id_of; + id_of.reserve(nodes.size() * 2 + 1); + for (size_t i = 0; i < nodes.size(); ++i) { + id_of[nodes[i]] = i; + } + + std::vector> adj(nodes.size()); + std::vector in_degree(nodes.size(), 0); + std::vector self_loop(nodes.size(), false); + + for (size_t vi = 0; vi < nodes.size(); ++vi) { + const GlobalAddr& v = nodes[vi]; + std::unordered_set preds; + + auto cp_it = cell_precedents_.find(v); + if (cp_it != cell_precedents_.end()) { + for (const auto& p : cp_it->second) { + auto it = id_of.find(p); + if (it != id_of.end()) preds.insert(it->second); + auto oit = spill_owner_.find(p); + if (oit != spill_owner_.end()) { + auto o_id = id_of.find(oit->second); + if (o_id != id_of.end()) preds.insert(o_id->second); + } + } + } + + auto rp_it = range_precedents_.find(v); + if (rp_it != range_precedents_.end()) { + for (const auto& rng : rp_it->second) { + for (size_t ui = 0; ui < nodes.size(); ++ui) { + const GlobalAddr& u = nodes[ui]; + if (rng.contains(u.sheet, u.row, u.col)) { + preds.insert(ui); + } else { + auto srit = spill_ranges_.find(u); + if (srit != spill_ranges_.end() && ranges_overlap(rng, srit->second)) { + preds.insert(ui); + } + } + } + } + } + + for (size_t ui : preds) { + if (ui == vi) { + self_loop[vi] = true; + } else { + adj[ui].push_back(vi); + } + in_degree[vi]++; + } + } + + std::vector followup_seeds; + auto eval_node = [&](size_t idx, bool force_cycle) { + const GlobalAddr& addr = nodes[idx]; + if (addr.sheet < 0 || addr.sheet >= wb.sheet_count()) return; + auto& cells_map = wb.sheet_mut(addr.sheet).cells; + auto cit = cells_map.find(CellKey{addr.row, addr.col}); + if (cit == cells_map.end() || !cit->second.ast) { + // Non-formula cell (or cleared): ensure any old spill is cleared. + std::vector cleared; + clear_spill_for_origin(addr, cleared); + clear_blocked_entries_for_origin(addr); + for (const auto& c : cleared) collect_dependents_of(c, followup_seeds); + return; + } + + if (force_cycle) { + std::vector cleared; + clear_spill_for_origin(addr, cleared); + clear_blocked_entries_for_origin(addr); + for (const auto& c : cleared) collect_dependents_of(c, followup_seeds); + cit->second.value = Value::make_error(ErrorCode::Cycle); + return; + } + + EvalContext ctx{&wb, addr.sheet, addr.row, addr.col}; + EvalResult res = evaluate_ast(cit->second.ast.get(), ctx); + Value val = deref_to_value(res, wb); + cit->second.value = val; + apply_spill_for_cell(wb, addr, val, followup_seeds); + }; + + // Pass 1: Kahn's topological sort + std::vector visited(nodes.size(), false); + std::queue q; + for (size_t i = 0; i < nodes.size(); ++i) { + if (in_degree[i] == 0) { + q.push(i); + } + } + while (!q.empty()) { + size_t u = q.front(); + q.pop(); + visited[u] = true; + eval_node(u, false); + for (size_t v : adj[u]) { + if (--in_degree[v] == 0) { + q.push(v); + } + } + } + + // Pass 2: Tarjan's SCC for remaining cyclic / cycle-downstream nodes + std::vector rem_nodes; + for (size_t i = 0; i < nodes.size(); ++i) { + if (!visited[i]) rem_nodes.push_back(i); + } + if (!rem_nodes.empty()) { + int tarjan_timer = 0; + std::vector disc(nodes.size(), -1); + std::vector low(nodes.size(), -1); + std::vector on_stack(nodes.size(), false); + std::stack st; + std::vector> sccs; + + auto strongconnect = [&](auto& self_fn, size_t u) -> void { + disc[u] = low[u] = tarjan_timer++; + st.push(u); + on_stack[u] = true; + for (size_t v : adj[u]) { + if (visited[v]) continue; + if (disc[v] == -1) { + self_fn(self_fn, v); + low[u] = std::min(low[u], low[v]); + } else if (on_stack[v]) { + low[u] = std::min(low[u], disc[v]); + } + } + if (low[u] == disc[u]) { + std::vector comp; + while (true) { + size_t w = st.top(); + st.pop(); + on_stack[w] = false; + comp.push_back(w); + if (w == u) break; + } + sccs.push_back(std::move(comp)); + } + }; + + for (size_t idx : rem_nodes) { + if (disc[idx] == -1) { + strongconnect(strongconnect, idx); + } + } + + // Tarjan yields SCCs in reverse topological order; iterate in reverse. + for (auto it = sccs.rbegin(); it != sccs.rend(); ++it) { + const auto& comp = *it; + bool is_cycle = (comp.size() > 1) || (comp.size() == 1 && self_loop[comp[0]]); + for (size_t idx : comp) { + eval_node(idx, is_cycle); + } + } + } + + if (pass == 31 && !followup_seeds.empty()) { + for (const auto& f : followup_seeds) { + if (f.sheet >= 0 && f.sheet < wb.sheet_count()) { + auto& cmap = wb.sheet_mut(f.sheet).cells; + auto cit = cmap.find(CellKey{f.row, f.col}); + if (cit != cmap.end() && cit->second.ast) { + cit->second.value = Value::make_error(ErrorCode::Cycle); + } + } + } + break; + } + + seeds = std::move(followup_seeds); + } +} + +bool DependencyGraph::is_spilled_cell(int sheet, int row, int col) const { + return spill_owner_.find(GlobalAddr{sheet, row, col}) != spill_owner_.end(); +} + +std::optional DependencyGraph::get_spill_range(int sheet, int row, int col) const { + GlobalAddr addr{sheet, row, col}; + auto it = spill_ranges_.find(addr); + if (it != spill_ranges_.end()) return it->second; + auto oit = spill_owner_.find(addr); + if (oit != spill_owner_.end()) { + auto it2 = spill_ranges_.find(oit->second); + if (it2 != spill_ranges_.end()) return it2->second; + } + return std::nullopt; +} + +std::optional DependencyGraph::get_spill_origin(int sheet, int row, int col) const { + auto oit = spill_owner_.find(GlobalAddr{sheet, row, col}); + if (oit != spill_owner_.end()) return oit->second; + return std::nullopt; +} + +Value DependencyGraph::get_spill_value(const Workbook& wb, int sheet, int row, int col) const { + auto oit = spill_owner_.find(GlobalAddr{sheet, row, col}); + if (oit == spill_owner_.end()) return Value::make_empty(); + const GlobalAddr& origin = oit->second; + const Cell* oc = wb.get_cell(origin.sheet, origin.row, origin.col); + if (!oc || !oc->value.is_array()) return Value::make_empty(); + const auto& arr = oc->value.as_array(); + int dr = row - origin.row; + int dc = col - origin.col; + if (!arr || dr < 0 || dc < 0 || dr >= arr->rows || dc >= arr->cols) { + return Value::make_empty(); + } + return arr->at(dr, dc); +} + +} // namespace htab diff --git a/engine/dag.hpp b/engine/dag.hpp new file mode 100644 index 0000000..e6b1127 --- /dev/null +++ b/engine/dag.hpp @@ -0,0 +1,64 @@ +#pragma once + +#include "engine/address.hpp" +#include "engine/parser.hpp" +#include "engine/value.hpp" + +#include +#include +#include +#include + +namespace htab { + +class Workbook; + +class DependencyGraph { + public: + void clear(); + void rebuild(Workbook& wb); + void update_cell_deps(const Workbook& wb, const GlobalAddr& cell, const Expr* ast); + void remove_cell(const GlobalAddr& cell); + + void recalculate_from(Workbook& wb, std::vector seeds); + + bool is_spilled_cell(int sheet, int row, int col) const; + std::optional get_spill_range(int sheet, int row, int col) const; + std::optional get_spill_origin(int sheet, int row, int col) const; + Value get_spill_value(const Workbook& wb, int sheet, int row, int col) const; + const std::unordered_map& spill_ranges() const { + return spill_ranges_; + } + + private: + struct LargeRangeEntry { + GlobalAddr dependent; + CellRange range; + }; + + void remove_cell_deps_only(const GlobalAddr& cell); + void clear_spill_for_origin(const GlobalAddr& origin, + std::vector& affected_cells); + void clear_blocked_entries_for_origin(const GlobalAddr& origin); + bool apply_spill_for_cell(Workbook& wb, + const GlobalAddr& origin, + const Value& val, + std::vector& followup_seeds); + void collect_dependents_of(const GlobalAddr& cell, + std::vector& out) const; + + std::unordered_map, GlobalAddrHash> cell_precedents_; + std::unordered_map, GlobalAddrHash> range_precedents_; + std::unordered_map, GlobalAddrHash> + dependents_; + std::unordered_map> large_range_dependents_; + + // Spill state + std::unordered_map spill_ranges_; + std::unordered_map spill_owner_; + std::unordered_map, GlobalAddrHash> + spill_blocked_by_; + std::unordered_map, GlobalAddrHash> origin_blockers_; +}; + +} // namespace htab diff --git a/engine/evaluator.cpp b/engine/evaluator.cpp new file mode 100644 index 0000000..ce8a5ea --- /dev/null +++ b/engine/evaluator.cpp @@ -0,0 +1,312 @@ +#include "engine/evaluator.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include + +namespace htab { + +namespace { + +constexpr int kMaxArrayCells = 1000000; + +Value eval_scalar_binary(BinOp op, const Value& a, const Value& b) { + if (a.is_error()) return a; + if (b.is_error()) return b; + + switch (op) { + case BinOp::Add: + case BinOp::Sub: + case BinOp::Mul: + case BinOp::Div: + case BinOp::Pow: { + auto na = to_number(a); + if (std::holds_alternative(na)) return Value::make_error(std::get(na)); + auto nb = to_number(b); + if (std::holds_alternative(nb)) return Value::make_error(std::get(nb)); + double da = std::get(na); + double db = std::get(nb); + switch (op) { + case BinOp::Add: return Value::make_checked_number(da + db); + case BinOp::Sub: return Value::make_checked_number(da - db); + case BinOp::Mul: return Value::make_checked_number(da * db); + case BinOp::Div: + if (db == 0.0) return Value::make_error(ErrorCode::Div0); + return Value::make_checked_number(da / db); + case BinOp::Pow: + if (da == 0.0 && db < 0.0) return Value::make_error(ErrorCode::Div0); + return Value::make_checked_number(std::pow(da, db)); + default: break; + } + break; + } + case BinOp::Concat: { + auto sa = to_string(a); + if (std::holds_alternative(sa)) return Value::make_error(std::get(sa)); + auto sb = to_string(b); + if (std::holds_alternative(sb)) return Value::make_error(std::get(sb)); + return Value::make_string(std::get(sa) + std::get(sb)); + } + case BinOp::Eq: + case BinOp::Neq: + case BinOp::Lt: + case BinOp::Gt: + case BinOp::Le: + case BinOp::Ge: { + auto cmp = compare_values(a, b); + if (std::holds_alternative(cmp)) return Value::make_error(std::get(cmp)); + int c = std::get(cmp); + switch (op) { + case BinOp::Eq: return Value::make_bool(c == 0); + case BinOp::Neq: return Value::make_bool(c != 0); + case BinOp::Lt: return Value::make_bool(c < 0); + case BinOp::Gt: return Value::make_bool(c > 0); + case BinOp::Le: return Value::make_bool(c <= 0); + case BinOp::Ge: return Value::make_bool(c >= 0); + default: break; + } + break; + } + default: + break; + } + return Value::make_error(ErrorCode::Value); +} + +Value eval_scalar_unary(char op, const Value& v) { + if (v.is_error()) return v; + auto n = to_number(v); + if (std::holds_alternative(n)) return Value::make_error(std::get(n)); + double d = std::get(n); + return Value::make_checked_number(op == '-' ? -d : d); +} + +Value eval_scalar_percent(const Value& v) { + if (v.is_error()) return v; + auto n = to_number(v); + if (std::holds_alternative(n)) return Value::make_error(std::get(n)); + return Value::make_checked_number(std::get(n) / 100.0); +} + +Value broadcast_binary(BinOp op, const Value& lhs, const Value& rhs) { + if (!lhs.is_array() && !rhs.is_array()) { + return eval_scalar_binary(op, lhs, rhs); + } + int lr = lhs.is_array() ? lhs.as_array()->rows : 1; + int lc = lhs.is_array() ? lhs.as_array()->cols : 1; + int rr = rhs.is_array() ? rhs.as_array()->rows : 1; + int rc = rhs.is_array() ? rhs.as_array()->cols : 1; + + if (lr <= 0 || lc <= 0 || rr <= 0 || rc <= 0) { + return Value::make_error(ErrorCode::Value); + } + if (lr != rr && lr != 1 && rr != 1) return Value::make_error(ErrorCode::Value); + if (lc != rc && lc != 1 && rc != 1) return Value::make_error(ErrorCode::Value); + + int out_r = std::max(lr, rr); + int out_c = std::max(lc, rc); + if (static_cast(out_r) * out_c > kMaxArrayCells) { + return Value::make_error(ErrorCode::Num); + } + auto out = std::make_shared(out_r, out_c); + for (int r = 0; r < out_r; ++r) { + for (int c = 0; c < out_c; ++c) { + const Value& va = lhs.is_array() ? lhs.as_array()->at(lr == 1 ? 0 : r, lc == 1 ? 0 : c) : lhs; + const Value& vb = rhs.is_array() ? rhs.as_array()->at(rr == 1 ? 0 : r, rc == 1 ? 0 : c) : rhs; + out->at(r, c) = eval_scalar_binary(op, va, vb); + } + } + if (out_r == 1 && out_c == 1) { + return out->at(0, 0); + } + return Value::make_array(std::move(out)); +} + +template +Value map_unary(const Value& v, Fn&& fn) { + if (!v.is_array()) return fn(v); + const auto& arr = v.as_array(); + if (!arr || arr->rows <= 0 || arr->cols <= 0) { + return Value::make_error(ErrorCode::Value); + } + auto out = std::make_shared(arr->rows, arr->cols); + for (int r = 0; r < arr->rows; ++r) { + for (int c = 0; c < arr->cols; ++c) { + out->at(r, c) = fn(arr->at(r, c)); + } + } + if (arr->rows == 1 && arr->cols == 1) { + return out->at(0, 0); + } + return Value::make_array(std::move(out)); +} + +int resolve_sheet(const std::string& sheet_name, const EvalContext& ctx) { + if (sheet_name.empty()) return ctx.current_sheet; + return ctx.wb->find_sheet(sheet_name); +} + +} // namespace + +Value deref_to_value(const EvalResult& res, const Workbook& wb) { + if (!res.is_ref) { + return res.value; + } + if (res.ranges.size() != 1) { + return Value::make_error(ErrorCode::Value); + } + const CellRange& rng = res.ranges[0]; + int rc = rng.row_count(); + int cc = rng.col_count(); + if (rc == 1 && cc == 1) { + return wb.get_scalar_value(rng.sheet, rng.r1, rng.c1); + } + if (static_cast(rc) * cc > kMaxArrayCells) { + return Value::make_error(ErrorCode::Num); + } + auto arr = std::make_shared(rc, cc); + for (int r = 0; r < rc; ++r) { + for (int c = 0; c < cc; ++c) { + arr->at(r, c) = wb.get_scalar_value(rng.sheet, rng.r1 + r, rng.c1 + c); + } + } + return Value::make_array(std::move(arr)); +} + +EvalResult evaluate_ast(const Expr* expr, const EvalContext& ctx) { + if (!expr || !ctx.wb) { + return EvalResult::from_value(Value::make_error(ErrorCode::Value)); + } + + switch (expr->kind) { + case Expr::Kind::Literal: { + return EvalResult::from_value(static_cast(expr)->value); + } + case Expr::Kind::UnknownName: { + return EvalResult::from_value(Value::make_error(ErrorCode::Name)); + } + case Expr::Kind::CellRef: { + const auto& ref = static_cast(expr)->ref; + if (ref.invalid) { + return EvalResult::from_value(Value::make_error(ErrorCode::Ref)); + } + int s = resolve_sheet(ref.sheet_name, ctx); + if (s < 0) { + return EvalResult::from_value(Value::make_error(ErrorCode::Ref)); + } + return EvalResult::from_range(CellRange{s, ref.row, ref.col, ref.row, ref.col}); + } + case Expr::Kind::Range: { + const auto* rng = static_cast(expr); + EvalResult lr = evaluate_ast(rng->lhs.get(), ctx); + if (!lr.is_ref) { + return EvalResult::from_value( + lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value)); + } + // Inherit sheet name when writing Sheet2!A1:B5 where RHS omitted the sheet prefix. + EvalContext rhs_ctx = ctx; + if (rng->lhs->kind == Expr::Kind::CellRef && rng->rhs->kind == Expr::Kind::CellRef) { + const auto& lref = static_cast(rng->lhs.get())->ref; + const auto& rref = static_cast(rng->rhs.get())->ref; + if (!lref.sheet_name.empty() && rref.sheet_name.empty() && !lr.ranges.empty()) { + rhs_ctx.current_sheet = lr.ranges[0].sheet; + } + } + EvalResult rr = evaluate_ast(rng->rhs.get(), rhs_ctx); + if (!rr.is_ref) { + return EvalResult::from_value( + rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value)); + } + if (lr.ranges.size() != 1 || rr.ranges.size() != 1) { + return EvalResult::from_value(Value::make_error(ErrorCode::Value)); + } + const CellRange& a = lr.ranges[0]; + const CellRange& b = rr.ranges[0]; + if (a.sheet != b.sheet) { + return EvalResult::from_value(Value::make_error(ErrorCode::Value)); + } + return EvalResult::from_range(CellRange{ + a.sheet, + std::min(a.r1, b.r1), + std::min(a.c1, b.c1), + std::max(a.r2, b.r2), + std::max(a.c2, b.c2), + }); + } + case Expr::Kind::Unary: { + const auto* u = static_cast(expr); + Value val = deref_to_value(evaluate_ast(u->operand.get(), ctx), *ctx.wb); + return EvalResult::from_value( + map_unary(val, [op = u->op](const Value& item) { return eval_scalar_unary(op, item); })); + } + case Expr::Kind::Percent: { + const auto* p = static_cast(expr); + Value val = deref_to_value(evaluate_ast(p->operand.get(), ctx), *ctx.wb); + return EvalResult::from_value(map_unary(val, eval_scalar_percent)); + } + case Expr::Kind::Binary: { + const auto* b = static_cast(expr); + EvalResult lr = evaluate_ast(b->lhs.get(), ctx); + EvalResult rr = evaluate_ast(b->rhs.get(), ctx); + + if (b->op == BinOp::Union) { + if (!lr.is_ref) { + return EvalResult::from_value( + lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value)); + } + if (!rr.is_ref) { + return EvalResult::from_value( + rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value)); + } + std::vector combined = std::move(lr.ranges); + combined.insert(combined.end(), rr.ranges.begin(), rr.ranges.end()); + return EvalResult::from_ranges(std::move(combined)); + } + + if (b->op == BinOp::Intersect) { + if (!lr.is_ref) { + return EvalResult::from_value( + lr.value.is_error() ? lr.value : Value::make_error(ErrorCode::Value)); + } + if (!rr.is_ref) { + return EvalResult::from_value( + rr.value.is_error() ? rr.value : Value::make_error(ErrorCode::Value)); + } + std::vector overlaps; + for (const auto& ra : lr.ranges) { + for (const auto& rb : rr.ranges) { + if (ra.sheet != rb.sheet) continue; + int r1 = std::max(ra.r1, rb.r1); + int c1 = std::max(ra.c1, rb.c1); + int r2 = std::min(ra.r2, rb.r2); + int c2 = std::min(ra.c2, rb.c2); + if (r1 <= r2 && c1 <= c2) { + overlaps.push_back(CellRange{ra.sheet, r1, c1, r2, c2}); + } + } + } + if (overlaps.empty()) { + return EvalResult::from_value(Value::make_error(ErrorCode::NA)); + } + return EvalResult::from_ranges(std::move(overlaps)); + } + + Value lv = deref_to_value(lr, *ctx.wb); + Value rv = deref_to_value(rr, *ctx.wb); + return EvalResult::from_value(broadcast_binary(b->op, lv, rv)); + } + case Expr::Kind::Call: { + const auto* call = static_cast(expr); + const auto* fn = FunctionRegistry::instance().find(call->name); + if (!fn) { + return EvalResult::from_value(Value::make_error(ErrorCode::Name)); + } + return (*fn)(call->args, ctx); + } + } + return EvalResult::from_value(Value::make_error(ErrorCode::Value)); +} + +} // namespace htab diff --git a/engine/evaluator.hpp b/engine/evaluator.hpp new file mode 100644 index 0000000..328312e --- /dev/null +++ b/engine/evaluator.hpp @@ -0,0 +1,50 @@ +#pragma once + +#include "engine/address.hpp" +#include "engine/parser.hpp" +#include "engine/value.hpp" + +#include + +namespace htab { + +class Workbook; + +struct EvalResult { + bool is_ref = false; + Value value; + std::vector ranges; + + static EvalResult from_value(Value v) { + EvalResult r; + r.is_ref = false; + r.value = std::move(v); + return r; + } + + static EvalResult from_range(CellRange rng) { + EvalResult r; + r.is_ref = true; + r.ranges.push_back(rng); + return r; + } + + static EvalResult from_ranges(std::vector rngs) { + EvalResult r; + r.is_ref = true; + r.ranges = std::move(rngs); + return r; + } +}; + +struct EvalContext { + const Workbook* wb = nullptr; + int current_sheet = 0; + int current_row = 0; + int current_col = 0; +}; + +Value deref_to_value(const EvalResult& res, const Workbook& wb); +EvalResult evaluate_ast(const Expr* expr, const EvalContext& ctx); + +} // namespace htab diff --git a/engine/format.cpp b/engine/format.cpp new file mode 100644 index 0000000..d5bc597 --- /dev/null +++ b/engine/format.cpp @@ -0,0 +1,185 @@ +#include "engine/format.hpp" + +#include +#include +#include + +namespace htab { + +namespace { + +// Howard Hinnant civil-from-days / days-from-civil (epoch 1970-01-01) +constexpr int64_t kEpochOffset = 25569; // days between 1899-12-30 and 1970-01-01 + +int64_t days_from_civil(int64_t y, unsigned m, unsigned d) { + y -= m <= 2; + const int64_t era = (y >= 0 ? y : y - 399) / 400; + const unsigned yoe = static_cast(y - era * 400); + const unsigned doy = (153 * (m + (m > 2 ? static_cast(-3) : 9)) + 2) / 5 + d - 1; + const unsigned doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; + return era * 146097 + static_cast(doe) - 719468; +} + +void civil_from_days(int64_t z, int& y_out, int& m_out, int& d_out) { + z += 719468; + const int64_t era = (z >= 0 ? z : z - 146096) / 146097; + const unsigned doe = static_cast(z - era * 146097); + const unsigned yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365; + const int64_t y = static_cast(yoe) + era * 400; + const unsigned doy = doe - (365 * yoe + yoe / 4 - yoe / 100); + const unsigned mp = (5 * doy + 2) / 153; + const unsigned d = doy - (153 * mp + 2) / 5 + 1; + const unsigned m = mp + (mp < 10 ? 3 : static_cast(-9)); + y_out = static_cast(y + (m <= 2)); + m_out = static_cast(m); + d_out = static_cast(d); +} + +std::string insert_thousands_commas(const std::string& int_digits) { + if (int_digits.size() <= 3) return int_digits; + std::string out; + out.reserve(int_digits.size() + int_digits.size() / 3); + size_t rem = int_digits.size() % 3; + size_t idx = 0; + if (rem > 0) { + out.append(int_digits, 0, rem); + idx = rem; + } + while (idx < int_digits.size()) { + if (!out.empty()) out.push_back(','); + out.append(int_digits, idx, 3); + idx += 3; + } + return out; +} + +std::string format_fixed_num(double v, int decimals, bool thousands) { + if (!std::isfinite(v)) return "#NUM!"; + bool neg = v < 0.0; + double av = std::fabs(v); + char buf[128]; + std::snprintf(buf, sizeof(buf), "%.*f", decimals, av); + std::string s(buf); + // Prevent "-0.00" when rounded value is zero. + bool all_zero = true; + for (char ch : s) { + if (ch >= '1' && ch <= '9') { + all_zero = false; + break; + } + } + if (all_zero) neg = false; + + if (thousands) { + size_t dot = s.find('.'); + std::string int_part = (dot == std::string::npos) ? s : s.substr(0, dot); + std::string frac_part = (dot == std::string::npos) ? "" : s.substr(dot); + s = insert_thousands_commas(int_part) + frac_part; + } + if (neg) s.insert(s.begin(), '-'); + return s; +} + +} // namespace + +int ymd_to_serial(int year, int month, int day) { + int64_t total_months = static_cast(year) * 12 + static_cast(month - 1); + int64_t norm_y = total_months >= 0 ? (total_months / 12) : ((total_months - 11) / 12); + int64_t norm_m = total_months - norm_y * 12 + 1; + int64_t days = days_from_civil(norm_y, static_cast(norm_m), 1) + + static_cast(day - 1) + kEpochOffset; + return static_cast(days); +} + +void serial_to_ymd(int serial, int& year, int& month, int& day) { + civil_from_days(static_cast(serial) - kEpochOffset, year, month, day); +} + +void serial_to_hms(double serial, int& hour, int& minute, int& second) { + double frac = serial - std::floor(serial); + long long total = std::llround(frac * 86400.0); + total = ((total % 86400) + 86400) % 86400; + hour = static_cast(total / 3600); + minute = static_cast((total % 3600) / 60); + second = static_cast(total % 60); +} + +std::string format_value(const Value& val, const std::string& fmt) { + if (val.is_empty()) return ""; + if (val.is_error()) return std::string(error_to_string(val.as_error())); + if (val.is_bool()) return val.as_bool() ? "TRUE" : "FALSE"; + if (val.is_string()) return val.as_string(); + if (val.is_array()) { + const auto& arr = val.as_array(); + if (arr && !arr->data.empty()) { + return format_value(arr->at(0, 0), fmt); + } + return ""; + } + + double d = val.as_number(); + if (fmt.empty() || iequals_ascii(fmt, "General")) { + auto s = to_string(val); + return std::holds_alternative(s) ? std::get(s) : "#VALUE!"; + } + + if (iequals_ascii(fmt, "Fixed") || fmt == "0.00") { + return format_fixed_num(d, 2, false); + } + if (iequals_ascii(fmt, "Integer") || fmt == "#,##0" || fmt == "0") { + return format_fixed_num(d, 0, fmt != "0"); + } + if (iequals_ascii(fmt, "Currency") || fmt == "$#,##0.00") { + bool neg = d < 0.0; + std::string body = format_fixed_num(std::fabs(d), 2, true); + bool all_zero = (body == "0.00"); + if (neg && !all_zero) return "-$" + body; + return "$" + body; + } + if (iequals_ascii(fmt, "Percentage") || fmt == "0.00%" || fmt == "0%") { + int dec = (fmt == "0%") ? 0 : 2; + return format_fixed_num(d * 100.0, dec, false) + "%"; + } + if (iequals_ascii(fmt, "Date") || iequals_ascii(fmt, "yyyy-mm-dd")) { + int y = 0, m = 0, day = 0; + serial_to_ymd(static_cast(std::floor(d)), y, m, day); + char buf[32]; + std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d", y, m, day); + return std::string(buf); + } + if (iequals_ascii(fmt, "Time") || iequals_ascii(fmt, "hh:mm:ss")) { + int hh = 0, mm = 0, ss = 0; + serial_to_hms(d, hh, mm, ss); + char buf[32]; + std::snprintf(buf, sizeof(buf), "%02d:%02d:%02d", hh, mm, ss); + return std::string(buf); + } + if (iequals_ascii(fmt, "DateTime") || iequals_ascii(fmt, "yyyy-mm-dd hh:mm")) { + int y = 0, m = 0, day = 0, hh = 0, mm = 0, ss = 0; + long long rounded_sec = std::llround((d - std::floor(d)) * 86400.0); + int day_serial = static_cast(std::floor(d)); + if (rounded_sec >= 86400) { + day_serial += 1; + } + serial_to_ymd(day_serial, y, m, day); + serial_to_hms(d, hh, mm, ss); + char buf[48]; + std::snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d", y, m, day, hh, mm); + return std::string(buf); + } + + // Fallback for custom decimal formats like "0.0" or "0.000%". + if (fmt.rfind("0.", 0) == 0) { + bool pct = fmt.back() == '%'; + size_t dec = fmt.size() - 2 - (pct ? 1 : 0); + if (dec <= 8) { + return format_fixed_num(pct ? d * 100.0 : d, static_cast(dec), false) + + (pct ? "%" : ""); + } + } + + auto s = to_string(val); + return std::holds_alternative(s) ? std::get(s) : "#VALUE!"; +} + +} // namespace htab diff --git a/engine/format.hpp b/engine/format.hpp new file mode 100644 index 0000000..85dc5ee --- /dev/null +++ b/engine/format.hpp @@ -0,0 +1,16 @@ +#pragma once + +#include "engine/value.hpp" + +#include + +namespace htab { + +// Pure proleptic Gregorian calendar with serial 0 = 1899-12-30. +int ymd_to_serial(int year, int month, int day); +void serial_to_ymd(int serial, int& year, int& month, int& day); +void serial_to_hms(double serial, int& hour, int& minute, int& second); + +std::string format_value(const Value& val, const std::string& fmt); + +} // namespace htab diff --git a/engine/functions/database.cpp b/engine/functions/database.cpp new file mode 100644 index 0000000..943e7fc --- /dev/null +++ b/engine/functions/database.cpp @@ -0,0 +1,269 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +// Shared helper required by design.md Section 4: +// Same criteria row = AND, different criteria rows = OR. +std::variant, ErrorCode> filterDatabase(const Array2D& db, + const Array2D& criteria) { + if (db.rows < 2 || db.cols < 1 || criteria.rows < 2 || criteria.cols < 1) { + return ErrorCode::Value; + } + + std::vector crit_to_db_col(static_cast(criteria.cols), -1); + for (int jc = 0; jc < criteria.cols; ++jc) { + auto h_var = to_string(criteria.at(0, jc)); + if (std::holds_alternative(h_var)) return std::get(h_var); + const std::string& h = std::get(h_var); + if (h.empty()) continue; + int found = -1; + for (int idb = 0; idb < db.cols; ++idb) { + auto dh_var = to_string(db.at(0, idb)); + if (std::holds_alternative(dh_var)) return std::get(dh_var); + if (iequals_ascii(h, std::get(dh_var))) { + found = idb; + break; + } + } + if (found < 0) return ErrorCode::Value; + crit_to_db_col[static_cast(jc)] = found; + } + + std::vector matched_rows; + for (int r = 1; r < db.rows; ++r) { + bool row_matches_any_or_clause = false; + for (int cr = 1; cr < criteria.rows; ++cr) { + bool clause_matches = true; + for (int jc = 0; jc < criteria.cols; ++jc) { + const Value& crit_cell = criteria.at(cr, jc); + if (crit_cell.is_empty()) continue; + int db_col = crit_to_db_col[static_cast(jc)]; + if (db_col < 0) { + clause_matches = false; + break; + } + if (!matches_criteria(db.at(r, db_col), crit_cell)) { + clause_matches = false; + break; + } + } + if (clause_matches) { + row_matches_any_or_clause = true; + break; + } + } + if (row_matches_any_or_clause) { + matched_rows.push_back(r); + } + } + return matched_rows; +} + +std::optional resolve_db_field(const Array2D& db, const Value& field, ErrorCode& err_out) { + if (field.is_error()) { + err_out = field.as_error(); + return std::nullopt; + } + if (field.is_number()) { + int idx = static_cast(std::trunc(field.as_number())) - 1; + if (idx < 0 || idx >= db.cols) { + err_out = ErrorCode::Value; + return std::nullopt; + } + return idx; + } + auto s_var = to_string(field); + if (std::holds_alternative(s_var)) { + err_out = std::get(s_var); + return std::nullopt; + } + const std::string& name = std::get(s_var); + for (int c = 0; c < db.cols; ++c) { + auto dh_var = to_string(db.at(0, c)); + if (std::holds_alternative(dh_var)) { + err_out = std::get(dh_var); + return std::nullopt; + } + if (iequals_ascii(name, std::get(dh_var))) { + return c; + } + } + err_out = ErrorCode::Value; + return std::nullopt; +} + +enum class DbOp { + Average, + Count, + CountA, + Get, + Max, + Min, + Product, + Stdev, + StdevP, + Sum, + Var, + VarP, +}; + +EvalResult run_db_op(const std::vector>& args, + const EvalContext& ctx, + DbOp op) { + if (args.size() != 3) return err_res(ErrorCode::Value); + auto db_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (std::holds_alternative(db_var)) return err_res(std::get(db_var)); + const Array2D& db = std::get(db_var); + + Value field_val = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb); + ErrorCode err = ErrorCode::Value; + auto field_col = resolve_db_field(db, field_val, err); + if (!field_col) return err_res(err); + + auto crit_var = result_to_array2d(evaluate_ast(args[2].get(), ctx), *ctx.wb); + if (std::holds_alternative(crit_var)) return err_res(std::get(crit_var)); + const Array2D& criteria = std::get(crit_var); + + auto rows_var = filterDatabase(db, criteria); + if (std::holds_alternative(rows_var)) return err_res(std::get(rows_var)); + const std::vector& matched = std::get>(rows_var); + + if (op == DbOp::Get) { + if (matched.empty()) return err_res(ErrorCode::Value); + if (matched.size() > 1) return err_res(ErrorCode::Num); + return EvalResult::from_value(db.at(matched[0], *field_col)); + } + + if (op == DbOp::CountA) { + size_t cnt = 0; + for (int r : matched) { + if (!db.at(r, *field_col).is_empty()) ++cnt; + } + return EvalResult::from_value(Value::make_number(static_cast(cnt))); + } + + std::vector nums; + for (int r : matched) { + const Value& v = db.at(r, *field_col); + if (v.is_error()) return EvalResult::from_value(v); + if (v.is_number()) nums.push_back(v.as_number()); + } + + switch (op) { + case DbOp::Count: + return EvalResult::from_value(Value::make_number(static_cast(nums.size()))); + case DbOp::Sum: { + double s = 0.0; + for (double v : nums) s += v; + return EvalResult::from_value(Value::make_checked_number(s)); + } + case DbOp::Average: { + if (nums.empty()) return err_res(ErrorCode::Div0); + double s = 0.0; + for (double v : nums) s += v; + return EvalResult::from_value(Value::make_checked_number(s / static_cast(nums.size()))); + } + case DbOp::Max: + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + return EvalResult::from_value( + Value::make_number(*std::max_element(nums.begin(), nums.end()))); + case DbOp::Min: + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + return EvalResult::from_value( + Value::make_number(*std::min_element(nums.begin(), nums.end()))); + case DbOp::Product: { + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + double p = 1.0; + for (double v : nums) p *= v; + return EvalResult::from_value(Value::make_checked_number(p)); + } + case DbOp::Var: + case DbOp::VarP: + case DbOp::Stdev: + case DbOp::StdevP: { + bool sample = (op == DbOp::Var || op == DbOp::Stdev); + bool take_sqrt = (op == DbOp::Stdev || op == DbOp::StdevP); + if (nums.size() < (sample ? 2U : 1U)) return err_res(ErrorCode::Div0); + double s = 0.0; + for (double v : nums) s += v; + double mean = s / static_cast(nums.size()); + double sq = 0.0; + for (double v : nums) { + double d = v - mean; + sq += d * d; + } + double var = sq / static_cast(sample ? (nums.size() - 1) : nums.size()); + return EvalResult::from_value(Value::make_checked_number(take_sqrt ? std::sqrt(var) : var)); + } + default: + return err_res(ErrorCode::Value); + } +} + +EvalResult fn_daverage(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Average); +} +EvalResult fn_dcount(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Count); +} +EvalResult fn_dcounta(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::CountA); +} +EvalResult fn_dget(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Get); +} +EvalResult fn_dmax(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Max); +} +EvalResult fn_dmin(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Min); +} +EvalResult fn_dproduct(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Product); +} +EvalResult fn_dstdev(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Stdev); +} +EvalResult fn_dstdevp(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::StdevP); +} +EvalResult fn_dsum(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Sum); +} +EvalResult fn_dvar(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::Var); +} +EvalResult fn_dvarp(const std::vector>& a, const EvalContext& c) { + return run_db_op(a, c, DbOp::VarP); +} + +} // namespace + +void register_database_functions(FunctionRegistry& reg) { + reg.register_fn("DAVERAGE", fn_daverage); + reg.register_fn("DCOUNT", fn_dcount); + reg.register_fn("DCOUNTA", fn_dcounta); + reg.register_fn("DGET", fn_dget); + reg.register_fn("DMAX", fn_dmax); + reg.register_fn("DMIN", fn_dmin); + reg.register_fn("DPRODUCT", fn_dproduct); + reg.register_fn("DSTDEV", fn_dstdev); + reg.register_fn("DSTDEVP", fn_dstdevp); + reg.register_fn("DSUM", fn_dsum); + reg.register_fn("DVAR", fn_dvar); + reg.register_fn("DVARP", fn_dvarp); +} + +} // namespace htab diff --git a/engine/functions/datetime.cpp b/engine/functions/datetime.cpp new file mode 100644 index 0000000..d0fd4fc --- /dev/null +++ b/engine/functions/datetime.cpp @@ -0,0 +1,316 @@ +#include "engine/format.hpp" +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +int days_in_month(int y, int m) { + static constexpr int kDays[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + if (m < 1 || m > 12) return 0; + if (m == 2) { + bool leap = (y % 4 == 0 && (y % 100 != 0 || y % 400 == 0)); + return leap ? 29 : 28; + } + return kDays[m - 1]; +} + +int parse_month_name(std::string_view s) { + static constexpr const char* kShort[] = { + "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec"}; + static constexpr const char* kFull[] = { + "january", "february", "march", "april", "may", "june", + "july", "august", "september", "october", "november", "december"}; + for (int i = 0; i < 12; ++i) { + if (iequals_ascii(s, kShort[i]) || iequals_ascii(s, kFull[i])) return i + 1; + } + return 0; +} + +bool parse_uint(std::string_view s, int& out) { + if (s.empty()) return false; + int64_t val = 0; + for (char ch : s) { + if (!std::isdigit(static_cast(ch))) return false; + val = val * 10 + (ch - '0'); + if (val > 1000000) return false; + } + out = static_cast(val); + return true; +} + +std::optional parse_date_string(std::string_view raw) { + raw = trim_ascii(raw); + if (raw.empty()) return std::nullopt; + + // Strip optional trailing time part if separated by space + // Wait: "Jan 5, 2024" has spaces, so only strip if contains ':' + size_t colon = raw.find(':'); + if (colon != std::string_view::npos) { + size_t sp = raw.rfind(' ', colon); + if (sp != std::string_view::npos) { + raw = trim_ascii(raw.substr(0, sp)); + } + } + + // Try YYYY-MM-DD or YYYY/MM/DD or MM/DD/YYYY or DD-MM-YYYY + auto split_sep = [&](char sep) -> std::vector { + std::vector parts; + size_t start = 0; + while (true) { + size_t p = raw.find(sep, start); + if (p == std::string_view::npos) { + parts.push_back(trim_ascii(raw.substr(start))); + break; + } + parts.push_back(trim_ascii(raw.substr(start, p - start))); + start = p + 1; + } + return parts; + }; + + for (char sep : {'-', '/'}) { + if (raw.find(sep) != std::string_view::npos) { + auto p = split_sep(sep); + if (p.size() == 3) { + int a = 0, b = 0, c = 0; + if (parse_uint(p[0], a) && parse_uint(p[1], b) && parse_uint(p[2], c)) { + int y = 0, m = 0, d = 0; + if (p[0].size() == 4) { + y = a; m = b; d = c; + } else { + m = a; d = b; y = c; + if (y < 100) y += (y >= 30 ? 1900 : 2000); + } + if (m >= 1 && m <= 12 && d >= 1 && d <= days_in_month(y, m)) { + return ymd_to_serial(y, m, d); + } + return std::nullopt; + } + // Try DD-Mon-YYYY + int mon = parse_month_name(p[1]); + if (mon > 0 && parse_uint(p[0], a) && parse_uint(p[2], c)) { + int y = c; + if (y < 100) y += (y >= 30 ? 1900 : 2000); + if (a >= 1 && a <= days_in_month(y, mon)) { + return ymd_to_serial(y, mon, a); + } + } + } + } + } + + // Try "Mon DD, YYYY" or "Mon DD YYYY" + std::vector words; + size_t i = 0; + while (i < raw.size()) { + while (i < raw.size() && (raw[i] == ' ' || raw[i] == ',')) ++i; + size_t st = i; + while (i < raw.size() && raw[i] != ' ' && raw[i] != ',') ++i; + if (i > st) words.push_back(raw.substr(st, i - st)); + } + if (words.size() == 3) { + int mon = parse_month_name(words[0]); + int d = 0, y = 0; + if (mon > 0 && parse_uint(words[1], d) && parse_uint(words[2], y)) { + if (d >= 1 && d <= days_in_month(y, mon)) { + return ymd_to_serial(y, mon, d); + } + } + } + return std::nullopt; +} + +std::optional parse_time_string(std::string_view raw) { + raw = trim_ascii(raw); + if (raw.empty()) return std::nullopt; + + bool has_ampm = false; + bool is_pm = false; + if (raw.size() >= 2) { + std::string_view tail = raw.substr(raw.size() - 2); + if (iequals_ascii(tail, "AM") || iequals_ascii(tail, "PM")) { + has_ampm = true; + is_pm = iequals_ascii(tail, "PM"); + raw = trim_ascii(raw.substr(0, raw.size() - 2)); + } + } + + // If date precedes space before time, take last space-separated token + size_t sp = raw.rfind(' '); + if (sp != std::string_view::npos) { + raw = trim_ascii(raw.substr(sp + 1)); + } + + std::vector parts; + size_t start = 0; + while (true) { + size_t p = raw.find(':', start); + if (p == std::string_view::npos) { + parts.push_back(raw.substr(start)); + break; + } + parts.push_back(raw.substr(start, p - start)); + start = p + 1; + } + if (parts.size() < 2 || parts.size() > 3) return std::nullopt; + + int h = 0, m = 0, s = 0; + if (!parse_uint(parts[0], h) || !parse_uint(parts[1], m)) return std::nullopt; + if (parts.size() == 3 && !parse_uint(parts[2], s)) return std::nullopt; + + if (has_ampm) { + if (h < 1 || h > 12) return std::nullopt; + if (h == 12) h = 0; + if (is_pm) h += 12; + } else { + if (h > 23) return std::nullopt; + } + if (m > 59 || s > 59) return std::nullopt; + return static_cast(h * 3600 + m * 60 + s) / 86400.0; +} + +EvalResult fn_date(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto yd = eval_number_arg(args[0], ctx, err); + if (!yd) return err_res(err); + auto md = eval_number_arg(args[1], ctx, err); + if (!md) return err_res(err); + auto dd = eval_number_arg(args[2], ctx, err); + if (!dd) return err_res(err); + + int y = static_cast(std::trunc(*yd)); + int m = static_cast(std::trunc(*md)); + int d = static_cast(std::trunc(*dd)); + if (y < 0 || y >= 10000) return err_res(ErrorCode::Num); + if (y < 1900) y += 1900; + int serial = ymd_to_serial(y, m, d); + if (serial < 0) return err_res(ErrorCode::Num); + return EvalResult::from_value(Value::make_number(static_cast(serial))); +} + +EvalResult fn_datevalue(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + auto serial = parse_date_string(*s); + if (!serial) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_number(static_cast(*serial))); +} + +EvalResult fn_time(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto hd = eval_number_arg(args[0], ctx, err); + if (!hd) return err_res(err); + auto md = eval_number_arg(args[1], ctx, err); + if (!md) return err_res(err); + auto sd = eval_number_arg(args[2], ctx, err); + if (!sd) return err_res(err); + + long long total = static_cast(std::trunc(*hd)) * 3600LL + + static_cast(std::trunc(*md)) * 60LL + + static_cast(std::trunc(*sd)); + if (total < 0) return err_res(ErrorCode::Num); + double frac = static_cast(total % 86400LL) / 86400.0; + return EvalResult::from_value(Value::make_number(frac)); +} + +EvalResult fn_timevalue(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + auto t = parse_time_string(*s); + if (!t) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_number(*t)); +} + +EvalResult fn_now(const std::vector>& args, const EvalContext&) { + if (!args.empty()) return err_res(ErrorCode::Value); + std::time_t now_t = std::time(nullptr); + std::tm local_tm{}; + localtime_r(&now_t, &local_tm); + int serial = ymd_to_serial(local_tm.tm_year + 1900, local_tm.tm_mon + 1, local_tm.tm_mday); + double frac = static_cast(local_tm.tm_hour * 3600 + local_tm.tm_min * 60 + + local_tm.tm_sec) / + 86400.0; + return EvalResult::from_value(Value::make_number(static_cast(serial) + frac)); +} + +EvalResult extract_ymd_part(const std::vector>& args, + const EvalContext& ctx, + int which) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto n = eval_number_arg(args[0], ctx, err); + if (!n) return err_res(err); + if (*n < 0.0) return err_res(ErrorCode::Num); + int y = 0, m = 0, d = 0; + serial_to_ymd(static_cast(std::floor(*n)), y, m, d); + int val = (which == 0) ? y : (which == 1 ? m : d); + return EvalResult::from_value(Value::make_number(static_cast(val))); +} + +EvalResult extract_hms_part(const std::vector>& args, + const EvalContext& ctx, + int which) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto n = eval_number_arg(args[0], ctx, err); + if (!n) return err_res(err); + if (*n < 0.0) return err_res(ErrorCode::Num); + int h = 0, m = 0, s = 0; + serial_to_hms(*n, h, m, s); + int val = (which == 0) ? h : (which == 1 ? m : s); + return EvalResult::from_value(Value::make_number(static_cast(val))); +} + +EvalResult fn_year(const std::vector>& a, const EvalContext& c) { + return extract_ymd_part(a, c, 0); +} +EvalResult fn_month(const std::vector>& a, const EvalContext& c) { + return extract_ymd_part(a, c, 1); +} +EvalResult fn_day(const std::vector>& a, const EvalContext& c) { + return extract_ymd_part(a, c, 2); +} +EvalResult fn_hour(const std::vector>& a, const EvalContext& c) { + return extract_hms_part(a, c, 0); +} +EvalResult fn_minute(const std::vector>& a, const EvalContext& c) { + return extract_hms_part(a, c, 1); +} +EvalResult fn_second(const std::vector>& a, const EvalContext& c) { + return extract_hms_part(a, c, 2); +} + +} // namespace + +void register_datetime_functions(FunctionRegistry& reg) { + reg.register_fn("DATE", fn_date); + reg.register_fn("DATEVALUE", fn_datevalue); + reg.register_fn("DAY", fn_day); + reg.register_fn("HOUR", fn_hour); + reg.register_fn("MINUTE", fn_minute); + reg.register_fn("MONTH", fn_month); + reg.register_fn("NOW", fn_now); + reg.register_fn("SECOND", fn_second); + reg.register_fn("TIME", fn_time); + reg.register_fn("TIMEVALUE", fn_timevalue); + reg.register_fn("YEAR", fn_year); +} + +} // namespace htab diff --git a/engine/functions/financial.cpp b/engine/functions/financial.cpp new file mode 100644 index 0000000..00c343b --- /dev/null +++ b/engine/functions/financial.cpp @@ -0,0 +1,377 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +double tvm_eval(double rate, double nper, double pmt, double pv, double fv, int type) { + if (std::fabs(rate) < 1e-12) { + return pv + pmt * nper + fv; + } + double factor = std::pow(1.0 + rate, nper); + return pv * factor + pmt * (1.0 + rate * type) * ((factor - 1.0) / rate) + fv; +} + +EvalResult fn_fv(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto rate = eval_number_arg(args[0], ctx, err); + if (!rate) return err_res(err); + auto nper = eval_number_arg(args[1], ctx, err); + if (!nper) return err_res(err); + auto pmt = eval_number_arg(args[2], ctx, err); + if (!pmt) return err_res(err); + double pv = 0.0; + int type = 0; + if (args.size() >= 4) { + auto p = eval_number_arg(args[3], ctx, err); + if (!p) return err_res(err); + pv = *p; + } + if (args.size() == 5) { + auto t = eval_number_arg(args[4], ctx, err); + if (!t) return err_res(err); + type = (*t != 0.0) ? 1 : 0; + } + double fv = 0.0; + if (std::fabs(*rate) < 1e-12) { + fv = -(pv + *pmt * *nper); + } else { + double factor = std::pow(1.0 + *rate, *nper); + fv = -(pv * factor + *pmt * (1.0 + *rate * type) * ((factor - 1.0) / *rate)); + } + return EvalResult::from_value(Value::make_checked_number(fv)); +} + +EvalResult fn_pv(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto rate = eval_number_arg(args[0], ctx, err); + if (!rate) return err_res(err); + auto nper = eval_number_arg(args[1], ctx, err); + if (!nper) return err_res(err); + auto pmt = eval_number_arg(args[2], ctx, err); + if (!pmt) return err_res(err); + double fv = 0.0; + int type = 0; + if (args.size() >= 4) { + auto f = eval_number_arg(args[3], ctx, err); + if (!f) return err_res(err); + fv = *f; + } + if (args.size() == 5) { + auto t = eval_number_arg(args[4], ctx, err); + if (!t) return err_res(err); + type = (*t != 0.0) ? 1 : 0; + } + double pv = 0.0; + if (std::fabs(*rate) < 1e-12) { + pv = -(*pmt * *nper + fv); + } else { + double factor = std::pow(1.0 + *rate, *nper); + pv = -(fv + *pmt * (1.0 + *rate * type) * ((factor - 1.0) / *rate)) / factor; + } + return EvalResult::from_value(Value::make_checked_number(pv)); +} + +EvalResult fn_pmt(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto rate = eval_number_arg(args[0], ctx, err); + if (!rate) return err_res(err); + auto nper = eval_number_arg(args[1], ctx, err); + if (!nper) return err_res(err); + auto pv = eval_number_arg(args[2], ctx, err); + if (!pv) return err_res(err); + double fv = 0.0; + int type = 0; + if (args.size() >= 4) { + auto f = eval_number_arg(args[3], ctx, err); + if (!f) return err_res(err); + fv = *f; + } + if (args.size() == 5) { + auto t = eval_number_arg(args[4], ctx, err); + if (!t) return err_res(err); + type = (*t != 0.0) ? 1 : 0; + } + if (*nper == 0.0) return err_res(ErrorCode::Num); + double pmt = 0.0; + if (std::fabs(*rate) < 1e-12) { + pmt = -(*pv + fv) / *nper; + } else { + double factor = std::pow(1.0 + *rate, *nper); + double denom = (1.0 + *rate * type) * ((factor - 1.0) / *rate); + if (denom == 0.0) return err_res(ErrorCode::Div0); + pmt = -(*pv * factor + fv) / denom; + } + return EvalResult::from_value(Value::make_checked_number(pmt)); +} + +EvalResult fn_nper(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 5) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto rate = eval_number_arg(args[0], ctx, err); + if (!rate) return err_res(err); + auto pmt = eval_number_arg(args[1], ctx, err); + if (!pmt) return err_res(err); + auto pv = eval_number_arg(args[2], ctx, err); + if (!pv) return err_res(err); + double fv = 0.0; + int type = 0; + if (args.size() >= 4) { + auto f = eval_number_arg(args[3], ctx, err); + if (!f) return err_res(err); + fv = *f; + } + if (args.size() == 5) { + auto t = eval_number_arg(args[4], ctx, err); + if (!t) return err_res(err); + type = (*t != 0.0) ? 1 : 0; + } + if (std::fabs(*rate) < 1e-12) { + if (*pmt == 0.0) return err_res(ErrorCode::Div0); + return EvalResult::from_value(Value::make_checked_number(-(*pv + fv) / *pmt)); + } + if (*rate <= -1.0) return err_res(ErrorCode::Num); + double z = *pmt * (1.0 + *rate * type) / *rate; + double num = z - fv; + double den = z + *pv; + if (den == 0.0 || num / den <= 0.0) return err_res(ErrorCode::Num); + double nper = std::log(num / den) / std::log(1.0 + *rate); + return EvalResult::from_value(Value::make_checked_number(nper)); +} + +EvalResult fn_rate(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 6) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto nper = eval_number_arg(args[0], ctx, err); + if (!nper) return err_res(err); + auto pmt = eval_number_arg(args[1], ctx, err); + if (!pmt) return err_res(err); + auto pv = eval_number_arg(args[2], ctx, err); + if (!pv) return err_res(err); + double fv = 0.0; + int type = 0; + double guess = 0.1; + if (args.size() >= 4) { + auto f = eval_number_arg(args[3], ctx, err); + if (!f) return err_res(err); + fv = *f; + } + if (args.size() >= 5) { + auto t = eval_number_arg(args[4], ctx, err); + if (!t) return err_res(err); + type = (*t != 0.0) ? 1 : 0; + } + if (args.size() == 6) { + auto g = eval_number_arg(args[5], ctx, err); + if (!g) return err_res(err); + guess = *g; + } + if (*nper <= 0.0) return err_res(ErrorCode::Num); + + double r = guess; + for (int iter = 0; iter < 100; ++iter) { + if (r <= -1.0) r = -0.999; + double f = tvm_eval(r, *nper, *pmt, *pv, fv, type); + if (std::fabs(f) < 1e-10) return EvalResult::from_value(Value::make_checked_number(r)); + double eps = 1e-6; + double df = (tvm_eval(r + eps, *nper, *pmt, *pv, fv, type) - f) / eps; + if (!std::isfinite(df) || std::fabs(df) < 1e-14) break; + double nr = r - f / df; + if (nr <= -1.0) nr = (r - 1.0) * 0.5; + if (std::fabs(nr - r) < 1e-10) { + return EvalResult::from_value(Value::make_checked_number(nr)); + } + r = nr; + } + return err_res(ErrorCode::Num); +} + +EvalResult fn_npv(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto rate = eval_number_arg(args[0], ctx, err); + if (!rate) return err_res(err); + if (*rate == -1.0) return err_res(ErrorCode::Div0); + + std::vector> cf_args(args.begin() + 1, args.end()); + std::vector cfs; + if (auto cerr = collect_numeric_args(cf_args, ctx, cfs)) return err_res(*cerr); + + double total = 0.0; + double denom = 1.0 + *rate; + double pow_d = denom; + for (double cf : cfs) { + total += cf / pow_d; + pow_d *= denom; + } + return EvalResult::from_value(Value::make_checked_number(total)); +} + +EvalResult fn_irr(const std::vector>& args, const EvalContext& ctx) { + if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value); + std::vector> single{args[0]}; + std::vector cfs; + if (auto err = collect_numeric_args(single, ctx, cfs)) return err_res(*err); + if (cfs.size() < 2) return err_res(ErrorCode::Num); + + bool has_pos = false, has_neg = false; + for (double v : cfs) { + if (v > 0.0) has_pos = true; + if (v < 0.0) has_neg = true; + } + if (!has_pos || !has_neg) return err_res(ErrorCode::Num); + + double guess = 0.1; + if (args.size() == 2) { + ErrorCode err = ErrorCode::Value; + auto g = eval_number_arg(args[1], ctx, err); + if (!g) return err_res(err); + guess = *g; + } + + auto eval_npv_and_deriv = [&](double r, double& f, double& df) { + double base = 1.0 + r; + f = 0.0; + df = 0.0; + double pow_b = 1.0; + for (size_t i = 0; i < cfs.size(); ++i) { + f += cfs[i] / pow_b; + if (i > 0) { + df -= static_cast(i) * cfs[i] / (pow_b * base); + } + pow_b *= base; + } + }; + + double r = guess; + for (int iter = 0; iter < 100; ++iter) { + if (r <= -1.0) r = -0.999; + double f = 0.0, df = 0.0; + eval_npv_and_deriv(r, f, df); + if (std::fabs(f) < 1e-10) return EvalResult::from_value(Value::make_checked_number(r)); + if (!std::isfinite(df) || std::fabs(df) < 1e-14) break; + double nr = r - f / df; + if (nr <= -1.0) nr = (r - 1.0) * 0.5; + if (std::fabs(nr - r) < 1e-10) { + return EvalResult::from_value(Value::make_checked_number(nr)); + } + r = nr; + } + + // Bisection fallback on (-0.9999, 100.0] + double lo = -0.99, hi = 10.0, f_lo = 0.0, df_unused = 0.0, f_hi = 0.0; + eval_npv_and_deriv(lo, f_lo, df_unused); + eval_npv_and_deriv(hi, f_hi, df_unused); + if (f_lo * f_hi <= 0.0) { + for (int iter = 0; iter < 120; ++iter) { + double mid = 0.5 * (lo + hi); + double f_mid = 0.0; + eval_npv_and_deriv(mid, f_mid, df_unused); + if (std::fabs(f_mid) < 1e-10 || (hi - lo) < 1e-12) { + return EvalResult::from_value(Value::make_checked_number(mid)); + } + if (f_lo * f_mid <= 0.0) { + hi = mid; + f_hi = f_mid; + } else { + lo = mid; + f_lo = f_mid; + } + } + } + return err_res(ErrorCode::Num); +} + +EvalResult fn_sln(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto cost = eval_number_arg(args[0], ctx, err); + if (!cost) return err_res(err); + auto salvage = eval_number_arg(args[1], ctx, err); + if (!salvage) return err_res(err); + auto life = eval_number_arg(args[2], ctx, err); + if (!life) return err_res(err); + if (*life == 0.0) return err_res(ErrorCode::Div0); + return EvalResult::from_value(Value::make_checked_number((*cost - *salvage) / *life)); +} + +EvalResult fn_syd(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 4) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto cost = eval_number_arg(args[0], ctx, err); + if (!cost) return err_res(err); + auto salvage = eval_number_arg(args[1], ctx, err); + if (!salvage) return err_res(err); + auto life = eval_number_arg(args[2], ctx, err); + if (!life) return err_res(err); + auto per = eval_number_arg(args[3], ctx, err); + if (!per) return err_res(err); + if (*life <= 0.0 || *per <= 0.0 || *per > *life) return err_res(ErrorCode::Num); + double res = ((*cost - *salvage) * (*life - *per + 1.0) * 2.0) / (*life * (*life + 1.0)); + return EvalResult::from_value(Value::make_checked_number(res)); +} + +EvalResult fn_ddb(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 4 || args.size() > 5) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto cost = eval_number_arg(args[0], ctx, err); + if (!cost) return err_res(err); + auto salvage = eval_number_arg(args[1], ctx, err); + if (!salvage) return err_res(err); + auto life = eval_number_arg(args[2], ctx, err); + if (!life) return err_res(err); + auto period = eval_number_arg(args[3], ctx, err); + if (!period) return err_res(err); + double factor = 2.0; + if (args.size() == 5) { + auto f = eval_number_arg(args[4], ctx, err); + if (!f) return err_res(err); + factor = *f; + } + if (*cost < 0.0 || *salvage < 0.0 || *life <= 0.0 || *period <= 0.0 || + *period > *life || factor <= 0.0) { + return err_res(ErrorCode::Num); + } + if (*cost <= *salvage) return EvalResult::from_value(Value::make_number(0.0)); + + double book = *cost; + double rate = std::min(1.0, factor / *life); + int full_p = static_cast(std::floor(*period)); + double dep = 0.0; + for (int p = 1; p <= full_p; ++p) { + dep = std::min(book * rate, std::max(0.0, book - *salvage)); + book -= dep; + } + double rem = *period - static_cast(full_p); + if (rem > 1e-12) { + dep = std::min(book * rate * rem, std::max(0.0, book - *salvage)); + } + return EvalResult::from_value(Value::make_checked_number(dep)); +} + +} // namespace + +void register_financial_functions(FunctionRegistry& reg) { + reg.register_fn("DDB", fn_ddb); + reg.register_fn("FV", fn_fv); + reg.register_fn("IRR", fn_irr); + reg.register_fn("NPER", fn_nper); + reg.register_fn("NPV", fn_npv); + reg.register_fn("PMT", fn_pmt); + reg.register_fn("PV", fn_pv); + reg.register_fn("RATE", fn_rate); + reg.register_fn("SLN", fn_sln); + reg.register_fn("SYD", fn_syd); +} + +} // namespace htab diff --git a/engine/functions/helpers.cpp b/engine/functions/helpers.cpp new file mode 100644 index 0000000..67ad5a6 --- /dev/null +++ b/engine/functions/helpers.cpp @@ -0,0 +1,387 @@ +#include "engine/functions/helpers.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include + +namespace htab::fn { + +namespace { + +std::optional try_parse_simple_number(std::string_view sv) { + sv = trim_ascii(sv); + if (sv.empty()) return std::nullopt; + bool pct = false; + if (sv.back() == '%') { + pct = true; + sv.remove_suffix(1); + sv = trim_ascii(sv); + if (sv.empty()) return std::nullopt; + } + size_t i = 0; + if (sv[i] == '+' || sv[i] == '-') ++i; + bool has_digits = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + if (i < sv.size() && sv[i] == '.') { + ++i; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + } + if (!has_digits) return std::nullopt; + if (i < sv.size() && (sv[i] == 'e' || sv[i] == 'E')) { + ++i; + if (i < sv.size() && (sv[i] == '+' || sv[i] == '-')) ++i; + bool exp_d = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + exp_d = true; + ++i; + } + if (!exp_d) return std::nullopt; + } + if (i != sv.size()) return std::nullopt; + std::string tmp(sv); + char* endptr = nullptr; + double val = std::strtod(tmp.c_str(), &endptr); + if (endptr != tmp.c_str() + tmp.size() || !std::isfinite(val)) return std::nullopt; + if (pct) val /= 100.0; + return val == 0.0 ? 0.0 : val; +} + +std::vector parse_wildcard_tokens(std::string_view pat) { + auto raw_cps = utf8_codepoints(pat); + std::vector out; + out.reserve(raw_cps.size()); + for (size_t i = 0; i < raw_cps.size(); ++i) { + out.push_back(raw_cps[i]); + } + return out; +} + +struct PatAtom { + enum Kind { WildMany, WildOne, Literal }; + Kind kind = Literal; + std::string_view cp; +}; + +std::vector compile_wildcard(std::string_view pattern) { + auto cps = parse_wildcard_tokens(pattern); + std::vector atoms; + atoms.reserve(cps.size()); + for (size_t i = 0; i < cps.size(); ++i) { + if (cps[i] == "~" && i + 1 < cps.size()) { + atoms.push_back({PatAtom::Literal, cps[i + 1]}); + ++i; + } else if (cps[i] == "*") { + if (atoms.empty() || atoms.back().kind != PatAtom::WildMany) { + atoms.push_back({PatAtom::WildMany, {}}); + } + } else if (cps[i] == "?") { + atoms.push_back({PatAtom::WildOne, {}}); + } else { + atoms.push_back({PatAtom::Literal, cps[i]}); + } + } + return atoms; +} + +bool cp_iequals(std::string_view a, std::string_view b) { + if (a.size() == 1 && b.size() == 1) { + return std::tolower(static_cast(a[0])) == + std::tolower(static_cast(b[0])); + } + return a == b; +} + +} // namespace + +std::optional eval_scalar_arg(const std::shared_ptr& expr, + const EvalContext& ctx) { + Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb); + return v; +} + +std::optional eval_number_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out) { + Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb); + auto n = to_number(v); + if (std::holds_alternative(n)) { + err_out = std::get(n); + return std::nullopt; + } + return std::get(n); +} + +std::optional eval_bool_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out) { + Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb); + auto b = to_bool(v); + if (std::holds_alternative(b)) { + err_out = std::get(b); + return std::nullopt; + } + return std::get(b); +} + +std::optional eval_string_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out) { + Value v = deref_to_value(evaluate_ast(expr.get(), ctx), *ctx.wb); + auto s = to_string(v); + if (std::holds_alternative(s)) { + err_out = std::get(s); + return std::nullopt; + } + return std::get(s); +} + +std::optional collect_numeric_args( + const std::vector>& args, + const EvalContext& ctx, + std::vector& out_nums) { + for (const auto& arg : args) { + EvalResult res = evaluate_ast(arg.get(), ctx); + if (res.is_ref) { + for (const auto& rng : res.ranges) { + for (int r = rng.r1; r <= rng.r2; ++r) { + for (int c = rng.c1; c <= rng.c2; ++c) { + Value v = ctx.wb->get_scalar_value(rng.sheet, r, c); + if (v.is_error()) return v.as_error(); + if (v.is_number()) out_nums.push_back(v.as_number()); + } + } + } + } else if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + if (arr) { + for (const auto& v : arr->data) { + if (v.is_error()) return v.as_error(); + if (v.is_number()) out_nums.push_back(v.as_number()); + } + } + } else { + const Value& v = res.value; + if (v.is_error()) return v.as_error(); + if (v.is_empty()) continue; + auto num = to_number(v); + if (std::holds_alternative(num)) { + return std::get(num); + } + out_nums.push_back(std::get(num)); + } + } + return std::nullopt; +} + +std::variant result_to_array2d(const EvalResult& res, + const Workbook& wb) { + if (res.is_ref) { + if (res.ranges.size() != 1) return ErrorCode::Value; + const CellRange& rng = res.ranges[0]; + int rc = rng.row_count(); + int cc = rng.col_count(); + Array2D arr(rc, cc); + for (int r = 0; r < rc; ++r) { + for (int c = 0; c < cc; ++c) { + arr.at(r, c) = wb.get_scalar_value(rng.sheet, rng.r1 + r, rng.c1 + c); + } + } + return arr; + } + if (res.value.is_error()) return res.value.as_error(); + if (res.value.is_array()) { + const auto& p = res.value.as_array(); + if (!p) return ErrorCode::Value; + return *p; + } + Array2D single(1, 1, res.value); + return single; +} + +std::vector utf8_codepoints(std::string_view s) { + std::vector cps; + size_t i = 0; + while (i < s.size()) { + unsigned char b = static_cast(s[i]); + size_t len = 1; + if ((b & 0x80) == 0) len = 1; + else if ((b & 0xE0) == 0xC0) len = 2; + else if ((b & 0xF0) == 0xE0) len = 3; + else if ((b & 0xF8) == 0xF0) len = 4; + if (i + len > s.size()) len = 1; + cps.push_back(s.substr(i, len)); + i += len; + } + return cps; +} + +std::string utf8_join(const std::vector& cps, size_t start, size_t count) { + std::string out; + size_t end = std::min(cps.size(), start + count); + for (size_t i = start; i < end; ++i) { + out.append(cps[i]); + } + return out; +} + +bool wildcard_match_ci(std::string_view pattern, std::string_view text) { + auto atoms = compile_wildcard(pattern); + auto text_cps = utf8_codepoints(text); + size_t m = atoms.size(); + size_t n = text_cps.size(); + + std::vector prev(n + 1, false), curr(n + 1, false); + prev[0] = true; + for (size_t i = 0; i < m; ++i) { + std::fill(curr.begin(), curr.end(), false); + if (atoms[i].kind == PatAtom::WildMany) { + curr[0] = prev[0]; + for (size_t j = 1; j <= n; ++j) { + curr[j] = prev[j] || curr[j - 1]; + } + } else if (atoms[i].kind == PatAtom::WildOne) { + for (size_t j = 1; j <= n; ++j) { + curr[j] = prev[j - 1]; + } + } else { + for (size_t j = 1; j <= n; ++j) { + if (prev[j - 1] && cp_iequals(atoms[i].cp, text_cps[j - 1])) { + curr[j] = true; + } + } + } + prev.swap(curr); + } + return prev[n]; +} + +bool matches_criteria(const Value& cell_val, const Value& criteria_val) { + if (criteria_val.is_error()) { + return cell_val.is_error() && cell_val.as_error() == criteria_val.as_error(); + } + if (criteria_val.is_empty()) { + return cell_val.is_empty() || + (cell_val.is_string() && cell_val.as_string().empty()); + } + if (criteria_val.is_number()) { + if (cell_val.is_number()) return cell_val.as_number() == criteria_val.as_number(); + if (cell_val.is_string()) { + auto n = try_parse_simple_number(cell_val.as_string()); + return n.has_value() && *n == criteria_val.as_number(); + } + return false; + } + if (criteria_val.is_bool()) { + return cell_val.is_bool() && cell_val.as_bool() == criteria_val.as_bool(); + } + if (!criteria_val.is_string()) { + return false; + } + + std::string_view crit = criteria_val.as_string(); + enum class Op { Eq, Neq, Lt, Gt, Le, Ge }; + Op op = Op::Eq; + bool has_explicit_op = false; + if (crit.rfind("<=", 0) == 0) { op = Op::Le; crit.remove_prefix(2); has_explicit_op = true; } + else if (crit.rfind(">=", 0) == 0) { op = Op::Ge; crit.remove_prefix(2); has_explicit_op = true; } + else if (crit.rfind("<>", 0) == 0) { op = Op::Neq; crit.remove_prefix(2); has_explicit_op = true; } + else if (!crit.empty() && crit[0] == '<') { op = Op::Lt; crit.remove_prefix(1); has_explicit_op = true; } + else if (!crit.empty() && crit[0] == '>') { op = Op::Gt; crit.remove_prefix(1); has_explicit_op = true; } + else if (!crit.empty() && crit[0] == '=') { op = Op::Eq; crit.remove_prefix(1); has_explicit_op = true; } + + // Special empty checks "=" and "<>" + if (has_explicit_op && crit.empty()) { + bool is_cell_blank = cell_val.is_empty() || + (cell_val.is_string() && cell_val.as_string().empty()); + if (op == Op::Eq) return is_cell_blank; + if (op == Op::Neq) return !is_cell_blank; + return false; + } + + auto rhs_num = try_parse_simple_number(crit); + if (rhs_num.has_value()) { + if (cell_val.is_number()) { + double cv = cell_val.as_number(); + double rv = *rhs_num; + switch (op) { + case Op::Eq: return cv == rv; + case Op::Neq: return cv != rv; + case Op::Lt: return cv < rv; + case Op::Gt: return cv > rv; + case Op::Le: return cv <= rv; + case Op::Ge: return cv >= rv; + } + } + if (op == Op::Neq) { + if (cell_val.is_string()) { + auto cn = try_parse_simple_number(cell_val.as_string()); + if (cn.has_value()) return *cn != *rhs_num; + } + return true; + } + if (op == Op::Eq && cell_val.is_string()) { + auto cn = try_parse_simple_number(cell_val.as_string()); + return cn.has_value() && *cn == *rhs_num; + } + return false; + } + + // Boolean criteria literal + std::string_view crit_trim = trim_ascii(crit); + if (iequals_ascii(crit_trim, "TRUE") || iequals_ascii(crit_trim, "FALSE")) { + bool rb = iequals_ascii(crit_trim, "TRUE"); + if (cell_val.is_bool()) { + bool cb = cell_val.as_bool(); + switch (op) { + case Op::Eq: return cb == rb; + case Op::Neq: return cb != rb; + case Op::Lt: return !cb && rb; + case Op::Gt: return cb && !rb; + case Op::Le: return cb <= rb; + case Op::Ge: return cb >= rb; + } + } + return op == Op::Neq; + } + + // Error criteria literal + if (auto rerr = parse_error_code(crit_trim)) { + bool same = cell_val.is_error() && cell_val.as_error() == *rerr; + if (op == Op::Eq) return same; + if (op == Op::Neq) return !same; + return false; + } + + // String comparison / wildcard matching + if (op == Op::Eq) { + if (cell_val.is_empty()) return crit.empty(); + if (!cell_val.is_string()) return false; + return wildcard_match_ci(crit, cell_val.as_string()); + } + if (op == Op::Neq) { + if (cell_val.is_empty()) return !crit.empty(); + if (!cell_val.is_string()) return true; + return !wildcard_match_ci(crit, cell_val.as_string()); + } + // Relational string comparison (<, >, <=, >=) + if (!cell_val.is_string()) return false; + auto cmp = compare_values(cell_val, Value::make_string(std::string(crit))); + if (!std::holds_alternative(cmp)) return false; + int c = std::get(cmp); + switch (op) { + case Op::Lt: return c < 0; + case Op::Gt: return c > 0; + case Op::Le: return c <= 0; + case Op::Ge: return c >= 0; + default: return false; + } +} + +} // namespace htab::fn diff --git a/engine/functions/helpers.hpp b/engine/functions/helpers.hpp new file mode 100644 index 0000000..934acf1 --- /dev/null +++ b/engine/functions/helpers.hpp @@ -0,0 +1,54 @@ +#pragma once + +#include "engine/evaluator.hpp" + +#include +#include +#include +#include +#include +#include + +namespace htab::fn { + +inline EvalResult err_res(ErrorCode e) { + return EvalResult::from_value(Value::make_error(e)); +} + +std::optional eval_scalar_arg(const std::shared_ptr& expr, + const EvalContext& ctx); + +std::optional eval_number_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out); + +std::optional eval_bool_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out); + +std::optional eval_string_arg(const std::shared_ptr& expr, + const EvalContext& ctx, + ErrorCode& err_out); + +// Collects numeric values from variadic arguments following spreadsheet semantics: +// - Range/Array args: only numbers (ignoring Empty, String, Bool); Error propagates. +// - Direct scalar args: coerces numbers, booleans, numeric strings; Empty ignored; +// invalid text -> #VALUE!; Error propagates. +std::optional collect_numeric_args( + const std::vector>& args, + const EvalContext& ctx, + std::vector& out_nums); + +// Converts a single EvalResult (CellRange or Value) to Array2D. +std::variant result_to_array2d(const EvalResult& res, + const Workbook& wb); + +// Shared criteria matcher used by SUMIF/SUMIFS/COUNTIF/COUNTIFS/Database. +bool matches_criteria(const Value& cell_val, const Value& criteria_val); +bool wildcard_match_ci(std::string_view pattern, std::string_view text); + +// UTF-8 codepoint helpers +std::vector utf8_codepoints(std::string_view s); +std::string utf8_join(const std::vector& cps, size_t start, size_t count); + +} // namespace htab::fn diff --git a/engine/functions/logical.cpp b/engine/functions/logical.cpp new file mode 100644 index 0000000..5f0cb89 --- /dev/null +++ b/engine/functions/logical.cpp @@ -0,0 +1,122 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +std::optional collect_logicals(const std::vector>& args, + const EvalContext& ctx, + bool& any_found, + bool is_and, + bool& acc) { + any_found = false; + acc = is_and; + for (const auto& arg : args) { + EvalResult res = evaluate_ast(arg.get(), ctx); + if (res.is_ref) { + for (const auto& rng : res.ranges) { + for (int r = rng.r1; r <= rng.r2; ++r) { + for (int c = rng.c1; c <= rng.c2; ++c) { + Value v = ctx.wb->get_scalar_value(rng.sheet, r, c); + if (v.is_error()) return v.as_error(); + if (v.is_bool()) { + any_found = true; + acc = is_and ? (acc && v.as_bool()) : (acc || v.as_bool()); + } else if (v.is_number()) { + any_found = true; + bool b = (v.as_number() != 0.0); + acc = is_and ? (acc && b) : (acc || b); + } + } + } + } + } else if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + if (arr) { + for (const auto& v : arr->data) { + if (v.is_error()) return v.as_error(); + if (v.is_bool()) { + any_found = true; + acc = is_and ? (acc && v.as_bool()) : (acc || v.as_bool()); + } else if (v.is_number()) { + any_found = true; + bool b = (v.as_number() != 0.0); + acc = is_and ? (acc && b) : (acc || b); + } + } + } + } else { + const Value& v = res.value; + if (v.is_error()) return v.as_error(); + if (v.is_empty()) continue; + auto b = to_bool(v); + if (std::holds_alternative(b)) return std::get(b); + any_found = true; + acc = is_and ? (acc && std::get(b)) : (acc || std::get(b)); + } + } + return std::nullopt; +} + +EvalResult fn_and(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + bool any = false, acc = true; + if (auto err = collect_logicals(args, ctx, any, true, acc)) return err_res(*err); + if (!any) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_bool(acc)); +} + +EvalResult fn_or(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + bool any = false, acc = false; + if (auto err = collect_logicals(args, ctx, any, false, acc)) return err_res(*err); + if (!any) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_bool(acc)); +} + +EvalResult fn_not(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto b = eval_bool_arg(args[0], ctx, err); + if (!b) return err_res(err); + return EvalResult::from_value(Value::make_bool(!*b)); +} + +EvalResult fn_if(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto b = eval_bool_arg(args[0], ctx, err); + if (!b) return err_res(err); + if (*b) return evaluate_ast(args[1].get(), ctx); + if (args.size() == 3) return evaluate_ast(args[2].get(), ctx); + return EvalResult::from_value(Value::make_bool(false)); +} + +EvalResult fn_true(const std::vector>& args, const EvalContext&) { + if (!args.empty()) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_bool(true)); +} + +EvalResult fn_false(const std::vector>& args, const EvalContext&) { + if (!args.empty()) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_bool(false)); +} + +} // namespace + +void register_logical_functions(FunctionRegistry& reg) { + reg.register_fn("AND", fn_and); + reg.register_fn("FALSE", fn_false); + reg.register_fn("IF", fn_if); + reg.register_fn("NOT", fn_not); + reg.register_fn("OR", fn_or); + reg.register_fn("TRUE", fn_true); +} + +} // namespace htab diff --git a/engine/functions/lookup.cpp b/engine/functions/lookup.cpp new file mode 100644 index 0000000..cb85863 --- /dev/null +++ b/engine/functions/lookup.cpp @@ -0,0 +1,353 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +bool values_equal_for_lookup(const Value& candidate, const Value& key) { + if (candidate.is_error() || key.is_error() || candidate.is_empty() || key.is_empty()) { + return false; + } + if (key.is_string() && candidate.is_string()) { + return wildcard_match_ci(key.as_string(), candidate.as_string()); + } + if (key.is_number() && candidate.is_number()) { + return candidate.as_number() == key.as_number(); + } + if (key.is_bool() && candidate.is_bool()) { + return candidate.as_bool() == key.as_bool(); + } + return false; +} + +bool same_lookup_type(const Value& a, const Value& b) { + return (a.is_number() && b.is_number()) || + (a.is_string() && b.is_string()) || + (a.is_bool() && b.is_bool()); +} + +EvalResult fn_choose(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto idx_d = eval_number_arg(args[0], ctx, err); + if (!idx_d) return err_res(err); + int idx = static_cast(std::trunc(*idx_d)); + if (idx < 1 || static_cast(idx) >= args.size()) return err_res(ErrorCode::Value); + return evaluate_ast(args[static_cast(idx)].get(), ctx); +} + +EvalResult fn_rows(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + EvalResult res = evaluate_ast(args[0].get(), ctx); + if (res.is_ref) { + if (res.ranges.size() != 1) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_number(static_cast(res.ranges[0].row_count()))); + } + if (res.value.is_error()) return EvalResult::from_value(res.value); + if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + return EvalResult::from_value(Value::make_number(static_cast(arr ? arr->rows : 0))); + } + return EvalResult::from_value(Value::make_number(1.0)); +} + +EvalResult fn_columns(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + EvalResult res = evaluate_ast(args[0].get(), ctx); + if (res.is_ref) { + if (res.ranges.size() != 1) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_number(static_cast(res.ranges[0].col_count()))); + } + if (res.value.is_error()) return EvalResult::from_value(res.value); + if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + return EvalResult::from_value(Value::make_number(static_cast(arr ? arr->cols : 0))); + } + return EvalResult::from_value(Value::make_number(1.0)); +} + +EvalResult fn_filter(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + const Array2D& arr = std::get(arr_var); + + auto inc_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb); + if (std::holds_alternative(inc_var)) return err_res(std::get(inc_var)); + const Array2D& inc = std::get(inc_var); + + auto eval_include_flag = [](const Value& v, ErrorCode& err_out) -> std::optional { + if (v.is_error()) { err_out = v.as_error(); return std::nullopt; } + if (v.is_empty()) return false; + if (v.is_bool()) return v.as_bool(); + if (v.is_number()) return v.as_number() != 0.0; + err_out = ErrorCode::Value; + return std::nullopt; + }; + + // Row filtering: include is (rows x 1) + if (inc.cols == 1 && inc.rows == arr.rows) { + std::vector kept_rows; + for (int r = 0; r < arr.rows; ++r) { + ErrorCode err = ErrorCode::Value; + auto flag = eval_include_flag(inc.at(r, 0), err); + if (!flag) return err_res(err); + if (*flag) kept_rows.push_back(r); + } + if (kept_rows.empty()) { + if (args.size() == 3) return evaluate_ast(args[2].get(), ctx); + return err_res(ErrorCode::NA); + } + auto out = std::make_shared(static_cast(kept_rows.size()), arr.cols); + for (size_t i = 0; i < kept_rows.size(); ++i) { + for (int c = 0; c < arr.cols; ++c) { + out->at(static_cast(i), c) = arr.at(kept_rows[i], c); + } + } + if (out->rows == 1 && out->cols == 1) return EvalResult::from_value(out->at(0, 0)); + return EvalResult::from_value(Value::make_array(std::move(out))); + } + + // Column filtering: include is (1 x cols) + if (inc.rows == 1 && inc.cols == arr.cols) { + std::vector kept_cols; + for (int c = 0; c < arr.cols; ++c) { + ErrorCode err = ErrorCode::Value; + auto flag = eval_include_flag(inc.at(0, c), err); + if (!flag) return err_res(err); + if (*flag) kept_cols.push_back(c); + } + if (kept_cols.empty()) { + if (args.size() == 3) return evaluate_ast(args[2].get(), ctx); + return err_res(ErrorCode::NA); + } + auto out = std::make_shared(arr.rows, static_cast(kept_cols.size())); + for (int r = 0; r < arr.rows; ++r) { + for (size_t j = 0; j < kept_cols.size(); ++j) { + out->at(r, static_cast(j)) = arr.at(r, kept_cols[j]); + } + } + if (out->rows == 1 && out->cols == 1) return EvalResult::from_value(out->at(0, 0)); + return EvalResult::from_value(Value::make_array(std::move(out))); + } + + return err_res(ErrorCode::Value); +} + +EvalResult fn_index(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + EvalResult arr_res = evaluate_ast(args[0].get(), ctx); + ErrorCode err = ErrorCode::Value; + auto r_d = eval_number_arg(args[1], ctx, err); + if (!r_d) return err_res(err); + int row_num = static_cast(std::trunc(*r_d)); + int col_num = -1; + if (args.size() == 3) { + auto c_d = eval_number_arg(args[2], ctx, err); + if (!c_d) return err_res(err); + col_num = static_cast(std::trunc(*c_d)); + } + + if (arr_res.is_ref) { + if (arr_res.ranges.size() != 1) return err_res(ErrorCode::Ref); + const CellRange& rng = arr_res.ranges[0]; + int rc = rng.row_count(); + int cc = rng.col_count(); + if (col_num < 0) { + if (rc == 1) { + col_num = row_num; + row_num = 1; + } else if (cc == 1) { + col_num = 1; + } else { + col_num = 0; + } + } + if (row_num < 0 || col_num < 0 || row_num > rc || col_num > cc) { + return err_res(ErrorCode::Ref); + } + if (row_num == 0 && col_num == 0) return arr_res; + if (row_num == 0) { + return EvalResult::from_range( + CellRange{rng.sheet, rng.r1, rng.c1 + col_num - 1, rng.r2, rng.c1 + col_num - 1}); + } + if (col_num == 0) { + return EvalResult::from_range( + CellRange{rng.sheet, rng.r1 + row_num - 1, rng.c1, rng.r1 + row_num - 1, rng.c2}); + } + return EvalResult::from_range(CellRange{ + rng.sheet, rng.r1 + row_num - 1, rng.c1 + col_num - 1, + rng.r1 + row_num - 1, rng.c1 + col_num - 1}); + } + + auto arr_var = result_to_array2d(arr_res, *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + const Array2D& arr = std::get(arr_var); + if (col_num < 0) { + if (arr.rows == 1) { + col_num = row_num; + row_num = 1; + } else if (arr.cols == 1) { + col_num = 1; + } else { + col_num = 0; + } + } + if (row_num < 0 || col_num < 0 || row_num > arr.rows || col_num > arr.cols) { + return err_res(ErrorCode::Ref); + } + if (row_num == 0 && col_num == 0) { + return EvalResult::from_value(Value::make_array(std::make_shared(arr))); + } + if (row_num == 0) { + auto out = std::make_shared(arr.rows, 1); + for (int r = 0; r < arr.rows; ++r) out->at(r, 0) = arr.at(r, col_num - 1); + return EvalResult::from_value(out->rows == 1 ? out->at(0, 0) : Value::make_array(std::move(out))); + } + if (col_num == 0) { + auto out = std::make_shared(1, arr.cols); + for (int c = 0; c < arr.cols; ++c) out->at(0, c) = arr.at(row_num - 1, c); + return EvalResult::from_value(out->cols == 1 ? out->at(0, 0) : Value::make_array(std::move(out))); + } + return EvalResult::from_value(arr.at(row_num - 1, col_num - 1)); +} + +EvalResult fn_match(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + Value key = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (key.is_error()) return EvalResult::from_value(key); + + auto arr_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + const Array2D& arr = std::get(arr_var); + if (arr.rows != 1 && arr.cols != 1) return err_res(ErrorCode::NA); + + int match_type = 1; + if (args.size() == 3) { + ErrorCode err = ErrorCode::Value; + auto mt = eval_number_arg(args[2], ctx, err); + if (!mt) return err_res(err); + match_type = static_cast(std::trunc(*mt)); + } + + int n = static_cast(arr.data.size()); + if (match_type == 0) { + for (int i = 0; i < n; ++i) { + if (values_equal_for_lookup(arr.data[static_cast(i)], key)) { + return EvalResult::from_value(Value::make_number(static_cast(i + 1))); + } + } + return err_res(ErrorCode::NA); + } + + if (match_type > 0) { + int best = -1; + for (int i = 0; i < n; ++i) { + const Value& elem = arr.data[static_cast(i)]; + if (!same_lookup_type(elem, key)) continue; + auto cmp = compare_values(elem, key); + if (!std::holds_alternative(cmp)) continue; + int c = std::get(cmp); + if (c <= 0) best = i; + else break; + } + if (best < 0) return err_res(ErrorCode::NA); + return EvalResult::from_value(Value::make_number(static_cast(best + 1))); + } + + // match_type < 0: descending, smallest >= key + int best = -1; + for (int i = 0; i < n; ++i) { + const Value& elem = arr.data[static_cast(i)]; + if (!same_lookup_type(elem, key)) continue; + auto cmp = compare_values(elem, key); + if (!std::holds_alternative(cmp)) continue; + int c = std::get(cmp); + if (c >= 0) best = i; + else break; + } + if (best < 0) return err_res(ErrorCode::NA); + return EvalResult::from_value(Value::make_number(static_cast(best + 1))); +} + +EvalResult fn_vh_lookup(const std::vector>& args, + const EvalContext& ctx, + bool vertical) { + if (args.size() < 3 || args.size() > 4) return err_res(ErrorCode::Value); + Value key = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (key.is_error()) return EvalResult::from_value(key); + + auto tbl_var = result_to_array2d(evaluate_ast(args[1].get(), ctx), *ctx.wb); + if (std::holds_alternative(tbl_var)) return err_res(std::get(tbl_var)); + const Array2D& tbl = std::get(tbl_var); + + ErrorCode err = ErrorCode::Value; + auto idx_d = eval_number_arg(args[2], ctx, err); + if (!idx_d) return err_res(err); + int idx = static_cast(std::trunc(*idx_d)); + if (idx < 1) return err_res(ErrorCode::Value); + int max_idx = vertical ? tbl.cols : tbl.rows; + if (idx > max_idx) return err_res(ErrorCode::Ref); + + bool range_lookup = true; + if (args.size() == 4) { + auto rl = eval_bool_arg(args[3], ctx, err); + if (!rl) return err_res(err); + range_lookup = *rl; + } + + int len = vertical ? tbl.rows : tbl.cols; + int found = -1; + if (!range_lookup) { + for (int i = 0; i < len; ++i) { + const Value& elem = vertical ? tbl.at(i, 0) : tbl.at(0, i); + if (values_equal_for_lookup(elem, key)) { + found = i; + break; + } + } + } else { + for (int i = 0; i < len; ++i) { + const Value& elem = vertical ? tbl.at(i, 0) : tbl.at(0, i); + if (!same_lookup_type(elem, key)) continue; + auto cmp = compare_values(elem, key); + if (!std::holds_alternative(cmp)) continue; + int c = std::get(cmp); + if (c <= 0) found = i; + else break; + } + } + + if (found < 0) return err_res(ErrorCode::NA); + Value out = vertical ? tbl.at(found, idx - 1) : tbl.at(idx - 1, found); + return EvalResult::from_value(out.is_empty() ? Value::make_number(0.0) : out); +} + +EvalResult fn_vlookup(const std::vector>& a, const EvalContext& c) { + return fn_vh_lookup(a, c, true); +} +EvalResult fn_hlookup(const std::vector>& a, const EvalContext& c) { + return fn_vh_lookup(a, c, false); +} + +} // namespace + +void register_lookup_functions(FunctionRegistry& reg) { + reg.register_fn("CHOOSE", fn_choose); + reg.register_fn("COLUMNS", fn_columns); + reg.register_fn("FILTER", fn_filter); + reg.register_fn("HLOOKUP", fn_hlookup); + reg.register_fn("INDEX", fn_index); + reg.register_fn("MATCH", fn_match); + reg.register_fn("ROWS", fn_rows); + reg.register_fn("VLOOKUP", fn_vlookup); +} + +} // namespace htab diff --git a/engine/functions/math_trig.cpp b/engine/functions/math_trig.cpp new file mode 100644 index 0000000..57921f6 --- /dev/null +++ b/engine/functions/math_trig.cpp @@ -0,0 +1,324 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +constexpr double kPi = 3.14159265358979323846; + +template +EvalResult unary_math(const std::vector>& args, + const EvalContext& ctx, + UnaryMathFn&& fn) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto num = eval_number_arg(args[0], ctx, err); + if (!num) return err_res(err); + return EvalResult::from_value(fn(*num)); +} + +EvalResult fn_abs(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::fabs(x)); }); +} +EvalResult fn_acos(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x < -1.0 || x > 1.0) return Value::make_error(ErrorCode::Num); + return Value::make_checked_number(std::acos(x)); + }); +} +EvalResult fn_asin(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x < -1.0 || x > 1.0) return Value::make_error(ErrorCode::Num); + return Value::make_checked_number(std::asin(x)); + }); +} +EvalResult fn_atan(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::atan(x)); }); +} +EvalResult fn_atan2(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto x = eval_number_arg(args[0], ctx, err); + if (!x) return err_res(err); + auto y = eval_number_arg(args[1], ctx, err); + if (!y) return err_res(err); + if (*x == 0.0 && *y == 0.0) return err_res(ErrorCode::Div0); + return EvalResult::from_value(Value::make_checked_number(std::atan2(*y, *x))); +} +EvalResult fn_cos(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::cos(x)); }); +} +EvalResult fn_degrees(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(x * 180.0 / kPi); }); +} +EvalResult fn_exp(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::exp(x)); }); +} +EvalResult fn_fact(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x < 0.0) return Value::make_error(ErrorCode::Num); + int n = static_cast(std::trunc(x)); + if (n > 170) return Value::make_error(ErrorCode::Num); + double res = 1.0; + for (int i = 2; i <= n; ++i) res *= static_cast(i); + return Value::make_checked_number(res); + }); +} +EvalResult fn_int(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::floor(x)); }); +} +EvalResult fn_ln(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x <= 0.0) return Value::make_error(ErrorCode::Num); + return Value::make_checked_number(std::log(x)); + }); +} +EvalResult fn_log(const std::vector>& args, const EvalContext& ctx) { + if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto num = eval_number_arg(args[0], ctx, err); + if (!num) return err_res(err); + double base = 10.0; + if (args.size() == 2) { + auto b = eval_number_arg(args[1], ctx, err); + if (!b) return err_res(err); + base = *b; + } + if (*num <= 0.0 || base <= 0.0 || base == 1.0) return err_res(ErrorCode::Num); + return EvalResult::from_value(Value::make_checked_number(std::log(*num) / std::log(base))); +} +EvalResult fn_log10(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x <= 0.0) return Value::make_error(ErrorCode::Num); + return Value::make_checked_number(std::log10(x)); + }); +} +EvalResult fn_mod(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto n = eval_number_arg(args[0], ctx, err); + if (!n) return err_res(err); + auto d = eval_number_arg(args[1], ctx, err); + if (!d) return err_res(err); + if (*d == 0.0) return err_res(ErrorCode::Div0); + double res = *n - *d * std::floor(*n / *d); + return EvalResult::from_value(Value::make_checked_number(res)); +} +EvalResult fn_pi(const std::vector>& args, const EvalContext&) { + if (!args.empty()) return err_res(ErrorCode::Value); + return EvalResult::from_value(Value::make_number(kPi)); +} +EvalResult fn_power(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto x = eval_number_arg(args[0], ctx, err); + if (!x) return err_res(err); + auto y = eval_number_arg(args[1], ctx, err); + if (!y) return err_res(err); + if (*x == 0.0 && *y < 0.0) return err_res(ErrorCode::Div0); + return EvalResult::from_value(Value::make_checked_number(std::pow(*x, *y))); +} +EvalResult fn_product(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + double prod = 1.0; + for (double v : nums) prod *= v; + return EvalResult::from_value(Value::make_checked_number(prod)); +} +EvalResult fn_radians(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(x * kPi / 180.0); }); +} +EvalResult fn_rand(const std::vector>& args, const EvalContext&) { + if (!args.empty()) return err_res(ErrorCode::Value); + thread_local std::mt19937_64 rng{std::random_device{}()}; + thread_local std::uniform_real_distribution dist(0.0, 1.0); + return EvalResult::from_value(Value::make_number(dist(rng))); +} +EvalResult fn_round(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto num = eval_number_arg(args[0], ctx, err); + if (!num) return err_res(err); + auto dig = eval_number_arg(args[1], ctx, err); + if (!dig) return err_res(err); + int d = static_cast(std::trunc(*dig)); + double x = *num; + double res = 0.0; + if (d >= 0) { + double scale = std::pow(10.0, d); + double v = x * scale; + if (!std::isfinite(v)) return EvalResult::from_value(Value::make_checked_number(x)); + double r = (v >= 0.0) ? std::floor(v + 0.5) : -std::floor(-v + 0.5); + res = r / scale; + } else { + double scale = std::pow(10.0, -d); + double v = x / scale; + double r = (v >= 0.0) ? std::floor(v + 0.5) : -std::floor(-v + 0.5); + res = r * scale; + } + return EvalResult::from_value(Value::make_checked_number(res)); +} +EvalResult fn_sin(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::sin(x)); }); +} +EvalResult fn_sqrt(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { + if (x < 0.0) return Value::make_error(ErrorCode::Num); + return Value::make_checked_number(std::sqrt(x)); + }); +} +EvalResult fn_sum(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + double total = 0.0; + for (double v : nums) total += v; + return EvalResult::from_value(Value::make_checked_number(total)); +} +EvalResult fn_sumif(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + EvalResult cr_res = evaluate_ast(args[0].get(), ctx); + auto cr_var = result_to_array2d(cr_res, *ctx.wb); + if (std::holds_alternative(cr_var)) return err_res(std::get(cr_var)); + const Array2D& cr = std::get(cr_var); + + Value crit = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb); + if (crit.is_error()) return EvalResult::from_value(crit); + + Array2D sr; + if (args.size() == 3) { + EvalResult sr_res = evaluate_ast(args[2].get(), ctx); + if (sr_res.is_ref && sr_res.ranges.size() == 1) { + CellRange base = sr_res.ranges[0]; + sr = Array2D(cr.rows, cr.cols); + for (int r = 0; r < cr.rows; ++r) { + for (int c = 0; c < cr.cols; ++c) { + sr.at(r, c) = ctx.wb->get_scalar_value(base.sheet, base.r1 + r, base.c1 + c); + } + } + } else { + auto sr_var = result_to_array2d(sr_res, *ctx.wb); + if (std::holds_alternative(sr_var)) return err_res(std::get(sr_var)); + sr = std::move(std::get(sr_var)); + if (sr.rows != cr.rows || sr.cols != cr.cols) return err_res(ErrorCode::Value); + } + } else { + sr = cr; + } + + double total = 0.0; + for (int r = 0; r < cr.rows; ++r) { + for (int c = 0; c < cr.cols; ++c) { + if (matches_criteria(cr.at(r, c), crit)) { + const Value& sv = sr.at(r, c); + if (sv.is_number()) total += sv.as_number(); + } + } + } + return EvalResult::from_value(Value::make_checked_number(total)); +} +EvalResult fn_sumifs(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || (args.size() - 1) % 2 != 0) return err_res(ErrorCode::Value); + auto sr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (std::holds_alternative(sr_var)) return err_res(std::get(sr_var)); + const Array2D& sr = std::get(sr_var); + + struct Pair { Array2D range; Value crit; }; + std::vector pairs; + for (size_t i = 1; i < args.size(); i += 2) { + auto cr_var = result_to_array2d(evaluate_ast(args[i].get(), ctx), *ctx.wb); + if (std::holds_alternative(cr_var)) return err_res(std::get(cr_var)); + Array2D cr = std::move(std::get(cr_var)); + if (cr.rows != sr.rows || cr.cols != sr.cols) return err_res(ErrorCode::Value); + Value crit = deref_to_value(evaluate_ast(args[i + 1].get(), ctx), *ctx.wb); + if (crit.is_error()) return EvalResult::from_value(crit); + pairs.push_back({std::move(cr), std::move(crit)}); + } + + double total = 0.0; + for (int r = 0; r < sr.rows; ++r) { + for (int c = 0; c < sr.cols; ++c) { + bool ok = true; + for (const auto& p : pairs) { + if (!matches_criteria(p.range.at(r, c), p.crit)) { + ok = false; + break; + } + } + if (ok && sr.at(r, c).is_number()) { + total += sr.at(r, c).as_number(); + } + } + } + return EvalResult::from_value(Value::make_checked_number(total)); +} +EvalResult fn_tan(const std::vector>& a, const EvalContext& ctx) { + return unary_math(a, ctx, [](double x) { return Value::make_checked_number(std::tan(x)); }); +} +EvalResult fn_trunc(const std::vector>& args, const EvalContext& ctx) { + if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto num = eval_number_arg(args[0], ctx, err); + if (!num) return err_res(err); + int d = 0; + if (args.size() == 2) { + auto dig = eval_number_arg(args[1], ctx, err); + if (!dig) return err_res(err); + d = static_cast(std::trunc(*dig)); + } + double x = *num; + double res = 0.0; + if (d >= 0) { + double scale = std::pow(10.0, d); + double v = x * scale; + res = std::isfinite(v) ? (std::trunc(v) / scale) : x; + } else { + double scale = std::pow(10.0, -d); + res = std::trunc(x / scale) * scale; + } + return EvalResult::from_value(Value::make_checked_number(res)); +} + +} // namespace + +void register_math_trig_functions(FunctionRegistry& reg) { + reg.register_fn("ABS", fn_abs); + reg.register_fn("ACOS", fn_acos); + reg.register_fn("ASIN", fn_asin); + reg.register_fn("ATAN", fn_atan); + reg.register_fn("ATAN2", fn_atan2); + reg.register_fn("COS", fn_cos); + reg.register_fn("DEGREES", fn_degrees); + reg.register_fn("EXP", fn_exp); + reg.register_fn("FACT", fn_fact); + reg.register_fn("INT", fn_int); + reg.register_fn("LN", fn_ln); + reg.register_fn("LOG", fn_log); + reg.register_fn("LOG10", fn_log10); + reg.register_fn("MOD", fn_mod); + reg.register_fn("PI", fn_pi); + reg.register_fn("POWER", fn_power); + reg.register_fn("PRODUCT", fn_product); + reg.register_fn("RADIANS", fn_radians); + reg.register_fn("RAND", fn_rand); + reg.register_fn("ROUND", fn_round); + reg.register_fn("SIN", fn_sin); + reg.register_fn("SQRT", fn_sqrt); + reg.register_fn("SUM", fn_sum); + reg.register_fn("SUMIF", fn_sumif); + reg.register_fn("SUMIFS", fn_sumifs); + reg.register_fn("TAN", fn_tan); + reg.register_fn("TRUNC", fn_trunc); +} + +} // namespace htab diff --git a/engine/functions/registry.cpp b/engine/functions/registry.cpp new file mode 100644 index 0000000..6641fc9 --- /dev/null +++ b/engine/functions/registry.cpp @@ -0,0 +1,31 @@ +#include "engine/functions/registry.hpp" + +namespace htab { + +const FunctionRegistry& FunctionRegistry::instance() { + static const FunctionRegistry reg; + return reg; +} + +FunctionRegistry::FunctionRegistry() { + register_math_trig_functions(*this); + register_logical_functions(*this); + register_statistical_functions(*this); + register_lookup_functions(*this); + register_text_functions(*this); + register_datetime_functions(*this); + register_financial_functions(*this); + register_database_functions(*this); +} + +void FunctionRegistry::register_fn(std::string name, FunctionImpl fn) { + funcs_.emplace(std::move(name), std::move(fn)); +} + +const FunctionImpl* FunctionRegistry::find(std::string_view upper_name) const { + auto it = funcs_.find(std::string(upper_name)); + if (it == funcs_.end()) return nullptr; + return &it->second; +} + +} // namespace htab diff --git a/engine/functions/registry.hpp b/engine/functions/registry.hpp new file mode 100644 index 0000000..73b45cd --- /dev/null +++ b/engine/functions/registry.hpp @@ -0,0 +1,41 @@ +#pragma once + +#include "engine/evaluator.hpp" + +#include +#include +#include +#include +#include +#include + +namespace htab { + +using FunctionImpl = + std::function>& args, const EvalContext& ctx)>; + +class FunctionRegistry { + public: + static const FunctionRegistry& instance(); + + const FunctionImpl* find(std::string_view upper_name) const; + size_t registered_count() const { return funcs_.size(); } + + void register_fn(std::string name, FunctionImpl fn); + + private: + FunctionRegistry(); + + std::unordered_map funcs_; +}; + +void register_math_trig_functions(FunctionRegistry& reg); +void register_logical_functions(FunctionRegistry& reg); +void register_statistical_functions(FunctionRegistry& reg); +void register_lookup_functions(FunctionRegistry& reg); +void register_text_functions(FunctionRegistry& reg); +void register_datetime_functions(FunctionRegistry& reg); +void register_financial_functions(FunctionRegistry& reg); +void register_database_functions(FunctionRegistry& reg); + +} // namespace htab diff --git a/engine/functions/statistical.cpp b/engine/functions/statistical.cpp new file mode 100644 index 0000000..8eb5c5d --- /dev/null +++ b/engine/functions/statistical.cpp @@ -0,0 +1,222 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +double compute_variance(const std::vector& nums, bool sample) { + double sum = 0.0; + for (double v : nums) sum += v; + double mean = sum / static_cast(nums.size()); + double sq_sum = 0.0; + for (double v : nums) { + double d = v - mean; + sq_sum += d * d; + } + double denom = static_cast(sample ? (nums.size() - 1) : nums.size()); + return sq_sum / denom; +} + +EvalResult fn_average(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + if (nums.empty()) return err_res(ErrorCode::Div0); + double sum = 0.0; + for (double v : nums) sum += v; + return EvalResult::from_value(Value::make_checked_number(sum / static_cast(nums.size()))); +} + +EvalResult fn_count(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + size_t count = 0; + for (const auto& arg : args) { + EvalResult res = evaluate_ast(arg.get(), ctx); + if (res.is_ref) { + for (const auto& rng : res.ranges) { + for (int r = rng.r1; r <= rng.r2; ++r) { + for (int c = rng.c1; c <= rng.c2; ++c) { + Value v = ctx.wb->get_scalar_value(rng.sheet, r, c); + if (v.is_number()) ++count; + } + } + } + } else if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + if (arr) { + for (const auto& v : arr->data) { + if (v.is_number()) ++count; + } + } + } else if (!res.value.is_error() && !res.value.is_empty()) { + auto num = to_number(res.value); + if (std::holds_alternative(num)) ++count; + } + } + return EvalResult::from_value(Value::make_number(static_cast(count))); +} + +EvalResult fn_counta(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + size_t count = 0; + for (const auto& arg : args) { + EvalResult res = evaluate_ast(arg.get(), ctx); + if (res.is_ref) { + for (const auto& rng : res.ranges) { + for (int r = rng.r1; r <= rng.r2; ++r) { + for (int c = rng.c1; c <= rng.c2; ++c) { + Value v = ctx.wb->get_scalar_value(rng.sheet, r, c); + if (!v.is_empty()) ++count; + } + } + } + } else if (res.value.is_array()) { + const auto& arr = res.value.as_array(); + if (arr) { + for (const auto& v : arr->data) { + if (!v.is_empty()) ++count; + } + } + } else if (!res.value.is_empty()) { + ++count; + } + } + return EvalResult::from_value(Value::make_number(static_cast(count))); +} + +EvalResult fn_countblank(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + const Array2D& arr = std::get(arr_var); + size_t count = 0; + for (const auto& v : arr.data) { + if (v.is_empty() || (v.is_string() && v.as_string().empty())) { + ++count; + } + } + return EvalResult::from_value(Value::make_number(static_cast(count))); +} + +EvalResult fn_countif(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + auto arr_var = result_to_array2d(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + const Array2D& arr = std::get(arr_var); + Value crit = deref_to_value(evaluate_ast(args[1].get(), ctx), *ctx.wb); + if (crit.is_error()) return EvalResult::from_value(crit); + + size_t count = 0; + for (const auto& v : arr.data) { + if (matches_criteria(v, crit)) ++count; + } + return EvalResult::from_value(Value::make_number(static_cast(count))); +} + +EvalResult fn_countifs(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() % 2 != 0) return err_res(ErrorCode::Value); + struct Pair { Array2D range; Value crit; }; + std::vector pairs; + int rows = -1, cols = -1; + for (size_t i = 0; i < args.size(); i += 2) { + auto arr_var = result_to_array2d(evaluate_ast(args[i].get(), ctx), *ctx.wb); + if (std::holds_alternative(arr_var)) return err_res(std::get(arr_var)); + Array2D arr = std::move(std::get(arr_var)); + if (rows < 0) { + rows = arr.rows; + cols = arr.cols; + } else if (arr.rows != rows || arr.cols != cols) { + return err_res(ErrorCode::Value); + } + Value crit = deref_to_value(evaluate_ast(args[i + 1].get(), ctx), *ctx.wb); + if (crit.is_error()) return EvalResult::from_value(crit); + pairs.push_back({std::move(arr), std::move(crit)}); + } + + size_t count = 0; + for (int r = 0; r < rows; ++r) { + for (int c = 0; c < cols; ++c) { + bool ok = true; + for (const auto& p : pairs) { + if (!matches_criteria(p.range.at(r, c), p.crit)) { + ok = false; + break; + } + } + if (ok) ++count; + } + } + return EvalResult::from_value(Value::make_number(static_cast(count))); +} + +EvalResult fn_max(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + double m = *std::max_element(nums.begin(), nums.end()); + return EvalResult::from_value(Value::make_number(m)); +} + +EvalResult fn_min(const std::vector>& args, const EvalContext& ctx) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + if (nums.empty()) return EvalResult::from_value(Value::make_number(0.0)); + double m = *std::min_element(nums.begin(), nums.end()); + return EvalResult::from_value(Value::make_number(m)); +} + +EvalResult fn_var_impl(const std::vector>& args, + const EvalContext& ctx, + bool sample, + bool take_sqrt) { + if (args.empty()) return err_res(ErrorCode::Value); + std::vector nums; + if (auto err = collect_numeric_args(args, ctx, nums)) return err_res(*err); + if (nums.size() < (sample ? 2U : 1U)) return err_res(ErrorCode::Div0); + double v = compute_variance(nums, sample); + if (take_sqrt) v = std::sqrt(v); + return EvalResult::from_value(Value::make_checked_number(v)); +} + +EvalResult fn_stdev(const std::vector>& a, const EvalContext& c) { + return fn_var_impl(a, c, true, true); +} +EvalResult fn_stdevp(const std::vector>& a, const EvalContext& c) { + return fn_var_impl(a, c, false, true); +} +EvalResult fn_var(const std::vector>& a, const EvalContext& c) { + return fn_var_impl(a, c, true, false); +} +EvalResult fn_varp(const std::vector>& a, const EvalContext& c) { + return fn_var_impl(a, c, false, false); +} + +} // namespace + +void register_statistical_functions(FunctionRegistry& reg) { + reg.register_fn("AVERAGE", fn_average); + reg.register_fn("COUNT", fn_count); + reg.register_fn("COUNTA", fn_counta); + reg.register_fn("COUNTBLANK", fn_countblank); + reg.register_fn("COUNTIF", fn_countif); + reg.register_fn("COUNTIFS", fn_countifs); + reg.register_fn("MAX", fn_max); + reg.register_fn("MIN", fn_min); + reg.register_fn("STDEV", fn_stdev); + reg.register_fn("STDEVP", fn_stdevp); + reg.register_fn("VAR", fn_var); + reg.register_fn("VARP", fn_varp); +} + +} // namespace htab diff --git a/engine/functions/text.cpp b/engine/functions/text.cpp new file mode 100644 index 0000000..caab0a9 --- /dev/null +++ b/engine/functions/text.cpp @@ -0,0 +1,293 @@ +#include "engine/functions/helpers.hpp" +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include +#include + +namespace htab { + +using namespace htab::fn; + +namespace { + +EvalResult fn_exact(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto a = eval_string_arg(args[0], ctx, err); + if (!a) return err_res(err); + auto b = eval_string_arg(args[1], ctx, err); + if (!b) return err_res(err); + return EvalResult::from_value(Value::make_bool(*a == *b)); +} + +EvalResult fn_len(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + return EvalResult::from_value( + Value::make_number(static_cast(utf8_codepoints(*s).size()))); +} + +EvalResult fn_lower(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + return EvalResult::from_value(Value::make_string(to_lower_ascii(*s))); +} + +EvalResult fn_upper(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + return EvalResult::from_value(Value::make_string(to_upper_ascii(*s))); +} + +EvalResult fn_proper(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + std::string out = *s; + bool start_word = true; + for (char& ch : out) { + unsigned char uc = static_cast(ch); + if (std::isalpha(uc)) { + ch = static_cast(start_word ? std::toupper(uc) : std::tolower(uc)); + start_word = false; + } else { + start_word = true; + } + } + return EvalResult::from_value(Value::make_string(std::move(out))); +} + +EvalResult fn_trim(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + std::string out; + out.reserve(s->size()); + bool in_space = true; + for (char ch : *s) { + if (ch == ' ') { + if (!in_space) { + out.push_back(' '); + in_space = true; + } + } else { + out.push_back(ch); + in_space = false; + } + } + if (!out.empty() && out.back() == ' ') out.pop_back(); + return EvalResult::from_value(Value::make_string(std::move(out))); +} + +EvalResult fn_left(const std::vector>& args, const EvalContext& ctx) { + if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + int count = 1; + if (args.size() == 2) { + auto n = eval_number_arg(args[1], ctx, err); + if (!n) return err_res(err); + count = static_cast(std::trunc(*n)); + } + if (count < 0) return err_res(ErrorCode::Value); + auto cps = utf8_codepoints(*s); + return EvalResult::from_value(Value::make_string(utf8_join(cps, 0, static_cast(count)))); +} + +EvalResult fn_right(const std::vector>& args, const EvalContext& ctx) { + if (args.empty() || args.size() > 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + int count = 1; + if (args.size() == 2) { + auto n = eval_number_arg(args[1], ctx, err); + if (!n) return err_res(err); + count = static_cast(std::trunc(*n)); + } + if (count < 0) return err_res(ErrorCode::Value); + auto cps = utf8_codepoints(*s); + size_t c = static_cast(count); + size_t start = (c >= cps.size()) ? 0 : (cps.size() - c); + return EvalResult::from_value(Value::make_string(utf8_join(cps, start, c))); +} + +EvalResult fn_mid(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto s = eval_string_arg(args[0], ctx, err); + if (!s) return err_res(err); + auto st = eval_number_arg(args[1], ctx, err); + if (!st) return err_res(err); + auto nc = eval_number_arg(args[2], ctx, err); + if (!nc) return err_res(err); + int start1 = static_cast(std::trunc(*st)); + int count = static_cast(std::trunc(*nc)); + if (start1 < 1 || count < 0) return err_res(ErrorCode::Value); + auto cps = utf8_codepoints(*s); + size_t start0 = static_cast(start1 - 1); + if (start0 >= cps.size()) return EvalResult::from_value(Value::make_string("")); + return EvalResult::from_value( + Value::make_string(utf8_join(cps, start0, static_cast(count)))); +} + +EvalResult fn_find(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 2 || args.size() > 3) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto needle = eval_string_arg(args[0], ctx, err); + if (!needle) return err_res(err); + auto hay = eval_string_arg(args[1], ctx, err); + if (!hay) return err_res(err); + int start1 = 1; + if (args.size() == 3) { + auto sn = eval_number_arg(args[2], ctx, err); + if (!sn) return err_res(err); + start1 = static_cast(std::trunc(*sn)); + } + auto hay_cps = utf8_codepoints(*hay); + auto ned_cps = utf8_codepoints(*needle); + if (start1 < 1 || static_cast(start1) > hay_cps.size() + 1) { + return err_res(ErrorCode::Value); + } + if (ned_cps.empty()) { + return EvalResult::from_value(Value::make_number(static_cast(start1))); + } + if (ned_cps.size() > hay_cps.size()) return err_res(ErrorCode::Value); + for (size_t i = static_cast(start1 - 1); i + ned_cps.size() <= hay_cps.size(); ++i) { + bool match = true; + for (size_t j = 0; j < ned_cps.size(); ++j) { + if (hay_cps[i + j] != ned_cps[j]) { + match = false; + break; + } + } + if (match) { + return EvalResult::from_value(Value::make_number(static_cast(i + 1))); + } + } + return err_res(ErrorCode::Value); +} + +EvalResult fn_replace(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 4) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto old_t = eval_string_arg(args[0], ctx, err); + if (!old_t) return err_res(err); + auto st = eval_number_arg(args[1], ctx, err); + if (!st) return err_res(err); + auto nc = eval_number_arg(args[2], ctx, err); + if (!nc) return err_res(err); + auto new_t = eval_string_arg(args[3], ctx, err); + if (!new_t) return err_res(err); + + int start1 = static_cast(std::trunc(*st)); + int count = static_cast(std::trunc(*nc)); + if (start1 < 1 || count < 0) return err_res(ErrorCode::Value); + + auto cps = utf8_codepoints(*old_t); + size_t s0 = std::min(static_cast(start1 - 1), cps.size()); + size_t e0 = std::min(s0 + static_cast(count), cps.size()); + + std::string out = utf8_join(cps, 0, s0); + out += *new_t; + out += utf8_join(cps, e0, cps.size() - e0); + return EvalResult::from_value(Value::make_string(std::move(out))); +} + +EvalResult fn_rept(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 2) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto t = eval_string_arg(args[0], ctx, err); + if (!t) return err_res(err); + auto n = eval_number_arg(args[1], ctx, err); + if (!n) return err_res(err); + int times = static_cast(std::trunc(*n)); + if (times < 0) return err_res(ErrorCode::Value); + if (times == 0 || t->empty()) return EvalResult::from_value(Value::make_string("")); + if (t->size() * static_cast(times) > 32767) return err_res(ErrorCode::Value); + + std::string out; + out.reserve(t->size() * static_cast(times)); + for (int i = 0; i < times; ++i) out += *t; + return EvalResult::from_value(Value::make_string(std::move(out))); +} + +EvalResult fn_substitute(const std::vector>& args, const EvalContext& ctx) { + if (args.size() < 3 || args.size() > 4) return err_res(ErrorCode::Value); + ErrorCode err = ErrorCode::Value; + auto text = eval_string_arg(args[0], ctx, err); + if (!text) return err_res(err); + auto old_t = eval_string_arg(args[1], ctx, err); + if (!old_t) return err_res(err); + auto new_t = eval_string_arg(args[2], ctx, err); + if (!new_t) return err_res(err); + + int instance_num = 0; + if (args.size() == 4) { + auto inst = eval_number_arg(args[3], ctx, err); + if (!inst) return err_res(err); + instance_num = static_cast(std::trunc(*inst)); + if (instance_num < 1) return err_res(ErrorCode::Value); + } + if (old_t->empty()) return EvalResult::from_value(Value::make_string(*text)); + + std::string out; + size_t pos = 0; + int seen = 0; + while (pos < text->size()) { + size_t found = text->find(*old_t, pos); + if (found == std::string::npos) { + out.append(*text, pos, text->size() - pos); + break; + } + ++seen; + out.append(*text, pos, found - pos); + if (instance_num == 0 || seen == instance_num) { + out.append(*new_t); + } else { + out.append(*old_t); + } + pos = found + old_t->size(); + } + return EvalResult::from_value(Value::make_string(std::move(out))); +} + +EvalResult fn_t(const std::vector>& args, const EvalContext& ctx) { + if (args.size() != 1) return err_res(ErrorCode::Value); + Value v = deref_to_value(evaluate_ast(args[0].get(), ctx), *ctx.wb); + if (v.is_error()) return EvalResult::from_value(v); + if (v.is_string()) return EvalResult::from_value(v); + return EvalResult::from_value(Value::make_string("")); +} + +} // namespace + +void register_text_functions(FunctionRegistry& reg) { + reg.register_fn("EXACT", fn_exact); + reg.register_fn("FIND", fn_find); + reg.register_fn("LEFT", fn_left); + reg.register_fn("LEN", fn_len); + reg.register_fn("LOWER", fn_lower); + reg.register_fn("MID", fn_mid); + reg.register_fn("PROPER", fn_proper); + reg.register_fn("REPLACE", fn_replace); + reg.register_fn("REPT", fn_rept); + reg.register_fn("RIGHT", fn_right); + reg.register_fn("SUBSTITUTE", fn_substitute); + reg.register_fn("T", fn_t); + reg.register_fn("TRIM", fn_trim); + reg.register_fn("UPPER", fn_upper); +} + +} // namespace htab diff --git a/engine/io_csv.cpp b/engine/io_csv.cpp new file mode 100644 index 0000000..7c35bc0 --- /dev/null +++ b/engine/io_csv.cpp @@ -0,0 +1,213 @@ +#include "engine/io_csv.hpp" + +#include +#include +#include + +namespace htab { + +namespace { + +bool parse_rfc4180_csv(std::string_view text, + std::vector>& rows_out, + std::string* err) { + rows_out.clear(); + if (text.size() >= 3 && + static_cast(text[0]) == 0xEF && + static_cast(text[1]) == 0xBB && + static_cast(text[2]) == 0xBF) { + text.remove_prefix(3); + } + if (text.empty()) return true; + + size_t i = 0; + std::vector current_row; + + while (i < text.size()) { + std::string field; + if (text[i] == '"') { + ++i; + bool closed = false; + while (i < text.size()) { + if (text[i] == '"') { + if (i + 1 < text.size() && text[i + 1] == '"') { + field.push_back('"'); + i += 2; + } else { + ++i; + closed = true; + break; + } + } else { + field.push_back(text[i++]); + } + } + if (!closed) { + if (err) *err = "Unterminated quoted CSV field"; + return false; + } + if (i < text.size() && text[i] != ',' && text[i] != '\r' && text[i] != '\n') { + if (err) *err = "Unexpected character after closing CSV quote"; + return false; + } + } else { + while (i < text.size() && text[i] != ',' && text[i] != '\r' && text[i] != '\n') { + if (text[i] == '"') { + if (err) *err = "Unexpected quote inside unquoted CSV field"; + return false; + } + field.push_back(text[i++]); + } + } + + current_row.push_back(std::move(field)); + + if (i >= text.size()) { + rows_out.push_back(std::move(current_row)); + current_row.clear(); + break; + } + + if (text[i] == ',') { + ++i; + if (i >= text.size()) { + // Trailing comma at EOF -> final empty field + current_row.emplace_back(""); + rows_out.push_back(std::move(current_row)); + current_row.clear(); + break; + } + continue; + } + + // End of line (\r\n, \n, or \r) + if (text[i] == '\r') { + ++i; + if (i < text.size() && text[i] == '\n') ++i; + } else if (text[i] == '\n') { + ++i; + } + rows_out.push_back(std::move(current_row)); + current_row.clear(); + } + + return true; +} + +std::string escape_csv_field(const std::string& s) { + bool needs_quote = false; + for (char ch : s) { + if (ch == ',' || ch == '"' || ch == '\n' || ch == '\r') { + needs_quote = true; + break; + } + } + if (!needs_quote) return s; + std::string out; + out.reserve(s.size() + 4); + out.push_back('"'); + for (char ch : s) { + if (ch == '"') out += "\"\""; + else out.push_back(ch); + } + out.push_back('"'); + return out; +} + +} // namespace + +bool import_csv_string(Workbook& wb, + int sheet_idx, + std::string_view csv_text, + std::string* err) { + if (sheet_idx < 0 || sheet_idx >= wb.sheet_count()) { + if (err) *err = "Invalid sheet index"; + return false; + } + std::vector> rows; + if (!parse_rfc4180_csv(csv_text, rows, err)) { + return false; + } + std::unordered_map new_cells; + for (size_t r = 0; r < rows.size(); ++r) { + if (r >= static_cast(kMaxRows)) break; + for (size_t c = 0; c < rows[r].size(); ++c) { + if (c >= static_cast(kMaxCols)) break; + if (rows[r][c].empty()) continue; + Cell cell; + cell.raw_input = rows[r][c]; + new_cells.emplace(CellKey{static_cast(r), static_cast(c)}, std::move(cell)); + } + } + wb.replace_sheet_cells(sheet_idx, std::move(new_cells)); + return true; +} + +bool import_csv_file(Workbook& wb, + int sheet_idx, + const std::string& path, + std::string* err) { + std::ifstream in(path, std::ios::binary); + if (!in) { + if (err) *err = "Cannot open CSV file for reading: " + path; + return false; + } + std::ostringstream oss; + oss << in.rdbuf(); + return import_csv_string(wb, sheet_idx, oss.str(), err); +} + +std::string export_csv_string(const Workbook& wb, + int sheet_idx, + bool export_formulas) { + auto bounds = wb.get_used_bounds(sheet_idx); + if (!bounds) return ""; + + std::string out; + for (int r = 0; r <= bounds->r2; ++r) { + int row_last_col = -1; + std::vector row_vals(static_cast(bounds->c2 + 1)); + for (int c = 0; c <= bounds->c2; ++c) { + std::string val; + if (export_formulas) { + const Cell* cell = wb.get_cell(sheet_idx, r, c); + if (cell && !cell->raw_input.empty()) { + val = cell->raw_input; + } + } else { + val = wb.get_formatted_value(sheet_idx, r, c); + } + if (!val.empty()) row_last_col = c; + row_vals[static_cast(c)] = std::move(val); + } + + int limit = (row_last_col >= 0) ? row_last_col : -1; + for (int c = 0; c <= limit; ++c) { + if (c > 0) out.push_back(','); + out += escape_csv_field(row_vals[static_cast(c)]); + } + out += "\r\n"; + } + return out; +} + +bool export_csv_file(const Workbook& wb, + int sheet_idx, + const std::string& path, + bool export_formulas, + std::string* err) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) { + if (err) *err = "Cannot open CSV file for writing: " + path; + return false; + } + std::string data = export_csv_string(wb, sheet_idx, export_formulas); + out.write(data.data(), static_cast(data.size())); + if (!out) { + if (err) *err = "Failed writing CSV file: " + path; + return false; + } + return true; +} + +} // namespace htab diff --git a/engine/io_csv.hpp b/engine/io_csv.hpp new file mode 100644 index 0000000..aed3b5b --- /dev/null +++ b/engine/io_csv.hpp @@ -0,0 +1,30 @@ +#pragma once + +#include "engine/workbook.hpp" + +#include +#include + +namespace htab { + +bool import_csv_string(Workbook& wb, + int sheet_idx, + std::string_view csv_text, + std::string* err = nullptr); + +bool import_csv_file(Workbook& wb, + int sheet_idx, + const std::string& path, + std::string* err = nullptr); + +std::string export_csv_string(const Workbook& wb, + int sheet_idx, + bool export_formulas = false); + +bool export_csv_file(const Workbook& wb, + int sheet_idx, + const std::string& path, + bool export_formulas = false, + std::string* err = nullptr); + +} // namespace htab diff --git a/engine/io_native.cpp b/engine/io_native.cpp new file mode 100644 index 0000000..9677d17 --- /dev/null +++ b/engine/io_native.cpp @@ -0,0 +1,530 @@ +#include "engine/io_native.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace htab { + +namespace { + +void append_json_string(std::string& out, const std::string& s) { + out.push_back('"'); + for (unsigned char ch : s) { + switch (ch) { + case '"': out += "\\\""; break; + case '\\': out += "\\\\"; break; + case '\b': out += "\\b"; break; + case '\f': out += "\\f"; break; + case '\n': out += "\\n"; break; + case '\r': out += "\\r"; break; + case '\t': out += "\\t"; break; + default: + if (ch < 0x20) { + char buf[8]; + std::snprintf(buf, sizeof(buf), "\\u%04x", static_cast(ch)); + out += buf; + } else { + out.push_back(static_cast(ch)); + } + break; + } + } + out.push_back('"'); +} + +struct JsonValue; +using JsonArray = std::vector; +using JsonObject = std::vector>; + +struct JsonValue { + std::variant data; + + bool is_null() const { return std::holds_alternative(data); } + bool is_bool() const { return std::holds_alternative(data); } + bool is_number() const { return std::holds_alternative(data); } + bool is_string() const { return std::holds_alternative(data); } + bool is_array() const { return std::holds_alternative(data); } + bool is_object() const { return std::holds_alternative(data); } + + const JsonValue* find(std::string_view key) const { + if (!is_object()) return nullptr; + for (const auto& [k, v] : std::get(data)) { + if (k == key) return &v; + } + return nullptr; + } +}; + +class JsonParser { + public: + explicit JsonParser(std::string_view src) : src_(src) {} + + bool parse(JsonValue& out, std::string& err) { + skip_ws(); + if (!parse_value(out, 0, err)) return false; + skip_ws(); + if (pos_ != src_.size()) { + err = "Unexpected trailing data in JSON"; + return false; + } + return true; + } + + private: + void skip_ws() { + while (pos_ < src_.size() && + (src_[pos_] == ' ' || src_[pos_] == '\t' || + src_[pos_] == '\r' || src_[pos_] == '\n')) { + ++pos_; + } + } + + static void append_utf8(std::string& out, uint32_t cp) { + if (cp <= 0x7F) { + out.push_back(static_cast(cp)); + } else if (cp <= 0x7FF) { + out.push_back(static_cast(0xC0 | (cp >> 6))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } else if (cp <= 0xFFFF) { + out.push_back(static_cast(0xE0 | (cp >> 12))); + out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } else { + out.push_back(static_cast(0xF0 | (cp >> 18))); + out.push_back(static_cast(0x80 | ((cp >> 12) & 0x3F))); + out.push_back(static_cast(0x80 | ((cp >> 6) & 0x3F))); + out.push_back(static_cast(0x80 | (cp & 0x3F))); + } + } + + bool parse_hex4(uint32_t& out) { + if (pos_ + 4 > src_.size()) return false; + uint32_t v = 0; + for (int i = 0; i < 4; ++i) { + char ch = src_[pos_++]; + v <<= 4; + if (ch >= '0' && ch <= '9') v |= static_cast(ch - '0'); + else if (ch >= 'a' && ch <= 'f') v |= static_cast(ch - 'a' + 10); + else if (ch >= 'A' && ch <= 'F') v |= static_cast(ch - 'A' + 10); + else return false; + } + out = v; + return true; + } + + bool parse_string(std::string& out, std::string& err) { + if (pos_ >= src_.size() || src_[pos_] != '"') { + err = "Expected '\"'"; + return false; + } + ++pos_; + out.clear(); + while (pos_ < src_.size()) { + char ch = src_[pos_++]; + if (ch == '"') return true; + if (static_cast(ch) < 0x20) { + err = "Control character in JSON string"; + return false; + } + if (ch == '\\') { + if (pos_ >= src_.size()) { + err = "Unterminated escape in JSON string"; + return false; + } + char esc = src_[pos_++]; + switch (esc) { + case '"': out.push_back('"'); break; + case '\\': out.push_back('\\'); break; + case '/': out.push_back('/'); break; + case 'b': out.push_back('\b'); break; + case 'f': out.push_back('\f'); break; + case 'n': out.push_back('\n'); break; + case 'r': out.push_back('\r'); break; + case 't': out.push_back('\t'); break; + case 'u': { + uint32_t cp = 0; + if (!parse_hex4(cp)) { + err = "Invalid \\u escape in JSON"; + return false; + } + if (cp >= 0xD800 && cp <= 0xDBFF && pos_ + 6 <= src_.size() && + src_[pos_] == '\\' && src_[pos_ + 1] == 'u') { + pos_ += 2; + uint32_t low = 0; + if (!parse_hex4(low) || low < 0xDC00 || low > 0xDFFF) { + err = "Invalid UTF-16 surrogate pair in JSON"; + return false; + } + cp = 0x10000 + (((cp - 0xD800) << 10) | (low - 0xDC00)); + } + append_utf8(out, cp); + break; + } + default: + err = "Unknown escape in JSON string"; + return false; + } + } else { + out.push_back(ch); + } + } + err = "Unterminated JSON string"; + return false; + } + + bool parse_number(double& out, std::string& err) { + size_t start = pos_; + if (pos_ < src_.size() && src_[pos_] == '-') ++pos_; + if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { + err = "Invalid JSON number"; + return false; + } + if (src_[pos_] == '0') { + ++pos_; + } else { + while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; + } + if (pos_ < src_.size() && src_[pos_] == '.') { + ++pos_; + if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { + err = "Invalid JSON fraction"; + return false; + } + while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; + } + if (pos_ < src_.size() && (src_[pos_] == 'e' || src_[pos_] == 'E')) { + ++pos_; + if (pos_ < src_.size() && (src_[pos_] == '+' || src_[pos_] == '-')) ++pos_; + if (pos_ >= src_.size() || !std::isdigit(static_cast(src_[pos_]))) { + err = "Invalid JSON exponent"; + return false; + } + while (pos_ < src_.size() && std::isdigit(static_cast(src_[pos_]))) ++pos_; + } + std::string num_str(src_.substr(start, pos_ - start)); + char* endptr = nullptr; + double val = std::strtod(num_str.c_str(), &endptr); + if (endptr != num_str.c_str() + num_str.size() || !std::isfinite(val)) { + err = "Non-finite JSON number"; + return false; + } + out = val; + return true; + } + + bool parse_value(JsonValue& out, int depth, std::string& err) { + if (depth > 64) { + err = "JSON nesting too deep"; + return false; + } + skip_ws(); + if (pos_ >= src_.size()) { + err = "Unexpected end of JSON"; + return false; + } + char ch = src_[pos_]; + if (ch == '"') { + std::string s; + if (!parse_string(s, err)) return false; + out.data = std::move(s); + return true; + } + if (ch == '{') { + ++pos_; + JsonObject obj; + skip_ws(); + if (pos_ < src_.size() && src_[pos_] == '}') { + ++pos_; + out.data = std::move(obj); + return true; + } + while (true) { + skip_ws(); + std::string key; + if (!parse_string(key, err)) return false; + skip_ws(); + if (pos_ >= src_.size() || src_[pos_] != ':') { + err = "Expected ':' in JSON object"; + return false; + } + ++pos_; + JsonValue val; + if (!parse_value(val, depth + 1, err)) return false; + obj.emplace_back(std::move(key), std::move(val)); + skip_ws(); + if (pos_ >= src_.size()) { + err = "Unterminated JSON object"; + return false; + } + if (src_[pos_] == '}') { + ++pos_; + out.data = std::move(obj); + return true; + } + if (src_[pos_] != ',') { + err = "Expected ',' or '}' in JSON object"; + return false; + } + ++pos_; + } + } + if (ch == '[') { + ++pos_; + JsonArray arr; + skip_ws(); + if (pos_ < src_.size() && src_[pos_] == ']') { + ++pos_; + out.data = std::move(arr); + return true; + } + while (true) { + JsonValue elem; + if (!parse_value(elem, depth + 1, err)) return false; + arr.push_back(std::move(elem)); + skip_ws(); + if (pos_ >= src_.size()) { + err = "Unterminated JSON array"; + return false; + } + if (src_[pos_] == ']') { + ++pos_; + out.data = std::move(arr); + return true; + } + if (src_[pos_] != ',') { + err = "Expected ',' or ']' in JSON array"; + return false; + } + ++pos_; + } + } + if (src_.substr(pos_, 4) == "true") { + pos_ += 4; + out.data = true; + return true; + } + if (src_.substr(pos_, 5) == "false") { + pos_ += 5; + out.data = false; + return true; + } + if (src_.substr(pos_, 4) == "null") { + pos_ += 4; + out.data = nullptr; + return true; + } + if (ch == '-' || std::isdigit(static_cast(ch))) { + double d = 0.0; + if (!parse_number(d, err)) return false; + out.data = d; + return true; + } + err = "Unexpected token in JSON"; + return false; + } + + std::string_view src_; + size_t pos_ = 0; +}; + +} // namespace + +std::string save_native_string(const Workbook& wb) { + std::string out; + out.reserve(4096); + out += "{\n \"htab_version\": 1,\n \"active_sheet\": "; + out += std::to_string(wb.active_sheet()); + out += ",\n \"sheets\": [\n"; + + for (int si = 0; si < wb.sheet_count(); ++si) { + const Sheet& s = wb.sheet(si); + out += " {\n \"name\": "; + append_json_string(out, s.name); + + // Deterministic sorted order for col_widths, row_heights, and cells + std::map sorted_cw(s.col_widths.begin(), s.col_widths.end()); + out += ",\n \"col_widths\": {"; + bool first_cw = true; + for (const auto& [col, w] : sorted_cw) { + if (!first_cw) out += ", "; + first_cw = false; + append_json_string(out, std::to_string(col)); + out += ": " + std::to_string(w); + } + out += "}"; + + std::map sorted_rh(s.row_heights.begin(), s.row_heights.end()); + out += ",\n \"row_heights\": {"; + bool first_rh = true; + for (const auto& [row, h] : sorted_rh) { + if (!first_rh) out += ", "; + first_rh = false; + append_json_string(out, std::to_string(row)); + out += ": " + std::to_string(h); + } + out += "}"; + + std::vector> sorted_cells; + sorted_cells.reserve(s.cells.size()); + for (const auto& [key, cell] : s.cells) { + if (cell.raw_input.empty() && cell.number_format.empty()) continue; + sorted_cells.emplace_back(key, &cell); + } + std::sort(sorted_cells.begin(), sorted_cells.end(), + [](const auto& a, const auto& b) { + if (a.first.row != b.first.row) return a.first.row < b.first.row; + return a.first.col < b.first.col; + }); + + out += ",\n \"cells\": ["; + if (!sorted_cells.empty()) out.push_back('\n'); + for (size_t idx = 0; idx < sorted_cells.size(); ++idx) { + const auto& [key, cell] = sorted_cells[idx]; + out += " {\"r\": " + std::to_string(key.row) + + ", \"c\": " + std::to_string(key.col) + ", \"raw\": "; + append_json_string(out, cell->raw_input); + if (!cell->number_format.empty()) { + out += ", \"fmt\": "; + append_json_string(out, cell->number_format); + } + out.push_back('}'); + if (idx + 1 < sorted_cells.size()) out.push_back(','); + out.push_back('\n'); + } + if (!sorted_cells.empty()) out += " "; + out += "]\n }"; + if (si + 1 < wb.sheet_count()) out.push_back(','); + out.push_back('\n'); + } + + out += " ]\n}\n"; + return out; +} + +bool save_native_file(const Workbook& wb, const std::string& path, std::string* err) { + std::ofstream out(path, std::ios::binary | std::ios::trunc); + if (!out) { + if (err) *err = "Cannot open file for writing: " + path; + return false; + } + std::string data = save_native_string(wb); + out.write(data.data(), static_cast(data.size())); + if (!out) { + if (err) *err = "Failed writing workbook file: " + path; + return false; + } + return true; +} + +bool load_native_string(Workbook& wb, std::string_view json_text, std::string* err) { + JsonParser parser(json_text); + JsonValue root; + std::string parse_err; + if (!parser.parse(root, parse_err)) { + if (err) *err = parse_err; + return false; + } + if (!root.is_object()) { + if (err) *err = "Root JSON value must be an object"; + return false; + } + const JsonValue* ver = root.find("htab_version"); + if (!ver || !ver->is_number() || static_cast(std::get(ver->data)) != 1) { + if (err) *err = "Unsupported or missing htab_version"; + return false; + } + const JsonValue* sheets_val = root.find("sheets"); + if (!sheets_val || !sheets_val->is_array() || std::get(sheets_val->data).empty()) { + if (err) *err = "Missing or empty sheets array"; + return false; + } + + int active_sheet = 0; + if (const JsonValue* act = root.find("active_sheet")) { + if (act->is_number()) active_sheet = static_cast(std::get(act->data)); + } + + std::vector loaded_sheets; + for (const auto& sv : std::get(sheets_val->data)) { + if (!sv.is_object()) { + if (err) *err = "Sheet entry must be an object"; + return false; + } + Sheet s; + const JsonValue* name_v = sv.find("name"); + if (!name_v || !name_v->is_string() || std::get(name_v->data).empty()) { + if (err) *err = "Sheet entry missing valid name"; + return false; + } + s.name = std::get(name_v->data); + + if (const JsonValue* cw = sv.find("col_widths"); cw && cw->is_object()) { + for (const auto& [k, v] : std::get(cw->data)) { + if (v.is_number()) { + int col = std::atoi(k.c_str()); + int w = static_cast(std::get(v.data)); + if (col >= 0 && col < kMaxCols && w > 0) s.col_widths[col] = w; + } + } + } + if (const JsonValue* rh = sv.find("row_heights"); rh && rh->is_object()) { + for (const auto& [k, v] : std::get(rh->data)) { + if (v.is_number()) { + int row = std::atoi(k.c_str()); + int h = static_cast(std::get(v.data)); + if (row >= 0 && row < kMaxRows && h > 0) s.row_heights[row] = h; + } + } + } + if (const JsonValue* cells = sv.find("cells"); cells && cells->is_array()) { + for (const auto& cv : std::get(cells->data)) { + if (!cv.is_object()) continue; + const JsonValue* rv = cv.find("r"); + const JsonValue* colv = cv.find("c"); + const JsonValue* rawv = cv.find("raw"); + if (!rv || !rv->is_number() || !colv || !colv->is_number() || !rawv || !rawv->is_string()) { + if (err) *err = "Invalid cell object in JSON"; + return false; + } + int r = static_cast(std::get(rv->data)); + int c = static_cast(std::get(colv->data)); + if (r < 0 || r >= kMaxRows || c < 0 || c >= kMaxCols) { + if (err) *err = "Cell coordinates out of bounds"; + return false; + } + Cell cell; + cell.raw_input = std::get(rawv->data); + if (const JsonValue* fmtv = cv.find("fmt"); fmtv && fmtv->is_string()) { + cell.number_format = std::get(fmtv->data); + } + s.cells.emplace(CellKey{r, c}, std::move(cell)); + } + } + loaded_sheets.push_back(std::move(s)); + } + + wb.replace_all_sheets(std::move(loaded_sheets), active_sheet); + return true; +} + +bool load_native_file(Workbook& wb, const std::string& path, std::string* err) { + std::ifstream in(path, std::ios::binary); + if (!in) { + if (err) *err = "Cannot open workbook file for reading: " + path; + return false; + } + std::ostringstream oss; + oss << in.rdbuf(); + return load_native_string(wb, oss.str(), err); +} + +} // namespace htab diff --git a/engine/io_native.hpp b/engine/io_native.hpp new file mode 100644 index 0000000..dc8bfe1 --- /dev/null +++ b/engine/io_native.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "engine/workbook.hpp" + +#include +#include + +namespace htab { + +std::string save_native_string(const Workbook& wb); + +bool save_native_file(const Workbook& wb, + const std::string& path, + std::string* err = nullptr); + +bool load_native_string(Workbook& wb, + std::string_view json_text, + std::string* err = nullptr); + +bool load_native_file(Workbook& wb, + const std::string& path, + std::string* err = nullptr); + +} // namespace htab diff --git a/engine/lexer.cpp b/engine/lexer.cpp new file mode 100644 index 0000000..22e9534 --- /dev/null +++ b/engine/lexer.cpp @@ -0,0 +1,428 @@ +#include "engine/lexer.hpp" + +#include +#include +#include + +namespace htab { + +namespace { + +bool is_ident_start(char ch) { + unsigned char uc = static_cast(ch); + return std::isalpha(uc) || ch == '_'; +} + +bool is_ident_cont(char ch) { + unsigned char uc = static_cast(ch); + return std::isalnum(uc) || ch == '_' || ch == '.'; +} + +bool try_parse_ref_tail(std::string_view src, size_t pos, size_t& end_out, CellRef& ref_out) { + size_t i = pos; + if (i < src.size() && src[i] == '$') { + ref_out.abs_col = true; + ++i; + } + size_t col_start = i; + while (i < src.size() && std::isalpha(static_cast(src[i]))) { + ++i; + } + if (i == col_start) return false; + int col = letters_to_col(src.substr(col_start, i - col_start)); + if (col < 0) return false; + + if (i < src.size() && src[i] == '$') { + ref_out.abs_row = true; + ++i; + } + size_t row_start = i; + int64_t row1 = 0; + while (i < src.size() && std::isdigit(static_cast(src[i]))) { + row1 = row1 * 10 + (src[i] - '0'); + if (row1 > kMaxRows) return false; + ++i; + } + if (i == row_start || row1 < 1) return false; + // Must not immediately continue into identifier characters or '(' (unless '$' anchored). + if (i < src.size()) { + if (is_ident_cont(src[i])) return false; + if (!ref_out.abs_col && !ref_out.abs_row && src[i] == '(') return false; + } + ref_out.col = col; + ref_out.row = static_cast(row1 - 1); + end_out = i; + return true; +} + +bool try_parse_error_at(std::string_view src, size_t pos, size_t& end_out, ErrorCode& err_out) { + static constexpr const char* kErrors[] = { + "#DIV/0!", "#VALUE!", "#NAME?", "#N/A", "#REF!", "#NUM!", "#CYCLE!", "#SPILL!", + }; + for (const char* lit : kErrors) { + std::string_view lv(lit); + if (pos + lv.size() <= src.size() && iequals_ascii(src.substr(pos, lv.size()), lv)) { + end_out = pos + lv.size(); + err_out = *parse_error_code(lv); + return true; + } + } + return false; +} + +} // namespace + +std::vector Lexer::tokenize(std::string_view input, bool skip_leading_equals) { + std::vector tokens; + size_t i = 0; + if (skip_leading_equals && i < input.size() && input[i] == '=') { + ++i; + } + + while (i < input.size()) { + bool had_space = false; + while (i < input.size() && (input[i] == ' ' || input[i] == '\t' || + input[i] == '\r' || input[i] == '\n')) { + had_space = true; + ++i; + } + if (i >= input.size()) break; + + size_t start = i; + char ch = input[i]; + + // String literal "..." + if (ch == '"') { + ++i; + std::string val; + bool closed = false; + while (i < input.size()) { + if (input[i] == '"') { + if (i + 1 < input.size() && input[i + 1] == '"') { + val.push_back('"'); + i += 2; + } else { + ++i; + closed = true; + break; + } + } else { + val.push_back(input[i++]); + } + } + Token tok; + tok.start = start; + tok.end = i; + tok.had_space_before = had_space; + if (closed) { + tok.kind = TokenKind::String; + tok.text = std::move(val); + } else { + tok.kind = TokenKind::Invalid; + tok.text = std::string(input.substr(start, i - start)); + } + tokens.push_back(std::move(tok)); + continue; + } + + // Quoted sheet name '...'!CellRef or '...'!#REF! + if (ch == '\'') { + ++i; + std::string sheet; + bool closed = false; + while (i < input.size()) { + if (input[i] == '\'') { + if (i + 1 < input.size() && input[i + 1] == '\'') { + sheet.push_back('\''); + i += 2; + } else { + ++i; + closed = true; + break; + } + } else { + sheet.push_back(input[i++]); + } + } + Token tok; + tok.start = start; + tok.had_space_before = had_space; + if (!closed || sheet.empty() || i >= input.size() || input[i] != '!') { + tok.kind = TokenKind::Invalid; + tok.end = i; + tok.text = std::string(input.substr(start, i - start)); + tokens.push_back(std::move(tok)); + continue; + } + ++i; // skip '!' + ErrorCode err = ErrorCode::Ref; + size_t end_pos = i; + if (try_parse_error_at(input, i, end_pos, err) && err == ErrorCode::Ref) { + tok.kind = TokenKind::Error; + tok.err_val = ErrorCode::Ref; + tok.ref_val.sheet_name = sheet; + tok.ref_val.invalid = true; + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + tokens.push_back(std::move(tok)); + continue; + } + CellRef ref; + ref.sheet_name = std::move(sheet); + if (try_parse_ref_tail(input, i, end_pos, ref)) { + tok.kind = TokenKind::CellRef; + tok.ref_val = std::move(ref); + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + } else { + tok.kind = TokenKind::Invalid; + tok.end = i; + tok.text = std::string(input.substr(start, i - start)); + } + tokens.push_back(std::move(tok)); + continue; + } + + // Error literal #... + if (ch == '#') { + ErrorCode err = ErrorCode::Value; + size_t end_pos = i; + Token tok; + tok.start = start; + tok.had_space_before = had_space; + if (try_parse_error_at(input, i, end_pos, err)) { + tok.kind = TokenKind::Error; + tok.err_val = err; + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + } else { + ++i; + tok.kind = TokenKind::Invalid; + tok.end = i; + tok.text = std::string(input.substr(start, 1)); + } + tokens.push_back(std::move(tok)); + continue; + } + + // Number literal + if (std::isdigit(static_cast(ch)) || + (ch == '.' && i + 1 < input.size() && std::isdigit(static_cast(input[i + 1])))) { + while (i < input.size() && std::isdigit(static_cast(input[i]))) ++i; + if (i < input.size() && input[i] == '.') { + ++i; + while (i < input.size() && std::isdigit(static_cast(input[i]))) ++i; + } + if (i < input.size() && (input[i] == 'e' || input[i] == 'E')) { + size_t exp_save = i; + ++i; + if (i < input.size() && (input[i] == '+' || input[i] == '-')) ++i; + if (i < input.size() && std::isdigit(static_cast(input[i]))) { + while (i < input.size() && std::isdigit(static_cast(input[i]))) ++i; + } else { + i = exp_save; + } + } + std::string num_str(input.substr(start, i - start)); + char* endptr = nullptr; + double val = std::strtod(num_str.c_str(), &endptr); + bool valid_num = (endptr == num_str.c_str() + num_str.size()) && std::isfinite(val); + Token tok; + tok.start = start; + tok.end = i; + tok.had_space_before = had_space; + tok.text = std::move(num_str); + if (valid_num) { + tok.kind = TokenKind::Number; + tok.num_val = (val == 0.0) ? 0.0 : val; + } else { + tok.kind = TokenKind::Error; + tok.err_val = ErrorCode::Num; + } + tokens.push_back(std::move(tok)); + continue; + } + + // Anchored cell reference starting with '$' + if (ch == '$') { + CellRef ref; + size_t end_pos = i; + Token tok; + tok.start = start; + tok.had_space_before = had_space; + if (try_parse_ref_tail(input, i, end_pos, ref)) { + tok.kind = TokenKind::CellRef; + tok.ref_val = std::move(ref); + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + } else { + ++i; + tok.kind = TokenKind::Invalid; + tok.end = i; + tok.text = "$"; + } + tokens.push_back(std::move(tok)); + continue; + } + + // Identifier, Boolean, CellRef, or Unquoted Sheet!Ref + if (is_ident_start(ch)) { + while (i < input.size() && is_ident_cont(input[i])) ++i; + // Handle A$1 where '$' follows column letters directly + if (i < input.size() && input[i] == '$') { + CellRef ref; + size_t end_pos = start; + if (try_parse_ref_tail(input, start, end_pos, ref)) { + Token tok; + tok.kind = TokenKind::CellRef; + tok.ref_val = std::move(ref); + tok.start = start; + tok.end = end_pos; + tok.had_space_before = had_space; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + tokens.push_back(std::move(tok)); + continue; + } + } + + std::string word(input.substr(start, i - start)); + Token tok; + tok.start = start; + tok.had_space_before = had_space; + + if (i < input.size() && input[i] == '!') { + ++i; + ErrorCode err = ErrorCode::Ref; + size_t end_pos = i; + if (try_parse_error_at(input, i, end_pos, err) && err == ErrorCode::Ref) { + tok.kind = TokenKind::Error; + tok.err_val = ErrorCode::Ref; + tok.ref_val.sheet_name = std::move(word); + tok.ref_val.invalid = true; + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + tokens.push_back(std::move(tok)); + continue; + } + CellRef ref; + ref.sheet_name = std::move(word); + if (try_parse_ref_tail(input, i, end_pos, ref)) { + tok.kind = TokenKind::CellRef; + tok.ref_val = std::move(ref); + tok.end = end_pos; + tok.text = std::string(input.substr(start, end_pos - start)); + i = end_pos; + } else { + tok.kind = TokenKind::Invalid; + tok.end = i; + tok.text = std::string(input.substr(start, i - start)); + } + tokens.push_back(std::move(tok)); + continue; + } + + // If immediately followed by '(', it is always a function name (e.g. LOG10(...), TRUE()). + if (i < input.size() && input[i] == '(') { + tok.kind = TokenKind::Ident; + tok.end = i; + tok.text = to_upper_ascii(word); + tokens.push_back(std::move(tok)); + continue; + } + + if (iequals_ascii(word, "TRUE")) { + tok.kind = TokenKind::Bool; + tok.bool_val = true; + tok.end = i; + tok.text = std::move(word); + tokens.push_back(std::move(tok)); + continue; + } + if (iequals_ascii(word, "FALSE")) { + tok.kind = TokenKind::Bool; + tok.bool_val = false; + tok.end = i; + tok.text = std::move(word); + tokens.push_back(std::move(tok)); + continue; + } + + // Check if valid unanchored cell ref like A1 or AA100 + CellRef ref; + size_t end_pos = start; + if (try_parse_ref_tail(input, start, end_pos, ref) && end_pos == i) { + tok.kind = TokenKind::CellRef; + tok.ref_val = std::move(ref); + tok.end = i; + tok.text = std::move(word); + tokens.push_back(std::move(tok)); + continue; + } + + tok.kind = TokenKind::Ident; + tok.end = i; + tok.text = to_upper_ascii(word); + tokens.push_back(std::move(tok)); + continue; + } + + // Two-character operators + if (i + 1 < input.size()) { + std::string_view two = input.substr(i, 2); + if (two == "<>" || two == "<=" || two == ">=") { + Token tok; + tok.kind = (two == "<>") ? TokenKind::Neq : (two == "<=" ? TokenKind::Le : TokenKind::Ge); + tok.text = std::string(two); + tok.start = start; + tok.end = i + 2; + tok.had_space_before = had_space; + i += 2; + tokens.push_back(std::move(tok)); + continue; + } + } + + // Single-character operators + TokenKind sk = TokenKind::Invalid; + switch (ch) { + case ':': sk = TokenKind::Colon; break; + case ',': sk = TokenKind::Comma; break; + case '+': sk = TokenKind::Plus; break; + case '-': sk = TokenKind::Minus; break; + case '*': sk = TokenKind::Star; break; + case '/': sk = TokenKind::Slash; break; + case '^': sk = TokenKind::Caret; break; + case '%': sk = TokenKind::Percent; break; + case '&': sk = TokenKind::Amp; break; + case '=': sk = TokenKind::Eq; break; + case '<': sk = TokenKind::Lt; break; + case '>': sk = TokenKind::Gt; break; + case '(': sk = TokenKind::LParen; break; + case ')': sk = TokenKind::RParen; break; + default: sk = TokenKind::Invalid; break; + } + ++i; + Token tok; + tok.kind = sk; + tok.text = std::string(1, ch); + tok.start = start; + tok.end = i; + tok.had_space_before = had_space; + tokens.push_back(std::move(tok)); + } + + Token eof; + eof.kind = TokenKind::Eof; + eof.start = input.size(); + eof.end = input.size(); + tokens.push_back(std::move(eof)); + return tokens; +} + +} // namespace htab diff --git a/engine/lexer.hpp b/engine/lexer.hpp new file mode 100644 index 0000000..3b64e98 --- /dev/null +++ b/engine/lexer.hpp @@ -0,0 +1,58 @@ +#pragma once + +#include "engine/address.hpp" +#include "engine/value.hpp" + +#include +#include +#include +#include + +namespace htab { + +enum class TokenKind { + Number, + String, + Bool, + Error, + CellRef, + Ident, + Colon, + Comma, + Plus, + Minus, + Star, + Slash, + Caret, + Percent, + Amp, + Eq, + Neq, + Lt, + Gt, + Le, + Ge, + LParen, + RParen, + Eof, + Invalid, +}; + +struct Token { + TokenKind kind = TokenKind::Invalid; + std::string text; + size_t start = 0; + size_t end = 0; + bool had_space_before = false; + double num_val = 0.0; + bool bool_val = false; + ErrorCode err_val = ErrorCode::Value; + CellRef ref_val; +}; + +class Lexer { + public: + static std::vector tokenize(std::string_view input, bool skip_leading_equals = true); +}; + +} // namespace htab diff --git a/engine/parser.cpp b/engine/parser.cpp new file mode 100644 index 0000000..5d3f599 --- /dev/null +++ b/engine/parser.cpp @@ -0,0 +1,227 @@ +#include "engine/parser.hpp" + +namespace htab { + +namespace { + +class PrattParser { + public: + explicit PrattParser(std::vector tokens) : tokens_(std::move(tokens)) {} + + ParseResult parse() { + if (peek().kind == TokenKind::Eof) { + return {nullptr, false, "Empty formula"}; + } + auto expr = parse_expr(0, false); + if (!expr) { + return {nullptr, false, error_.empty() ? "Syntax error" : error_}; + } + if (peek().kind != TokenKind::Eof) { + return {nullptr, false, "Unexpected trailing token: " + peek().text}; + } + return {std::move(expr), true, ""}; + } + + private: + const Token& peek() const { return tokens_[pos_]; } + const Token& advance() { + const Token& t = tokens_[pos_]; + if (pos_ + 1 < tokens_.size()) ++pos_; + return t; + } + + static bool is_ref_capable(const Expr* e) { + if (!e) return false; + switch (e->kind) { + case Expr::Kind::CellRef: + case Expr::Kind::Range: + case Expr::Kind::Call: + return true; + case Expr::Kind::Binary: { + auto* b = static_cast(e); + return b->op == BinOp::Intersect || b->op == BinOp::Union; + } + default: + return false; + } + } + + static bool infix_bp(TokenKind kind, int& lbp, int& rbp, BinOp& op) { + switch (kind) { + case TokenKind::Eq: lbp = 10; rbp = 11; op = BinOp::Eq; return true; + case TokenKind::Neq: lbp = 10; rbp = 11; op = BinOp::Neq; return true; + case TokenKind::Lt: lbp = 10; rbp = 11; op = BinOp::Lt; return true; + case TokenKind::Gt: lbp = 10; rbp = 11; op = BinOp::Gt; return true; + case TokenKind::Le: lbp = 10; rbp = 11; op = BinOp::Le; return true; + case TokenKind::Ge: lbp = 10; rbp = 11; op = BinOp::Ge; return true; + case TokenKind::Amp: lbp = 20; rbp = 21; op = BinOp::Concat; return true; + case TokenKind::Plus: lbp = 30; rbp = 31; op = BinOp::Add; return true; + case TokenKind::Minus: lbp = 30; rbp = 31; op = BinOp::Sub; return true; + case TokenKind::Star: lbp = 40; rbp = 41; op = BinOp::Mul; return true; + case TokenKind::Slash: lbp = 40; rbp = 41; op = BinOp::Div; return true; + case TokenKind::Caret: lbp = 50; rbp = 51; op = BinOp::Pow; return true; + default: return false; + } + } + + std::shared_ptr parse_expr(int min_bp, bool allow_union) { + auto lhs = parse_nud(); + if (!lhs) return nullptr; + + while (true) { + const Token& t = peek(); + if (t.kind == TokenKind::Invalid) { + error_ = "Invalid token: " + t.text; + return nullptr; + } + + // Range operator ':' (precedence 90, left-assoc) + if (t.kind == TokenKind::Colon) { + if (90 < min_bp) break; + advance(); + auto rhs = parse_expr(91, allow_union); + if (!rhs) return nullptr; + lhs = std::make_shared(std::move(lhs), std::move(rhs)); + continue; + } + + // Implicit intersection operator ' ' (precedence 85, left-assoc) + if (t.had_space_before && is_ref_capable(lhs.get()) && + (t.kind == TokenKind::CellRef || t.kind == TokenKind::LParen || + t.kind == TokenKind::Ident)) { + if (85 < min_bp) break; + auto rhs = parse_expr(86, allow_union); + if (!rhs) return nullptr; + lhs = std::make_shared(BinOp::Intersect, std::move(lhs), std::move(rhs)); + continue; + } + + // Union operator ',' inside parenthesized expressions (precedence 80, left-assoc) + if (allow_union && t.kind == TokenKind::Comma) { + if (80 < min_bp) break; + advance(); + auto rhs = parse_expr(81, allow_union); + if (!rhs) return nullptr; + lhs = std::make_shared(BinOp::Union, std::move(lhs), std::move(rhs)); + continue; + } + + // Postfix '%' (precedence 60, below unary prefix 70 and above '^' 50) + if (t.kind == TokenKind::Percent) { + if (60 < min_bp) break; + advance(); + lhs = std::make_shared(std::move(lhs)); + continue; + } + + int lbp = 0, rbp = 0; + BinOp op = BinOp::Add; + if (infix_bp(t.kind, lbp, rbp, op)) { + if (lbp < min_bp) break; + advance(); + auto rhs = parse_expr(rbp, allow_union); + if (!rhs) return nullptr; + lhs = std::make_shared(op, std::move(lhs), std::move(rhs)); + continue; + } + + break; + } + + return lhs; + } + + std::shared_ptr parse_nud() { + const Token& t = peek(); + switch (t.kind) { + case TokenKind::Number: { + double v = t.num_val; + advance(); + return std::make_shared(Value::make_number(v)); + } + case TokenKind::String: { + std::string s = t.text; + advance(); + return std::make_shared(Value::make_string(std::move(s))); + } + case TokenKind::Bool: { + bool b = t.bool_val; + advance(); + return std::make_shared(Value::make_bool(b)); + } + case TokenKind::Error: { + ErrorCode err = t.err_val; + advance(); + return std::make_shared(Value::make_error(err)); + } + case TokenKind::CellRef: { + CellRef ref = t.ref_val; + advance(); + return std::make_shared(std::move(ref)); + } + case TokenKind::Ident: { + std::string name = t.text; + advance(); + if (peek().kind == TokenKind::LParen) { + advance(); // consume '(' + std::vector> args; + if (peek().kind != TokenKind::RParen) { + while (true) { + auto arg = parse_expr(0, false); + if (!arg) return nullptr; + args.push_back(std::move(arg)); + if (peek().kind == TokenKind::Comma) { + advance(); + continue; + } + break; + } + } + if (peek().kind != TokenKind::RParen) { + error_ = "Expected ')' in call to " + name; + return nullptr; + } + advance(); + return std::make_shared(std::move(name), std::move(args)); + } + return std::make_shared(std::move(name)); + } + case TokenKind::Plus: + case TokenKind::Minus: { + char op = (t.kind == TokenKind::Plus) ? '+' : '-'; + advance(); + auto rhs = parse_expr(70, false); + if (!rhs) return nullptr; + return std::make_shared(op, std::move(rhs)); + } + case TokenKind::LParen: { + advance(); + auto inner = parse_expr(0, true); + if (!inner) return nullptr; + if (peek().kind != TokenKind::RParen) { + error_ = "Expected ')'"; + return nullptr; + } + advance(); + return inner; + } + default: + error_ = "Unexpected token: " + t.text; + return nullptr; + } + } + + std::vector tokens_; + size_t pos_ = 0; + std::string error_; +}; + +} // namespace + +ParseResult Parser::parse_formula(std::string_view formula) { + auto tokens = Lexer::tokenize(formula, true); + PrattParser p(std::move(tokens)); + return p.parse(); +} + +} // namespace htab diff --git a/engine/parser.hpp b/engine/parser.hpp new file mode 100644 index 0000000..9d56521 --- /dev/null +++ b/engine/parser.hpp @@ -0,0 +1,107 @@ +#pragma once + +#include "engine/address.hpp" +#include "engine/lexer.hpp" +#include "engine/value.hpp" + +#include +#include +#include + +namespace htab { + +enum class BinOp { + Add, + Sub, + Mul, + Div, + Pow, + Concat, + Eq, + Neq, + Lt, + Gt, + Le, + Ge, + Intersect, + Union, +}; + +struct Expr { + enum class Kind { + Literal, + CellRef, + Range, + Unary, + Percent, + Binary, + Call, + UnknownName, + }; + + Kind kind; + explicit Expr(Kind k) : kind(k) {} + virtual ~Expr() = default; +}; + +struct LiteralExpr : Expr { + Value value; + explicit LiteralExpr(Value v) : Expr(Kind::Literal), value(std::move(v)) {} +}; + +struct CellRefExpr : Expr { + CellRef ref; + explicit CellRefExpr(CellRef r) : Expr(Kind::CellRef), ref(std::move(r)) {} +}; + +struct RangeExpr : Expr { + std::shared_ptr lhs; + std::shared_ptr rhs; + RangeExpr(std::shared_ptr l, std::shared_ptr r) + : Expr(Kind::Range), lhs(std::move(l)), rhs(std::move(r)) {} +}; + +struct UnaryExpr : Expr { + char op = '+'; + std::shared_ptr operand; + UnaryExpr(char o, std::shared_ptr e) + : Expr(Kind::Unary), op(o), operand(std::move(e)) {} +}; + +struct PercentExpr : Expr { + std::shared_ptr operand; + explicit PercentExpr(std::shared_ptr e) : Expr(Kind::Percent), operand(std::move(e)) {} +}; + +struct BinaryExpr : Expr { + BinOp op; + std::shared_ptr lhs; + std::shared_ptr rhs; + BinaryExpr(BinOp o, std::shared_ptr l, std::shared_ptr r) + : Expr(Kind::Binary), op(o), lhs(std::move(l)), rhs(std::move(r)) {} +}; + +struct CallExpr : Expr { + std::string name; + std::vector> args; + CallExpr(std::string n, std::vector> a) + : Expr(Kind::Call), name(std::move(n)), args(std::move(a)) {} +}; + +struct UnknownNameExpr : Expr { + std::string name; + explicit UnknownNameExpr(std::string n) : Expr(Kind::UnknownName), name(std::move(n)) {} +}; + +struct ParseResult { + std::shared_ptr ast; + bool ok = false; + std::string error; +}; + +class Parser { + public: + static ParseResult parse_formula(std::string_view formula); +}; + +} // namespace htab diff --git a/engine/value.cpp b/engine/value.cpp new file mode 100644 index 0000000..5ba7d1a --- /dev/null +++ b/engine/value.cpp @@ -0,0 +1,275 @@ +#include "engine/value.hpp" + +#include +#include +#include +#include +#include + +namespace htab { + +namespace { + +bool is_ascii_space(char ch) { + return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'; +} + +std::optional parse_numeric_text(std::string_view sv) { + sv = trim_ascii(sv); + if (sv.empty()) { + return std::nullopt; + } + bool is_percent = false; + if (sv.back() == '%') { + is_percent = true; + sv.remove_suffix(1); + sv = trim_ascii(sv); + if (sv.empty()) { + return std::nullopt; + } + } + size_t i = 0; + if (sv[i] == '+' || sv[i] == '-') { + ++i; + } + bool has_digits = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + if (i < sv.size() && sv[i] == '.') { + ++i; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + } + if (!has_digits) { + return std::nullopt; + } + if (i < sv.size() && (sv[i] == 'e' || sv[i] == 'E')) { + ++i; + if (i < sv.size() && (sv[i] == '+' || sv[i] == '-')) { + ++i; + } + bool exp_digits = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + exp_digits = true; + ++i; + } + if (!exp_digits) { + return std::nullopt; + } + } + if (i != sv.size()) { + return std::nullopt; + } + + std::string tmp(sv); + char* endptr = nullptr; + double val = std::strtod(tmp.c_str(), &endptr); + if (endptr != tmp.c_str() + tmp.size() || !std::isfinite(val)) { + return std::nullopt; + } + if (is_percent) { + val /= 100.0; + } + if (val == 0.0) { + val = 0.0; + } + return val; +} + +Value unwrap_1x1(const Value& v) { + if (!v.is_array()) { + return v; + } + const auto& arr = v.as_array(); + if (arr && arr->rows == 1 && arr->cols == 1 && !arr->data.empty()) { + return arr->at(0, 0); + } + return Value::make_error(ErrorCode::Value); +} + +int compare_strings_ci(std::string_view a, std::string_view b) { + size_t n = std::min(a.size(), b.size()); + for (size_t i = 0; i < n; ++i) { + unsigned char ca = static_cast(std::tolower(static_cast(a[i]))); + unsigned char cb = static_cast(std::tolower(static_cast(b[i]))); + if (ca < cb) return -1; + if (ca > cb) return 1; + } + if (a.size() < b.size()) return -1; + if (a.size() > b.size()) return 1; + return 0; +} + +int type_rank(const Value& v) { + if (v.is_number()) return 0; + if (v.is_string()) return 1; + if (v.is_bool()) return 2; + return 3; +} + +} // namespace + +std::string_view error_to_string(ErrorCode err) { + switch (err) { + case ErrorCode::Div0: return "#DIV/0!"; + case ErrorCode::Value: return "#VALUE!"; + case ErrorCode::Name: return "#NAME?"; + case ErrorCode::NA: return "#N/A"; + case ErrorCode::Ref: return "#REF!"; + case ErrorCode::Num: return "#NUM!"; + case ErrorCode::Cycle: return "#CYCLE!"; + case ErrorCode::Spill: return "#SPILL!"; + } + return "#VALUE!"; +} + +std::optional parse_error_code(std::string_view text) { + text = trim_ascii(text); + if (iequals_ascii(text, "#DIV/0!")) return ErrorCode::Div0; + if (iequals_ascii(text, "#VALUE!")) return ErrorCode::Value; + if (iequals_ascii(text, "#NAME?")) return ErrorCode::Name; + if (iequals_ascii(text, "#N/A")) return ErrorCode::NA; + if (iequals_ascii(text, "#REF!")) return ErrorCode::Ref; + if (iequals_ascii(text, "#NUM!")) return ErrorCode::Num; + if (iequals_ascii(text, "#CYCLE!")) return ErrorCode::Cycle; + if (iequals_ascii(text, "#SPILL!")) return ErrorCode::Spill; + return std::nullopt; +} + +Value Value::make_number(double d) { + return Value(d == 0.0 ? 0.0 : d); +} + +Value Value::make_checked_number(double d) { + if (!std::isfinite(d)) { + return Value::make_error(ErrorCode::Num); + } + return Value(d == 0.0 ? 0.0 : d); +} + +std::variant to_number(const Value& v) { + Value u = unwrap_1x1(v); + if (u.is_error()) return u.as_error(); + if (u.is_empty()) return 0.0; + if (u.is_number()) return u.as_number(); + if (u.is_bool()) return u.as_bool() ? 1.0 : 0.0; + if (u.is_string()) { + auto parsed = parse_numeric_text(u.as_string()); + if (parsed) return *parsed; + return ErrorCode::Value; + } + return ErrorCode::Value; +} + +std::variant to_bool(const Value& v) { + Value u = unwrap_1x1(v); + if (u.is_error()) return u.as_error(); + if (u.is_empty()) return false; + if (u.is_bool()) return u.as_bool(); + if (u.is_number()) return u.as_number() != 0.0; + if (u.is_string()) { + auto t = trim_ascii(u.as_string()); + if (iequals_ascii(t, "TRUE")) return true; + if (iequals_ascii(t, "FALSE")) return false; + return ErrorCode::Value; + } + return ErrorCode::Value; +} + +std::variant to_string(const Value& v) { + Value u = unwrap_1x1(v); + if (u.is_error()) return u.as_error(); + if (u.is_empty()) return std::string{}; + if (u.is_string()) return u.as_string(); + if (u.is_bool()) return u.as_bool() ? std::string("TRUE") : std::string("FALSE"); + if (u.is_number()) { + double d = u.as_number(); + if (d == 0.0) d = 0.0; + char buf[64]; + std::snprintf(buf, sizeof(buf), "%.15g", d); + return std::string(buf); + } + return ErrorCode::Value; +} + +std::variant compare_values(const Value& a_in, const Value& b_in) { + Value a = unwrap_1x1(a_in); + if (a.is_error()) return a.as_error(); + Value b = unwrap_1x1(b_in); + if (b.is_error()) return b.as_error(); + + if (a.is_empty() && b.is_empty()) { + return 0; + } + if (a.is_empty()) { + if (b.is_number()) a = Value::make_number(0.0); + else if (b.is_string()) a = Value::make_string(""); + else if (b.is_bool()) a = Value::make_bool(false); + } else if (b.is_empty()) { + if (a.is_number()) b = Value::make_number(0.0); + else if (a.is_string()) b = Value::make_string(""); + else if (a.is_bool()) b = Value::make_bool(false); + } + + int ra = type_rank(a); + int rb = type_rank(b); + if (ra != rb) { + return ra < rb ? -1 : 1; + } + if (a.is_number()) { + double da = a.as_number(); + double db = b.as_number(); + if (da < db) return -1; + if (da > db) return 1; + return 0; + } + if (a.is_string()) { + return compare_strings_ci(a.as_string(), b.as_string()); + } + if (a.is_bool()) { + bool ba = a.as_bool(); + bool bb = b.as_bool(); + if (ba == bb) return 0; + return ba ? 1 : -1; + } + return 0; +} + +bool iequals_ascii(std::string_view a, std::string_view b) { + if (a.size() != b.size()) return false; + for (size_t i = 0; i < a.size(); ++i) { + if (std::tolower(static_cast(a[i])) != + std::tolower(static_cast(b[i]))) { + return false; + } + } + return true; +} + +std::string to_upper_ascii(std::string_view s) { + std::string out(s); + for (char& ch : out) { + ch = static_cast(std::toupper(static_cast(ch))); + } + return out; +} + +std::string to_lower_ascii(std::string_view s) { + std::string out(s); + for (char& ch : out) { + ch = static_cast(std::tolower(static_cast(ch))); + } + return out; +} + +std::string_view trim_ascii(std::string_view s) { + while (!s.empty() && is_ascii_space(s.front())) s.remove_prefix(1); + while (!s.empty() && is_ascii_space(s.back())) s.remove_suffix(1); + return s; +} + +} // namespace htab diff --git a/engine/value.hpp b/engine/value.hpp new file mode 100644 index 0000000..4e52df9 --- /dev/null +++ b/engine/value.hpp @@ -0,0 +1,97 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace htab { + +enum class ErrorCode { + Div0, + Value, + Name, + NA, + Ref, + Num, + Cycle, + Spill, +}; + +std::string_view error_to_string(ErrorCode err); +std::optional parse_error_code(std::string_view text); + +struct Empty { + bool operator==(const Empty&) const = default; +}; + +struct Array2D; + +struct Value { + using Variant = std::variant>; + + Variant data; + + Value() : data(Empty{}) {} + explicit Value(Empty e) : data(e) {} + explicit Value(double d) : data(d == 0.0 ? 0.0 : d) {} + explicit Value(bool b) : data(b) {} + explicit Value(std::string s) : data(std::move(s)) {} + explicit Value(ErrorCode err) : data(err) {} + explicit Value(std::shared_ptr arr) : data(std::move(arr)) {} + + static Value make_empty() { return Value(Empty{}); } + static Value make_number(double d); + static Value make_checked_number(double d); + static Value make_bool(bool b) { return Value(b); } + static Value make_string(std::string s) { return Value(std::move(s)); } + static Value make_error(ErrorCode err) { return Value(err); } + static Value make_array(std::shared_ptr arr) { return Value(std::move(arr)); } + + bool is_empty() const { return std::holds_alternative(data); } + bool is_number() const { return std::holds_alternative(data); } + bool is_bool() const { return std::holds_alternative(data); } + bool is_string() const { return std::holds_alternative(data); } + bool is_error() const { return std::holds_alternative(data); } + bool is_array() const { return std::holds_alternative>(data); } + + double as_number() const { return std::get(data); } + bool as_bool() const { return std::get(data); } + const std::string& as_string() const { return std::get(data); } + ErrorCode as_error() const { return std::get(data); } + const std::shared_ptr& as_array() const { + return std::get>(data); + } +}; + +struct Array2D { + int rows = 0; + int cols = 0; + std::vector data; + + Array2D() = default; + Array2D(int r, int c, Value fill = Value::make_empty()) + : rows(r), cols(c), data(static_cast(r) * static_cast(c), std::move(fill)) {} + + const Value& at(int r, int c) const { + return data[static_cast(r) * static_cast(cols) + static_cast(c)]; + } + Value& at(int r, int c) { + return data[static_cast(r) * static_cast(cols) + static_cast(c)]; + } +}; + +std::variant to_number(const Value& v); +std::variant to_bool(const Value& v); +std::variant to_string(const Value& v); +std::variant compare_values(const Value& a, const Value& b); + +bool iequals_ascii(std::string_view a, std::string_view b); +std::string to_upper_ascii(std::string_view s); +std::string to_lower_ascii(std::string_view s); +std::string_view trim_ascii(std::string_view s); + +} // namespace htab diff --git a/engine/workbook.cpp b/engine/workbook.cpp new file mode 100644 index 0000000..865af84 --- /dev/null +++ b/engine/workbook.cpp @@ -0,0 +1,887 @@ +#include "engine/workbook.hpp" +#include "engine/dag.hpp" +#include "engine/evaluator.hpp" +#include "engine/format.hpp" + +#include +#include +#include +#include + +namespace htab { + +namespace { + +constexpr size_t kMaxUndoDepth = 200; + +bool try_parse_plain_number(std::string_view raw, double& val_out, bool& is_pct_out) { + std::string_view sv = trim_ascii(raw); + if (sv.empty()) return false; + is_pct_out = false; + if (sv.back() == '%') { + is_pct_out = true; + sv.remove_suffix(1); + sv = trim_ascii(sv); + if (sv.empty()) return false; + } + size_t i = 0; + if (sv[i] == '+' || sv[i] == '-') ++i; + bool has_digits = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + if (i < sv.size() && sv[i] == '.') { + ++i; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + has_digits = true; + ++i; + } + } + if (!has_digits) return false; + if (i < sv.size() && (sv[i] == 'e' || sv[i] == 'E')) { + ++i; + if (i < sv.size() && (sv[i] == '+' || sv[i] == '-')) ++i; + bool exp_digits = false; + while (i < sv.size() && std::isdigit(static_cast(sv[i]))) { + exp_digits = true; + ++i; + } + if (!exp_digits) return false; + } + if (i != sv.size()) return false; + + std::string tmp(sv); + char* endptr = nullptr; + double val = std::strtod(tmp.c_str(), &endptr); + if (endptr != tmp.c_str() + tmp.size() || !std::isfinite(val)) return false; + if (is_pct_out) val /= 100.0; + val_out = (val == 0.0) ? 0.0 : val; + return true; +} + +struct CellDelta { + int row = 0; + int col = 0; + std::string old_raw; + std::string old_fmt; + std::string new_raw; + std::string new_fmt; +}; + +} // namespace + +class EditCellsCmd : public Workbook::Command { + public: + EditCellsCmd(int sheet_idx, std::vector deltas) + : sheet_idx_(sheet_idx), deltas_(std::move(deltas)) {} + + void undo(Workbook& wb) override { + std::vector seeds; + seeds.reserve(deltas_.size()); + for (const auto& d : deltas_) { + wb.set_cell_raw_no_recalc(sheet_idx_, d.row, d.col, d.old_raw, d.old_fmt, seeds); + } + wb.dag_->recalculate_from(wb, std::move(seeds)); + } + + void redo(Workbook& wb) override { + std::vector seeds; + seeds.reserve(deltas_.size()); + for (const auto& d : deltas_) { + wb.set_cell_raw_no_recalc(sheet_idx_, d.row, d.col, d.new_raw, d.new_fmt, seeds); + } + wb.dag_->recalculate_from(wb, std::move(seeds)); + } + + private: + int sheet_idx_ = 0; + std::vector deltas_; +}; + +class SnapshotCmd : public Workbook::Command { + public: + SnapshotCmd(std::vector before_sheets, + int before_active, + std::vector after_sheets, + int after_active) + : before_sheets_(std::move(before_sheets)), + before_active_(before_active), + after_sheets_(std::move(after_sheets)), + after_active_(after_active) {} + + void undo(Workbook& wb) override { + wb.sheets_ = before_sheets_; + wb.active_sheet_ = std::clamp(before_active_, 0, wb.sheet_count() - 1); + wb.dag_->rebuild(wb); + } + + void redo(Workbook& wb) override { + wb.sheets_ = after_sheets_; + wb.active_sheet_ = std::clamp(after_active_, 0, wb.sheet_count() - 1); + wb.dag_->rebuild(wb); + } + + private: + std::vector before_sheets_; + int before_active_ = 0; + std::vector after_sheets_; + int after_active_ = 0; +}; + +class DimEditCmd : public Workbook::Command { + public: + DimEditCmd(int sheet_idx, bool is_col, int index, int old_val, int new_val) + : sheet_idx_(sheet_idx), + is_col_(is_col), + index_(index), + old_val_(old_val), + new_val_(new_val) {} + + void undo(Workbook& wb) override { apply(wb, old_val_); } + void redo(Workbook& wb) override { apply(wb, new_val_); } + + private: + void apply(Workbook& wb, int val) { + if (sheet_idx_ < 0 || sheet_idx_ >= wb.sheet_count()) return; + auto& map = is_col_ ? wb.sheet_mut(sheet_idx_).col_widths + : wb.sheet_mut(sheet_idx_).row_heights; + if (val <= 0) map.erase(index_); + else map[index_] = val; + } + + int sheet_idx_ = 0; + bool is_col_ = false; + int index_ = 0; + int old_val_ = 0; + int new_val_ = 0; +}; + +Workbook::Workbook() : dag_(std::make_unique()) { + Sheet s; + s.name = "Sheet1"; + sheets_.push_back(std::move(s)); +} + +Workbook::~Workbook() = default; +Workbook::Workbook(Workbook&&) noexcept = default; +Workbook& Workbook::operator=(Workbook&&) noexcept = default; + +void Workbook::set_active_sheet(int idx) { + if (idx >= 0 && idx < sheet_count()) { + active_sheet_ = idx; + } +} + +int Workbook::find_sheet(std::string_view name) const { + for (size_t i = 0; i < sheets_.size(); ++i) { + if (iequals_ascii(sheets_[i].name, name)) { + return static_cast(i); + } + } + return -1; +} + +void Workbook::push_command(std::unique_ptr cmd) { + redo_stack_.clear(); + undo_stack_.push_back(std::move(cmd)); + if (undo_stack_.size() > kMaxUndoDepth) { + undo_stack_.erase(undo_stack_.begin()); + } +} + +void Workbook::clear_history() { + undo_stack_.clear(); + redo_stack_.clear(); +} + +bool Workbook::undo() { + if (undo_stack_.empty()) return false; + auto cmd = std::move(undo_stack_.back()); + undo_stack_.pop_back(); + cmd->undo(*this); + redo_stack_.push_back(std::move(cmd)); + return true; +} + +bool Workbook::redo() { + if (redo_stack_.empty()) return false; + auto cmd = std::move(redo_stack_.back()); + redo_stack_.pop_back(); + cmd->redo(*this); + undo_stack_.push_back(std::move(cmd)); + return true; +} + +int Workbook::add_sheet(std::string name) { + auto before_sheets = sheets_; + int before_active = active_sheet_; + + if (name.empty()) { + int n = sheet_count() + 1; + while (true) { + std::string cand = "Sheet" + std::to_string(n); + if (find_sheet(cand) < 0) { + name = std::move(cand); + break; + } + ++n; + } + } else if (find_sheet(name) >= 0) { + return -1; + } + + Sheet s; + s.name = std::move(name); + sheets_.push_back(std::move(s)); + int idx = sheet_count() - 1; + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); + return idx; +} + +bool Workbook::rename_sheet(int sheet_idx, const std::string& new_name) { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return false; + std::string trimmed(trim_ascii(new_name)); + if (trimmed.empty()) return false; + int existing = find_sheet(trimmed); + if (existing >= 0 && existing != sheet_idx) return false; + if (sheets_[static_cast(sheet_idx)].name == trimmed) return true; + + auto before_sheets = sheets_; + int before_active = active_sheet_; + + std::string old_name = sheets_[static_cast(sheet_idx)].name; + sheets_[static_cast(sheet_idx)].name = trimmed; + rewrite_all_formulas(old_name, StructuralOp::RenameSheet, 0, 0, trimmed); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); + return true; +} + +bool Workbook::delete_sheet(int sheet_idx) { + if (sheet_count() <= 1 || sheet_idx < 0 || sheet_idx >= sheet_count()) return false; + + auto before_sheets = sheets_; + int before_active = active_sheet_; + + std::string deleted_name = sheets_[static_cast(sheet_idx)].name; + sheets_.erase(sheets_.begin() + sheet_idx); + if (active_sheet_ >= sheet_count()) { + active_sheet_ = sheet_count() - 1; + } else if (active_sheet_ > sheet_idx) { + --active_sheet_; + } + rewrite_all_formulas(deleted_name, StructuralOp::DeleteSheet, 0, 0); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); + return true; +} + +void Workbook::parse_cell_input(Cell& cell, const std::string& raw) { + cell.raw_input = raw; + cell.ast.reset(); + cell.parse_error = false; + + if (raw.empty()) { + cell.value = Value::make_empty(); + return; + } + if (raw[0] == '=') { + auto res = Parser::parse_formula(raw); + if (res.ok) { + cell.ast = std::move(res.ast); + } else { + cell.parse_error = true; + cell.value = Value::make_error(ErrorCode::Value); + } + return; + } + if (raw[0] == '\'') { + cell.value = Value::make_string(raw.substr(1)); + return; + } + auto trimmed = trim_ascii(raw); + if (iequals_ascii(trimmed, "TRUE")) { + cell.value = Value::make_bool(true); + return; + } + if (iequals_ascii(trimmed, "FALSE")) { + cell.value = Value::make_bool(false); + return; + } + if (auto err = parse_error_code(trimmed)) { + cell.value = Value::make_error(*err); + return; + } + double num = 0.0; + bool is_pct = false; + if (try_parse_plain_number(raw, num, is_pct)) { + cell.value = Value::make_number(num); + if (is_pct && cell.number_format.empty()) { + cell.number_format = "0.00%"; + } + return; + } + cell.value = Value::make_string(raw); +} + +void Workbook::set_cell_raw_no_recalc(int sheet_idx, + int row, + int col, + const std::string& raw, + const std::optional& fmt_override, + std::vector& dirty_seeds) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || + row < 0 || row >= kMaxRows || col < 0 || col >= kMaxCols) { + return; + } + Sheet& s = sheets_[static_cast(sheet_idx)]; + CellKey key{row, col}; + GlobalAddr addr{sheet_idx, row, col}; + + std::string target_fmt; + if (fmt_override.has_value()) { + target_fmt = *fmt_override; + } else { + auto it = s.cells.find(key); + if (it != s.cells.end()) target_fmt = it->second.number_format; + } + + if (raw.empty() && target_fmt.empty()) { + s.cells.erase(key); + dag_->remove_cell(addr); + dirty_seeds.push_back(addr); + return; + } + + Cell& cell = s.cells[key]; + cell.number_format = std::move(target_fmt); + parse_cell_input(cell, raw); + if (cell.ast) { + dag_->update_cell_deps(*this, addr, cell.ast.get()); + } else { + dag_->remove_cell(addr); + } + dirty_seeds.push_back(addr); +} + +void Workbook::set_cell_input(int sheet_idx, int row, int col, const std::string& raw) { + apply_cell_edits(sheet_idx, {CellEdit{row, col, raw, std::nullopt}}); +} + +void Workbook::apply_cell_edits(int sheet_idx, const std::vector& edits) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || edits.empty()) return; + + std::vector deltas; + deltas.reserve(edits.size()); + std::vector seeds; + seeds.reserve(edits.size()); + + for (const auto& ed : edits) { + if (ed.row < 0 || ed.row >= kMaxRows || ed.col < 0 || ed.col >= kMaxCols) continue; + const Cell* existing = get_cell(sheet_idx, ed.row, ed.col); + CellDelta delta; + delta.row = ed.row; + delta.col = ed.col; + delta.old_raw = existing ? existing->raw_input : ""; + delta.old_fmt = existing ? existing->number_format : ""; + delta.new_raw = ed.raw_input; + set_cell_raw_no_recalc(sheet_idx, ed.row, ed.col, ed.raw_input, ed.number_format, seeds); + const Cell* after = get_cell(sheet_idx, ed.row, ed.col); + delta.new_fmt = after ? after->number_format : ""; + if (delta.old_raw != delta.new_raw || delta.old_fmt != delta.new_fmt) { + deltas.push_back(std::move(delta)); + } + } + + if (!seeds.empty()) { + dag_->recalculate_from(*this, std::move(seeds)); + } + if (!deltas.empty()) { + push_command(std::make_unique(sheet_idx, std::move(deltas))); + } +} + +void Workbook::set_cell_format(int sheet_idx, int row, int col, const std::string& fmt) { + apply_range_format(sheet_idx, CellRange{sheet_idx, row, col, row, col}, fmt); +} + +void Workbook::apply_range_format(int sheet_idx, CellRange range, const std::string& fmt) { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return; + int r1 = std::max(0, std::min(range.r1, range.r2)); + int r2 = std::min(kMaxRows - 1, std::max(range.r1, range.r2)); + int c1 = std::max(0, std::min(range.c1, range.c2)); + int c2 = std::min(kMaxCols - 1, std::max(range.c1, range.c2)); + if (static_cast(r2 - r1 + 1) * (c2 - c1 + 1) > 10000) return; + + std::vector deltas; + for (int r = r1; r <= r2; ++r) { + for (int c = c1; c <= c2; ++c) { + const Cell* existing = get_cell(sheet_idx, r, c); + std::string raw = existing ? existing->raw_input : ""; + std::string old_fmt = existing ? existing->number_format : ""; + if (old_fmt == fmt) continue; + + CellDelta d; + d.row = r; + d.col = c; + d.old_raw = raw; + d.old_fmt = old_fmt; + d.new_raw = raw; + d.new_fmt = fmt; + + if (raw.empty() && fmt.empty()) { + sheets_[static_cast(sheet_idx)].cells.erase(CellKey{r, c}); + } else { + Cell& cell = sheets_[static_cast(sheet_idx)].cells[CellKey{r, c}]; + cell.number_format = fmt; + } + deltas.push_back(std::move(d)); + } + } + if (!deltas.empty()) { + push_command(std::make_unique(sheet_idx, std::move(deltas))); + } +} + +void Workbook::rewrite_all_formulas(const std::string& target_sheet, + StructuralOp op, + int index, + int count, + const std::string& new_name) { + for (size_t si = 0; si < sheets_.size(); ++si) { + Sheet& s = sheets_[si]; + for (auto& [key, cell] : s.cells) { + if (!cell.raw_input.empty() && cell.raw_input[0] == '=') { + std::string updated = rewrite_formula_structural( + cell.raw_input, s.name, target_sheet, op, index, count, new_name); + if (updated != cell.raw_input) { + parse_cell_input(cell, updated); + } + } + } + } +} + +void Workbook::insert_rows(int sheet_idx, int row, int count) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || count <= 0) return; + auto before_sheets = sheets_; + int before_active = active_sheet_; + + Sheet& s = sheets_[static_cast(sheet_idx)]; + std::string target_name = s.name; + + std::unordered_map moved; + moved.reserve(s.cells.size()); + for (auto& [key, cell] : s.cells) { + int nr = (key.row >= row) ? (key.row + count) : key.row; + if (nr < kMaxRows) { + moved.emplace(CellKey{nr, key.col}, std::move(cell)); + } + } + s.cells = std::move(moved); + + std::unordered_map moved_h; + for (const auto& [r, h] : s.row_heights) { + int nr = (r >= row) ? (r + count) : r; + if (nr < kMaxRows) moved_h[nr] = h; + } + s.row_heights = std::move(moved_h); + + rewrite_all_formulas(target_name, StructuralOp::InsertRow, row, count); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); +} + +void Workbook::delete_rows(int sheet_idx, int row, int count) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || count <= 0) return; + auto before_sheets = sheets_; + int before_active = active_sheet_; + + Sheet& s = sheets_[static_cast(sheet_idx)]; + std::string target_name = s.name; + + std::unordered_map moved; + moved.reserve(s.cells.size()); + for (auto& [key, cell] : s.cells) { + if (key.row >= row && key.row < row + count) continue; + int nr = (key.row >= row + count) ? (key.row - count) : key.row; + moved.emplace(CellKey{nr, key.col}, std::move(cell)); + } + s.cells = std::move(moved); + + std::unordered_map moved_h; + for (const auto& [r, h] : s.row_heights) { + if (r >= row && r < row + count) continue; + int nr = (r >= row + count) ? (r - count) : r; + moved_h[nr] = h; + } + s.row_heights = std::move(moved_h); + + rewrite_all_formulas(target_name, StructuralOp::DeleteRow, row, count); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); +} + +void Workbook::insert_cols(int sheet_idx, int col, int count) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || count <= 0) return; + auto before_sheets = sheets_; + int before_active = active_sheet_; + + Sheet& s = sheets_[static_cast(sheet_idx)]; + std::string target_name = s.name; + + std::unordered_map moved; + moved.reserve(s.cells.size()); + for (auto& [key, cell] : s.cells) { + int nc = (key.col >= col) ? (key.col + count) : key.col; + if (nc < kMaxCols) { + moved.emplace(CellKey{key.row, nc}, std::move(cell)); + } + } + s.cells = std::move(moved); + + std::unordered_map moved_w; + for (const auto& [c, w] : s.col_widths) { + int nc = (c >= col) ? (c + count) : c; + if (nc < kMaxCols) moved_w[nc] = w; + } + s.col_widths = std::move(moved_w); + + rewrite_all_formulas(target_name, StructuralOp::InsertCol, col, count); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); +} + +void Workbook::delete_cols(int sheet_idx, int col, int count) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || count <= 0) return; + auto before_sheets = sheets_; + int before_active = active_sheet_; + + Sheet& s = sheets_[static_cast(sheet_idx)]; + std::string target_name = s.name; + + std::unordered_map moved; + moved.reserve(s.cells.size()); + for (auto& [key, cell] : s.cells) { + if (key.col >= col && key.col < col + count) continue; + int nc = (key.col >= col + count) ? (key.col - count) : key.col; + moved.emplace(CellKey{key.row, nc}, std::move(cell)); + } + s.cells = std::move(moved); + + std::unordered_map moved_w; + for (const auto& [c, w] : s.col_widths) { + if (c >= col && c < col + count) continue; + int nc = (c >= col + count) ? (c - count) : c; + moved_w[nc] = w; + } + s.col_widths = std::move(moved_w); + + rewrite_all_formulas(target_name, StructuralOp::DeleteCol, col, count); + dag_->rebuild(*this); + push_command(std::make_unique( + std::move(before_sheets), before_active, sheets_, active_sheet_)); +} + +void Workbook::set_col_width(int sheet_idx, int col, int width) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || col < 0 || col >= kMaxCols) return; + auto& cw = sheets_[static_cast(sheet_idx)].col_widths; + int old_w = cw.count(col) ? cw[col] : 0; + if (old_w == width) return; + if (width <= 0) cw.erase(col); + else cw[col] = width; + push_command(std::make_unique(sheet_idx, true, col, old_w, width)); +} + +int Workbook::get_col_width(int sheet_idx, int col, int default_width) const { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return default_width; + const auto& cw = sheets_[static_cast(sheet_idx)].col_widths; + auto it = cw.find(col); + return (it != cw.end() && it->second > 0) ? it->second : default_width; +} + +void Workbook::set_row_height(int sheet_idx, int row, int height) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || row < 0 || row >= kMaxRows) return; + auto& rh = sheets_[static_cast(sheet_idx)].row_heights; + int old_h = rh.count(row) ? rh[row] : 0; + if (old_h == height) return; + if (height <= 0) rh.erase(row); + else rh[row] = height; + push_command(std::make_unique(sheet_idx, false, row, old_h, height)); +} + +int Workbook::get_row_height(int sheet_idx, int row, int default_height) const { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return default_height; + const auto& rh = sheets_[static_cast(sheet_idx)].row_heights; + auto it = rh.find(row); + return (it != rh.end() && it->second > 0) ? it->second : default_height; +} + +const Cell* Workbook::get_cell(int sheet_idx, int row, int col) const { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return nullptr; + const Sheet& s = sheets_[static_cast(sheet_idx)]; + auto it = s.cells.find(CellKey{row, col}); + if (it == s.cells.end()) return nullptr; + return &it->second; +} + +Value Workbook::get_scalar_value(int sheet_idx, int row, int col) const { + const Cell* c = get_cell(sheet_idx, row, col); + if (c && !c->raw_input.empty()) { + if (c->value.is_array()) { + const auto& arr = c->value.as_array(); + if (arr && !arr->data.empty()) return arr->at(0, 0); + return Value::make_empty(); + } + return c->value; + } + return dag_->get_spill_value(*this, sheet_idx, row, col); +} + +std::string Workbook::get_formatted_value(int sheet_idx, int row, int col) const { + const Cell* c = get_cell(sheet_idx, row, col); + Value v = get_scalar_value(sheet_idx, row, col); + std::string fmt = c ? c->number_format : std::string{}; + return format_value(v, fmt); +} + +bool Workbook::is_spilled_cell(int sheet_idx, int row, int col) const { + return dag_->is_spilled_cell(sheet_idx, row, col); +} + +std::optional Workbook::get_spill_range(int sheet_idx, int row, int col) const { + return dag_->get_spill_range(sheet_idx, row, col); +} + +ClipboardGrid Workbook::copy_range(int sheet_idx, CellRange range, bool is_cut) const { + ClipboardGrid grid; + grid.src_sheet = sheet_idx; + grid.src_range = CellRange{ + sheet_idx, + std::min(range.r1, range.r2), + std::min(range.c1, range.c2), + std::max(range.r1, range.r2), + std::max(range.c1, range.c2), + }; + grid.is_cut = is_cut; + for (int r = grid.src_range.r1; r <= grid.src_range.r2; ++r) { + for (int c = grid.src_range.c1; c <= grid.src_range.c2; ++c) { + const Cell* cell = get_cell(sheet_idx, r, c); + ClipboardCell cc; + cc.dr = r - grid.src_range.r1; + cc.dc = c - grid.src_range.c1; + if (cell && !cell->raw_input.empty()) { + cc.raw_input = cell->raw_input; + cc.number_format = cell->number_format; + } else { + Value sv = get_scalar_value(sheet_idx, r, c); + if (!sv.is_empty()) { + auto s = to_string(sv); + cc.raw_input = std::holds_alternative(s) ? std::get(s) : ""; + } + } + cc.evaluated_value = get_scalar_value(sheet_idx, r, c); + grid.cells.push_back(std::move(cc)); + } + } + return grid; +} + +void Workbook::paste_range(int sheet_idx, + int dest_row, + int dest_col, + const ClipboardGrid& grid, + bool translate_refs) { + if (sheet_idx < 0 || sheet_idx >= sheet_count() || grid.cells.empty()) return; + int drow = dest_row - grid.src_range.r1; + int dcol = dest_col - grid.src_range.c1; + + std::vector edits; + if (grid.is_cut && grid.src_sheet == sheet_idx) { + for (int r = grid.src_range.r1; r <= grid.src_range.r2; ++r) { + for (int c = grid.src_range.c1; c <= grid.src_range.c2; ++c) { + edits.push_back(CellEdit{r, c, "", std::string{}}); + } + } + } + for (const auto& cc : grid.cells) { + int tr = dest_row + cc.dr; + int tc = dest_col + cc.dc; + if (tr < 0 || tr >= kMaxRows || tc < 0 || tc >= kMaxCols) continue; + std::string raw = cc.raw_input; + if (translate_refs && !raw.empty() && raw[0] == '=' && !grid.is_cut) { + raw = translate_formula_refs(raw, drow, dcol); + } + edits.push_back(CellEdit{tr, tc, std::move(raw), cc.number_format}); + } + apply_cell_edits(sheet_idx, edits); +} + +void Workbook::autofill_range(int sheet_idx, CellRange src, CellRange dst) { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return; + CellRange s{sheet_idx, std::min(src.r1, src.r2), std::min(src.c1, src.c2), + std::max(src.r1, src.r2), std::max(src.c1, src.c2)}; + CellRange d{sheet_idx, std::min(dst.r1, dst.r2), std::min(dst.c1, dst.c2), + std::max(dst.r1, dst.r2), std::max(dst.c1, dst.c2)}; + + bool vertical = (d.r1 < s.r1 || d.r2 > s.r2); + std::vector edits; + + if (vertical) { + int src_h = s.row_count(); + for (int c = d.c1; c <= d.c2; ++c) { + int sc = s.c1 + ((c - s.c1) % s.col_count() + s.col_count()) % s.col_count(); + // Check if source column slice is pure numeric trend with >= 2 cells + bool all_numeric = (src_h >= 2); + std::vector nums; + for (int r = s.r1; r <= s.r2 && all_numeric; ++r) { + const Cell* cell = get_cell(sheet_idx, r, sc); + if (!cell || (!cell->raw_input.empty() && cell->raw_input[0] == '=')) { + all_numeric = false; + break; + } + if (!cell || !cell->value.is_number()) { + all_numeric = false; + break; + } + nums.push_back(cell->value.as_number()); + } + double step = 0.0; + if (all_numeric && nums.size() >= 2) { + step = (nums.back() - nums.front()) / static_cast(nums.size() - 1); + } + + for (int r = d.r1; r <= d.r2; ++r) { + if (s.contains(sheet_idx, r, c)) continue; + if (all_numeric) { + double v = nums.front() + step * static_cast(r - s.r1); + const Cell* template_c = get_cell(sheet_idx, s.r1, sc); + auto str = to_string(Value::make_number(v)); + std::string raw = std::holds_alternative(str) ? std::get(str) : ""; + edits.push_back(CellEdit{r, c, std::move(raw), + template_c ? template_c->number_format : std::string{}}); + } else { + int off = ((r - s.r1) % src_h + src_h) % src_h; + int sr = s.r1 + off; + const Cell* src_c = get_cell(sheet_idx, sr, sc); + std::string raw = src_c ? src_c->raw_input : ""; + std::string fmt = src_c ? src_c->number_format : ""; + if (!raw.empty() && raw[0] == '=') { + raw = translate_formula_refs(raw, r - sr, c - sc); + } + edits.push_back(CellEdit{r, c, std::move(raw), std::move(fmt)}); + } + } + } + } else { + int src_w = s.col_count(); + for (int r = d.r1; r <= d.r2; ++r) { + int sr = s.r1 + ((r - s.r1) % s.row_count() + s.row_count()) % s.row_count(); + bool all_numeric = (src_w >= 2); + std::vector nums; + for (int c = s.c1; c <= s.c2 && all_numeric; ++c) { + const Cell* cell = get_cell(sheet_idx, sr, c); + if (!cell || (!cell->raw_input.empty() && cell->raw_input[0] == '=') || + !cell->value.is_number()) { + all_numeric = false; + break; + } + nums.push_back(cell->value.as_number()); + } + double step = 0.0; + if (all_numeric && nums.size() >= 2) { + step = (nums.back() - nums.front()) / static_cast(nums.size() - 1); + } + + for (int c = d.c1; c <= d.c2; ++c) { + if (s.contains(sheet_idx, r, c)) continue; + if (all_numeric) { + double v = nums.front() + step * static_cast(c - s.c1); + const Cell* template_c = get_cell(sheet_idx, sr, s.c1); + auto str = to_string(Value::make_number(v)); + std::string raw = std::holds_alternative(str) ? std::get(str) : ""; + edits.push_back(CellEdit{r, c, std::move(raw), + template_c ? template_c->number_format : std::string{}}); + } else { + int off = ((c - s.c1) % src_w + src_w) % src_w; + int sc = s.c1 + off; + const Cell* src_c = get_cell(sheet_idx, sr, sc); + std::string raw = src_c ? src_c->raw_input : ""; + std::string fmt = src_c ? src_c->number_format : ""; + if (!raw.empty() && raw[0] == '=') { + raw = translate_formula_refs(raw, r - sr, c - sc); + } + edits.push_back(CellEdit{r, c, std::move(raw), std::move(fmt)}); + } + } + } + } + + apply_cell_edits(sheet_idx, edits); +} + +void Workbook::replace_all_sheets(std::vector new_sheets, int active_sheet) { + if (new_sheets.empty()) { + Sheet s; + s.name = "Sheet1"; + new_sheets.push_back(std::move(s)); + } + sheets_ = std::move(new_sheets); + for (auto& s : sheets_) { + for (auto& [key, cell] : s.cells) { + parse_cell_input(cell, cell.raw_input); + } + } + active_sheet_ = std::clamp(active_sheet, 0, sheet_count() - 1); + clear_history(); + recalculate_all(); +} + +void Workbook::replace_sheet_cells(int sheet_idx, + std::unordered_map new_cells) { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return; + Sheet& s = sheets_[static_cast(sheet_idx)]; + s.cells = std::move(new_cells); + for (auto& [key, cell] : s.cells) { + parse_cell_input(cell, cell.raw_input); + } + clear_history(); + recalculate_all(); +} + +std::optional Workbook::get_used_bounds(int sheet_idx) const { + if (sheet_idx < 0 || sheet_idx >= sheet_count()) return std::nullopt; + const Sheet& s = sheets_[static_cast(sheet_idx)]; + bool any = false; + int max_r = 0; + int max_c = 0; + for (const auto& [key, cell] : s.cells) { + if (cell.raw_input.empty() && cell.value.is_empty()) continue; + any = true; + max_r = std::max(max_r, key.row); + max_c = std::max(max_c, key.col); + } + for (const auto& [origin, sr] : dag_->spill_ranges()) { + if (origin.sheet == sheet_idx) { + any = true; + max_r = std::max(max_r, sr.r2); + max_c = std::max(max_c, sr.c2); + } + } + if (!any) return std::nullopt; + return CellRange{sheet_idx, 0, 0, max_r, max_c}; +} + +void Workbook::recalculate_all() { + dag_->rebuild(*this); +} + +} // namespace htab diff --git a/engine/workbook.hpp b/engine/workbook.hpp new file mode 100644 index 0000000..e930574 --- /dev/null +++ b/engine/workbook.hpp @@ -0,0 +1,150 @@ +#pragma once + +#include "engine/address.hpp" +#include "engine/parser.hpp" +#include "engine/value.hpp" + +#include +#include +#include +#include +#include + +namespace htab { + +class DependencyGraph; + +struct Cell { + std::string raw_input; + std::string number_format; + Value value; + std::shared_ptr ast; + bool parse_error = false; +}; + +struct Sheet { + std::string name; + std::unordered_map cells; + std::unordered_map col_widths; + std::unordered_map row_heights; +}; + +struct CellEdit { + int row = 0; + int col = 0; + std::string raw_input; + std::optional number_format; +}; + +struct ClipboardCell { + int dr = 0; + int dc = 0; + std::string raw_input; + std::string number_format; + Value evaluated_value; +}; + +struct ClipboardGrid { + int src_sheet = 0; + CellRange src_range; + std::vector cells; + bool is_cut = false; +}; + +class Workbook { + public: + struct Command { + virtual ~Command() = default; + virtual void undo(Workbook& wb) = 0; + virtual void redo(Workbook& wb) = 0; + }; + + Workbook(); + ~Workbook(); + Workbook(Workbook&&) noexcept; + Workbook& operator=(Workbook&&) noexcept; + Workbook(const Workbook&) = delete; + Workbook& operator=(const Workbook&) = delete; + + int sheet_count() const { return static_cast(sheets_.size()); } + int active_sheet() const { return active_sheet_; } + void set_active_sheet(int idx); + + const Sheet& sheet(int idx) const { return sheets_[static_cast(idx)]; } + Sheet& sheet_mut(int idx) { return sheets_[static_cast(idx)]; } + + int find_sheet(std::string_view name) const; + int add_sheet(std::string name = ""); + bool rename_sheet(int sheet_idx, const std::string& new_name); + bool delete_sheet(int sheet_idx); + + void set_cell_input(int sheet_idx, int row, int col, const std::string& raw); + void apply_cell_edits(int sheet_idx, const std::vector& edits); + void set_cell_format(int sheet_idx, int row, int col, const std::string& fmt); + void apply_range_format(int sheet_idx, CellRange range, const std::string& fmt); + + void insert_rows(int sheet_idx, int row, int count = 1); + void delete_rows(int sheet_idx, int row, int count = 1); + void insert_cols(int sheet_idx, int col, int count = 1); + void delete_cols(int sheet_idx, int col, int count = 1); + + void set_col_width(int sheet_idx, int col, int width); + int get_col_width(int sheet_idx, int col, int default_width) const; + void set_row_height(int sheet_idx, int row, int height); + int get_row_height(int sheet_idx, int row, int default_height) const; + + bool can_undo() const { return !undo_stack_.empty(); } + bool can_redo() const { return !redo_stack_.empty(); } + bool undo(); + bool redo(); + void clear_history(); + + const Cell* get_cell(int sheet_idx, int row, int col) const; + Value get_scalar_value(int sheet_idx, int row, int col) const; + std::string get_formatted_value(int sheet_idx, int row, int col) const; + + bool is_spilled_cell(int sheet_idx, int row, int col) const; + std::optional get_spill_range(int sheet_idx, int row, int col) const; + + ClipboardGrid copy_range(int sheet_idx, CellRange range, bool is_cut = false) const; + void paste_range(int sheet_idx, + int dest_row, + int dest_col, + const ClipboardGrid& grid, + bool translate_refs = true); + void autofill_range(int sheet_idx, CellRange src, CellRange dst); + + void replace_all_sheets(std::vector new_sheets, int active_sheet); + void replace_sheet_cells(int sheet_idx, + std::unordered_map new_cells); + std::optional get_used_bounds(int sheet_idx) const; + void recalculate_all(); + + const DependencyGraph& dag() const { return *dag_; } + + private: + friend class EditCellsCmd; + friend class SnapshotCmd; + + void parse_cell_input(Cell& cell, const std::string& raw); + void set_cell_raw_no_recalc(int sheet_idx, + int row, + int col, + const std::string& raw, + const std::optional& fmt_override, + std::vector& dirty_seeds); + void push_command(std::unique_ptr cmd); + void rewrite_all_formulas(const std::string& target_sheet, + StructuralOp op, + int index, + int count, + const std::string& new_name = ""); + + std::vector sheets_; + int active_sheet_ = 0; + std::unique_ptr dag_; + std::vector> undo_stack_; + std::vector> redo_stack_; +}; + +} // namespace htab diff --git a/libgemui b/libgemui new file mode 160000 index 0000000..fab6a60 --- /dev/null +++ b/libgemui @@ -0,0 +1 @@ +Subproject commit fab6a60459eb9389fb29b21013cbfff3a3f43c1d diff --git a/tests/test_framework.hpp b/tests/test_framework.hpp new file mode 100644 index 0000000..5ce62a7 --- /dev/null +++ b/tests/test_framework.hpp @@ -0,0 +1,79 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +namespace htab::test { + +struct TestCase { + std::string name; + std::function fn; +}; + +inline std::vector& registry() { + static std::vector tests; + return tests; +} + +inline int& failures_in_current_test() { + static int count = 0; + return count; +} + +struct Registrar { + Registrar(const char* name, std::function fn) { + registry().push_back({name, std::move(fn)}); + } +}; + +inline void report_fail(const char* file, int line, const std::string& msg) { + ++failures_in_current_test(); + std::cerr << " FAIL " << file << ":" << line << ": " << msg << "\n"; +} + +} // namespace htab::test + +#define HTAB_CONCAT_INNER(a, b) a##b +#define HTAB_CONCAT(a, b) HTAB_CONCAT_INNER(a, b) + +#define TEST_CASE(name) \ + static void HTAB_CONCAT(htab_test_fn_, __LINE__)(); \ + static ::htab::test::Registrar HTAB_CONCAT(htab_test_reg_, __LINE__)( \ + name, HTAB_CONCAT(htab_test_fn_, __LINE__)); \ + static void HTAB_CONCAT(htab_test_fn_, __LINE__)() + +#define CHECK(cond) \ + do { \ + if (!(cond)) { \ + ::htab::test::report_fail(__FILE__, __LINE__, "Condition failed: " #cond); \ + } \ + } while (false) + +#define CHECK_EQ(a, b) \ + do { \ + auto htab_a_ = (a); \ + auto htab_b_ = (b); \ + if (!(htab_a_ == htab_b_)) { \ + std::ostringstream oss_; \ + oss_ << "Expected " << #a << " == " << #b << " (got " << htab_a_ << " vs " \ + << htab_b_ << ")"; \ + ::htab::test::report_fail(__FILE__, __LINE__, oss_.str()); \ + } \ + } while (false) + +#define CHECK_NEAR(a, b, eps) \ + do { \ + double htab_a_ = static_cast(a); \ + double htab_b_ = static_cast(b); \ + double htab_eps_ = static_cast(eps); \ + if (!(std::fabs(htab_a_ - htab_b_) <= htab_eps_)) { \ + std::ostringstream oss_; \ + oss_ << "Expected " << #a << " ~= " << #b << " (got " << htab_a_ << " vs " \ + << htab_b_ << ")"; \ + ::htab::test::report_fail(__FILE__, __LINE__, oss_.str()); \ + } \ + } while (false) diff --git a/tests/test_main.cpp b/tests/test_main.cpp new file mode 100644 index 0000000..46f8e3b --- /dev/null +++ b/tests/test_main.cpp @@ -0,0 +1,21 @@ +#include "tests/test_framework.hpp" + +#include + +int main() { + int total = 0; + int failed = 0; + for (const auto& tc : htab::test::registry()) { + ++total; + htab::test::failures_in_current_test() = 0; + tc.fn(); + if (htab::test::failures_in_current_test() > 0) { + ++failed; + std::cerr << "[FAIL] " << tc.name << "\n"; + } else { + std::cout << "[PASS] " << tc.name << "\n"; + } + } + std::cout << "Summary: " << (total - failed) << "/" << total << " tests passed.\n"; + return failed == 0 ? 0 : 1; +} diff --git a/tests/test_phase1.cpp b/tests/test_phase1.cpp new file mode 100644 index 0000000..6055571 --- /dev/null +++ b/tests/test_phase1.cpp @@ -0,0 +1,208 @@ +#include "tests/test_framework.hpp" + +#include "engine/address.hpp" +#include "engine/format.hpp" +#include "engine/lexer.hpp" +#include "engine/parser.hpp" +#include "engine/value.hpp" +#include "engine/workbook.hpp" + +#include + +using namespace htab; + +namespace { + +Value eval_expr(Workbook& wb, const std::string& formula, int sheet = 0) { + wb.set_cell_input(sheet, 99, 25, formula); + return wb.get_scalar_value(sheet, 99, 25); +} + +} // namespace + +TEST_CASE("Phase1: Operator precedence and spreadsheet quirks") { + Workbook wb; + Value v1 = eval_expr(wb, "=-2^2"); + CHECK(v1.is_number()); + CHECK_NEAR(v1.as_number(), 4.0, 1e-12); + + Value v2 = eval_expr(wb, "=0-2^2"); + CHECK(v2.is_number()); + CHECK_NEAR(v2.as_number(), -4.0, 1e-12); + + Value v3 = eval_expr(wb, "=2^3^2"); + CHECK(v3.is_number()); + CHECK_NEAR(v3.as_number(), 64.0, 1e-12); + + Value v4 = eval_expr(wb, "=2^-3"); + CHECK(v4.is_number()); + CHECK_NEAR(v4.as_number(), 0.125, 1e-12); + + Value v5 = eval_expr(wb, "=50%"); + CHECK(v5.is_number()); + CHECK_NEAR(v5.as_number(), 0.5, 1e-12); + + Value v6 = eval_expr(wb, "=-2%"); + CHECK(v6.is_number()); + CHECK_NEAR(v6.as_number(), -0.02, 1e-12); + + Value v7 = eval_expr(wb, "=1+2*3-4/2"); + CHECK(v7.is_number()); + CHECK_NEAR(v7.as_number(), 5.0, 1e-12); + + Value v8 = eval_expr(wb, "=(1+2)*3^2"); + CHECK(v8.is_number()); + CHECK_NEAR(v8.as_number(), 27.0, 1e-12); + + Value v9 = eval_expr(wb, "=\"a\" & \"b\" & 12"); + CHECK(v9.is_string()); + CHECK_EQ(v9.as_string(), std::string("ab12")); + + Value v10 = eval_expr(wb, "=\"Hello\"=\"hello\""); + CHECK(v10.is_bool()); + CHECK(v10.as_bool()); + + Value v11 = eval_expr(wb, "=1 < \"a\""); + CHECK(v11.is_bool()); + CHECK(v11.as_bool()); + + Value v12 = eval_expr(wb, "=\"z\" < TRUE"); + CHECK(v12.is_bool()); + CHECK(v12.as_bool()); +} + +TEST_CASE("Phase1: Type coercion and error propagation") { + Workbook wb; + wb.set_cell_input(0, 0, 0, "10"); // A1 + wb.set_cell_input(0, 1, 0, "\"x\""); // A2 string literal with quote? Wait: raw text without = is literal string + wb.set_cell_input(0, 1, 0, "hello"); // A2 + wb.set_cell_input(0, 2, 0, "TRUE"); // A3 + wb.set_cell_input(0, 3, 0, "50%"); // A4 + wb.set_cell_input(0, 4, 0, "'007"); // A5 + + CHECK(wb.get_scalar_value(0, 0, 0).is_number()); + CHECK_NEAR(wb.get_scalar_value(0, 0, 0).as_number(), 10.0, 1e-12); + CHECK(wb.get_scalar_value(0, 1, 0).is_string()); + CHECK_EQ(wb.get_scalar_value(0, 1, 0).as_string(), std::string("hello")); + CHECK(wb.get_scalar_value(0, 2, 0).is_bool()); + CHECK(wb.get_scalar_value(0, 2, 0).as_bool()); + CHECK(wb.get_scalar_value(0, 3, 0).is_number()); + CHECK_NEAR(wb.get_scalar_value(0, 3, 0).as_number(), 0.5, 1e-12); + CHECK(wb.get_scalar_value(0, 4, 0).is_string()); + CHECK_EQ(wb.get_scalar_value(0, 4, 0).as_string(), std::string("007")); + + // Bool and string coercion in arithmetic + Value b_add = eval_expr(wb, "=A3 + 5"); + CHECK_NEAR(b_add.as_number(), 6.0, 1e-12); + + Value s_num = eval_expr(wb, "=\"25%\" + 1"); + CHECK_NEAR(s_num.as_number(), 1.25, 1e-12); + + Value s_bad = eval_expr(wb, "=A2 + 1"); + CHECK(s_bad.is_error()); + CHECK(s_bad.as_error() == ErrorCode::Value); + + // Empty cell coerces to 0 in arithmetic, "" in concat, false in comparison + Value e_add = eval_expr(wb, "=Z1 + 4"); + CHECK_NEAR(e_add.as_number(), 4.0, 1e-12); + + Value e_cmp = eval_expr(wb, "=Z1 = 0"); + CHECK(e_cmp.is_bool() && e_cmp.as_bool()); + + // Error propagation + Value div0 = eval_expr(wb, "=10/0 + 5"); + CHECK(div0.is_error() && div0.as_error() == ErrorCode::Div0); + + Value unk = eval_expr(wb, "=UNKNOWNFN(1) + 2"); + CHECK(unk.is_error() && unk.as_error() == ErrorCode::Name); + + Value ident = eval_expr(wb, "=BADNAME"); + CHECK(ident.is_error() && ident.as_error() == ErrorCode::Name); + + // Short-circuit IF ignores error in untaken branch + Value sc_if = eval_expr(wb, "=IF(TRUE, 42, 1/0)"); + CHECK(sc_if.is_number()); + CHECK_NEAR(sc_if.as_number(), 42.0, 1e-12); +} + +TEST_CASE("Phase1: Addressing, cross-sheet refs, range intersection and union") { + CHECK_EQ(col_to_letters(0), std::string("A")); + CHECK_EQ(col_to_letters(25), std::string("Z")); + CHECK_EQ(col_to_letters(26), std::string("AA")); + CHECK_EQ(col_to_letters(701), std::string("ZZ")); + CHECK_EQ(col_to_letters(702), std::string("AAA")); + CHECK_EQ(letters_to_col("A"), 0); + CHECK_EQ(letters_to_col("xfd"), 16383); + CHECK_EQ(letters_to_col("XFE"), -1); + + auto ref = parse_cell_ref("'My Sheet'!$C$12"); + CHECK(ref.has_value()); + CHECK_EQ(ref->sheet_name, std::string("My Sheet")); + CHECK_EQ(ref->col, 2); + CHECK_EQ(ref->row, 11); + CHECK(ref->abs_col && ref->abs_row); + CHECK_EQ(format_cell_ref(*ref), std::string("'My Sheet'!$C$12")); + + // Disambiguation: LOG10(100) must tokenize LOG10 as Ident, not CellRef! + auto toks = Lexer::tokenize("=LOG10(100)"); + CHECK(toks.size() >= 2); + CHECK(toks[0].kind == TokenKind::Ident); + CHECK_EQ(toks[0].text, std::string("LOG10")); + + Workbook wb; + int s2 = wb.add_sheet("My Sheet"); + // Populate Sheet1 A1:C3 with values 1..9 + int val = 1; + for (int r = 0; r < 3; ++r) { + for (int c = 0; c < 3; ++c) { + wb.set_cell_input(0, r, c, std::to_string(val++)); + } + } + wb.set_cell_input(s2, 0, 0, "100"); + wb.set_cell_input(s2, 1, 0, "200"); + + Value cs = eval_expr(wb, "='My Sheet'!A1 + SUM('My Sheet'!A1:A2)"); + CHECK(cs.is_number()); + CHECK_NEAR(cs.as_number(), 400.0, 1e-12); + + // Intersection: A1:B3 B2:C3 => B2:B3 (values 5 and 8 -> sum 13) + Value inter = eval_expr(wb, "=SUM(A1:B3 B2:C3)"); + CHECK(inter.is_number()); + CHECK_NEAR(inter.as_number(), 13.0, 1e-12); + + // Union inside parens: SUM((A1:A2, C1:C2)) => 1+4 + 3+6 = 14 + Value uni = eval_expr(wb, "=SUM((A1:A2, C1:C2))"); + CHECK(uni.is_number()); + CHECK_NEAR(uni.as_number(), 14.0, 1e-12); + + // Non-existent sheet => #REF! + Value bad_sheet = eval_expr(wb, "=NoSuchSheet!A1"); + CHECK(bad_sheet.is_error() && bad_sheet.as_error() == ErrorCode::Ref); +} + +TEST_CASE("Phase1: Calendar serials and number formatting") { + int s = ymd_to_serial(2024, 2, 29); + int y = 0, m = 0, d = 0; + serial_to_ymd(s, y, m, d); + CHECK_EQ(y, 2024); + CHECK_EQ(m, 2); + CHECK_EQ(d, 29); + + // Month/day rollover + int s_roll = ymd_to_serial(2024, 13, 1); + serial_to_ymd(s_roll, y, m, d); + CHECK_EQ(y, 2025); + CHECK_EQ(m, 1); + CHECK_EQ(d, 1); + + CHECK_EQ(format_value(Value::make_number(1234.5), "$#,##0.00"), std::string("$1,234.50")); + CHECK_EQ(format_value(Value::make_number(-0.255), "0.00%"), std::string("-25.50%")); + CHECK_EQ(format_value(Value::make_number(static_cast(s)), "yyyy-mm-dd"), + std::string("2024-02-29")); + + int hh = 0, mm = 0, ss = 0; + serial_to_hms(0.5, hh, mm, ss); + CHECK_EQ(hh, 12); + CHECK_EQ(mm, 0); + CHECK_EQ(ss, 0); +} diff --git a/tests/test_phase2.cpp b/tests/test_phase2.cpp new file mode 100644 index 0000000..fc6b893 --- /dev/null +++ b/tests/test_phase2.cpp @@ -0,0 +1,177 @@ +#include "tests/test_framework.hpp" + +#include "engine/address.hpp" +#include "engine/workbook.hpp" + +using namespace htab; + +TEST_CASE("Phase2: Incremental DAG recalculation and cycle detection") { + Workbook wb; + wb.set_cell_input(0, 0, 0, "5"); // A1 + wb.set_cell_input(0, 1, 0, "=A1 * 2"); // A2 = 10 + wb.set_cell_input(0, 2, 0, "=A1 + A2"); // A3 = 15 (diamond) + wb.set_cell_input(0, 3, 0, "=A3 * 10"); // A4 = 150 + + CHECK_NEAR(wb.get_scalar_value(0, 3, 0).as_number(), 150.0, 1e-12); + + wb.set_cell_input(0, 0, 0, "10"); // A1 = 10 => A2=20, A3=30, A4=300 + CHECK_NEAR(wb.get_scalar_value(0, 1, 0).as_number(), 20.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 2, 0).as_number(), 30.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 3, 0).as_number(), 300.0, 1e-12); + + // Direct self-cycle + wb.set_cell_input(0, 0, 1, "=B1"); + CHECK(wb.get_scalar_value(0, 0, 1).is_error()); + CHECK(wb.get_scalar_value(0, 0, 1).as_error() == ErrorCode::Cycle); + + // Multi-node cycle: C1 -> D1 -> E1 -> C1 and downstream F1 = E1 + 1 + wb.set_cell_input(0, 0, 2, "=E1 + 1"); // C1 + wb.set_cell_input(0, 0, 3, "=C1 + 1"); // D1 + wb.set_cell_input(0, 0, 4, "=D1 + 1"); // E1 + wb.set_cell_input(0, 0, 5, "=E1 + 10"); // F1 (downstream of cycle) + wb.set_cell_input(0, 0, 6, "=IF(FALSE, E1, 99)"); // G1 (short-circuits past cycle) + + CHECK(wb.get_scalar_value(0, 0, 2).as_error() == ErrorCode::Cycle); + CHECK(wb.get_scalar_value(0, 0, 3).as_error() == ErrorCode::Cycle); + CHECK(wb.get_scalar_value(0, 0, 4).as_error() == ErrorCode::Cycle); + CHECK(wb.get_scalar_value(0, 0, 5).as_error() == ErrorCode::Cycle); + CHECK(wb.get_scalar_value(0, 0, 6).is_number()); + CHECK_NEAR(wb.get_scalar_value(0, 0, 6).as_number(), 99.0, 1e-12); + + // Break cycle + wb.set_cell_input(0, 0, 2, "100"); + CHECK_NEAR(wb.get_scalar_value(0, 0, 3).as_number(), 101.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 0, 4).as_number(), 102.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 0, 5).as_number(), 112.0, 1e-12); +} + +TEST_CASE("Phase2: Structural row/col edits, sheet ops, and Undo/Redo") { + Workbook wb; + wb.set_cell_input(0, 0, 0, "10"); // A1 + wb.set_cell_input(0, 1, 0, "20"); // A2 + wb.set_cell_input(0, 2, 0, "30"); // A3 + wb.set_cell_input(0, 3, 0, "=SUM(A1:A3)"); // A4 = 60 + wb.set_cell_input(0, 4, 0, "=$A$2 + A3"); // A5 = 50 + + int s2 = wb.add_sheet("Data"); + wb.set_cell_input(s2, 0, 0, "=Sheet1!$A$2 + SUM(Sheet1!A1:A3)"); // 20 + 60 = 80 + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 80.0, 1e-12); + + // Insert row inside A1:A3 (at index 1, before row 2) -> A1:A3 expands to A1:A4 + wb.insert_rows(0, 1, 1); + // Old A2 shifted to A3; A4 shifted to A5; A5 shifted to A6 + CHECK_EQ(wb.get_cell(0, 4, 0)->raw_input, std::string("=SUM(A1:A4)")); + CHECK_EQ(wb.get_cell(0, 5, 0)->raw_input, std::string("=$A$3 + A4")); + CHECK_EQ(wb.get_cell(s2, 0, 0)->raw_input, + std::string("=Sheet1!$A$3 + SUM(Sheet1!A1:A4)")); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 80.0, 1e-12); + + // Set newly inserted A2 = 5 -> sums update to 65 and Data!A1 = 85 + wb.set_cell_input(0, 1, 0, "5"); + CHECK_NEAR(wb.get_scalar_value(0, 4, 0).as_number(), 65.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 85.0, 1e-12); + + // Delete row 2 (index 2, which holds 20 and is referenced directly by $A$3!) + wb.delete_rows(0, 2, 1); + CHECK_EQ(wb.get_cell(0, 3, 0)->raw_input, std::string("=SUM(A1:A3)")); + CHECK_EQ(wb.get_cell(0, 4, 0)->raw_input, std::string("=#REF! + A3")); + CHECK(wb.get_scalar_value(0, 4, 0).is_error()); + CHECK(wb.get_scalar_value(0, 4, 0).as_error() == ErrorCode::Ref); + CHECK(wb.get_scalar_value(s2, 0, 0).as_error() == ErrorCode::Ref); + + // Undo row deletion restores #REF! formula back to exact working formula + CHECK(wb.undo()); + CHECK_EQ(wb.get_cell(0, 5, 0)->raw_input, std::string("=$A$3 + A4")); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 85.0, 1e-12); + + // Redo re-applies deletion + CHECK(wb.redo()); + CHECK(wb.get_scalar_value(0, 4, 0).as_error() == ErrorCode::Ref); + + // Undo back to clean state, test column insert/delete and sheet rename/delete + CHECK(wb.undo()); + CHECK(wb.rename_sheet(0, "Main Sheet")); + CHECK_EQ(wb.get_cell(s2, 0, 0)->raw_input, + std::string("='Main Sheet'!$A$3 + SUM('Main Sheet'!A1:A4)")); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 85.0, 1e-12); + + // Insert column at index 0 on Main Sheet -> A becomes B + wb.insert_cols(0, 0, 1); + CHECK_EQ(wb.get_cell(s2, 0, 0)->raw_input, + std::string("='Main Sheet'!$B$3 + SUM('Main Sheet'!B1:B4)")); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 85.0, 1e-12); + + // Delete entire range B1:B4 by deleting col B -> range becomes #REF! + wb.delete_cols(0, 1, 1); + CHECK(wb.get_scalar_value(s2, 0, 0).as_error() == ErrorCode::Ref); + CHECK(wb.undo()); + CHECK_NEAR(wb.get_scalar_value(s2, 0, 0).as_number(), 85.0, 1e-12); + + // Delete Main Sheet -> Data!A1 becomes #REF! + CHECK(wb.delete_sheet(0)); + CHECK_EQ(wb.sheet_count(), 1); + CHECK(wb.get_scalar_value(0, 0, 0).as_error() == ErrorCode::Ref); + CHECK(wb.undo()); + CHECK_EQ(wb.sheet_count(), 2); + CHECK_NEAR(wb.get_scalar_value(1, 0, 0).as_number(), 85.0, 1e-12); +} + +TEST_CASE("Phase2: Copy/paste relative anchors and autofill") { + Workbook wb; + wb.set_cell_input(0, 0, 0, "2"); + wb.set_cell_input(0, 1, 0, "4"); + wb.set_cell_input(0, 0, 1, "10"); + wb.set_cell_input(0, 1, 1, "20"); + wb.set_cell_input(0, 0, 2, "=A1 + $A$1 + $B1 + B$1"); + + auto clip = wb.copy_range(0, CellRange{0, 0, 2, 0, 2}); + wb.paste_range(0, 1, 3, clip, true); // Paste at D2 (drow=1, dcol=1) + // A1 -> B2, $A$1 -> $A$1, $B1 -> $B2, B$1 -> C$1 + CHECK_EQ(wb.get_cell(0, 1, 3)->raw_input, std::string("=B2 + $A$1 + $B2 + C$1")); + + // Autofill numeric series A1:A2 (2, 4) -> A1:A5 (2, 4, 6, 8, 10) + wb.autofill_range(0, CellRange{0, 0, 0, 1, 0}, CellRange{0, 0, 0, 4, 0}); + CHECK_NEAR(wb.get_scalar_value(0, 2, 0).as_number(), 6.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 3, 0).as_number(), 8.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 4, 0).as_number(), 10.0, 1e-12); +} + +TEST_CASE("Phase2: Dynamic array spilling, blocking, unblocking, and downstream DAG") { + Workbook wb; + wb.set_cell_input(0, 0, 0, "1"); + wb.set_cell_input(0, 1, 0, "2"); + wb.set_cell_input(0, 2, 0, "3"); + + // Put blocker in B2 before entering spill formula in B1 + wb.set_cell_input(0, 1, 1, "BLOCKER"); + wb.set_cell_input(0, 0, 1, "=A1:A3 * 10"); + + // B1 must be #SPILL!, B2 must still preserve "BLOCKER" + CHECK(wb.get_scalar_value(0, 0, 1).is_error()); + CHECK(wb.get_scalar_value(0, 0, 1).as_error() == ErrorCode::Spill); + CHECK_EQ(wb.get_scalar_value(0, 1, 1).as_string(), std::string("BLOCKER")); + + // Downstream formula referencing B1:B3 + wb.set_cell_input(0, 0, 2, "=SUM(B1:B3)"); // C1 + + // Clear blocker in B2 -> B1 must automatically spill 10, 20, 30 and C1 must become 60! + wb.set_cell_input(0, 1, 1, ""); + CHECK(wb.get_scalar_value(0, 0, 1).is_number()); + CHECK_NEAR(wb.get_scalar_value(0, 0, 1).as_number(), 10.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 1, 1).as_number(), 20.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 2, 1).as_number(), 30.0, 1e-12); + CHECK(wb.is_spilled_cell(0, 1, 1)); + CHECK(wb.is_spilled_cell(0, 2, 1)); + CHECK_NEAR(wb.get_scalar_value(0, 0, 2).as_number(), 60.0, 1e-12); + + // Edit A2 from 2 to 5 -> B2 updates to 50 and C1 updates to 90 + wb.set_cell_input(0, 1, 0, "5"); + CHECK_NEAR(wb.get_scalar_value(0, 1, 1).as_number(), 50.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 0, 2).as_number(), 90.0, 1e-12); + + // Typing into spilled cell B3 triggers #SPILL! on B1 and preserves user's value in B3 + wb.set_cell_input(0, 2, 1, "999"); + CHECK(wb.get_scalar_value(0, 0, 1).as_error() == ErrorCode::Spill); + CHECK_NEAR(wb.get_scalar_value(0, 2, 1).as_number(), 999.0, 1e-12); + CHECK(!wb.is_spilled_cell(0, 1, 1)); +} diff --git a/tests/test_phase3.cpp b/tests/test_phase3.cpp new file mode 100644 index 0000000..9bc3643 --- /dev/null +++ b/tests/test_phase3.cpp @@ -0,0 +1,268 @@ +#include "tests/test_framework.hpp" + +#include "engine/functions/registry.hpp" +#include "engine/workbook.hpp" + +#include +#include + +using namespace htab; + +namespace { + +Value eval(Workbook& wb, const std::string& formula, int sheet = 0) { + wb.set_cell_input(sheet, 200, 50, formula); + return wb.get_scalar_value(sheet, 200, 50); +} + +} // namespace + +TEST_CASE("Phase3: Registry contains all 100 required functions") { + const auto& reg = FunctionRegistry::instance(); + CHECK_EQ(reg.registered_count(), static_cast(100)); + + static constexpr const char* kAll100[] = { + // Math & Trig (27) + "ABS", "ACOS", "ASIN", "ATAN", "ATAN2", "COS", "DEGREES", "EXP", "FACT", + "INT", "LN", "LOG", "LOG10", "MOD", "PI", "POWER", "PRODUCT", "RADIANS", + "RAND", "ROUND", "SIN", "SQRT", "SUM", "SUMIF", "SUMIFS", "TAN", "TRUNC", + // Logical (6) + "AND", "FALSE", "IF", "NOT", "OR", "TRUE", + // Statistical (12) + "AVERAGE", "COUNT", "COUNTA", "COUNTBLANK", "COUNTIF", "COUNTIFS", + "MAX", "MIN", "STDEV", "STDEVP", "VAR", "VARP", + // Lookup & Reference (8) + "CHOOSE", "COLUMNS", "FILTER", "HLOOKUP", "INDEX", "MATCH", "ROWS", "VLOOKUP", + // Text (14) + "EXACT", "FIND", "LEFT", "LEN", "LOWER", "MID", "PROPER", "REPLACE", + "REPT", "RIGHT", "SUBSTITUTE", "T", "TRIM", "UPPER", + // Date & Time (11) + "DATE", "DATEVALUE", "DAY", "HOUR", "MINUTE", "MONTH", "NOW", "SECOND", + "TIME", "TIMEVALUE", "YEAR", + // Financial (10) + "DDB", "FV", "IRR", "NPER", "NPV", "PMT", "PV", "RATE", "SLN", "SYD", + // Database (12) + "DAVERAGE", "DCOUNT", "DCOUNTA", "DGET", "DMAX", "DMIN", + "DPRODUCT", "DSTDEV", "DSTDEVP", "DSUM", "DVAR", "DVARP", + }; + CHECK_EQ(sizeof(kAll100) / sizeof(kAll100[0]), static_cast(100)); + for (const char* name : kAll100) { + CHECK(reg.find(name) != nullptr); + } +} + +TEST_CASE("Phase3: Math & Trig (all 27 functions)") { + Workbook wb; + CHECK_NEAR(eval(wb, "=ABS(-7.5)").as_number(), 7.5, 1e-12); + CHECK_NEAR(eval(wb, "=ACOS(0.5)").as_number(), std::acos(0.5), 1e-12); + CHECK_NEAR(eval(wb, "=ASIN(0.5)").as_number(), std::asin(0.5), 1e-12); + CHECK_NEAR(eval(wb, "=ATAN(1)").as_number(), std::atan(1.0), 1e-12); + CHECK_NEAR(eval(wb, "=ATAN2(1, 0)").as_number(), 0.0, 1e-12); + CHECK_NEAR(eval(wb, "=ATAN2(0, 1)").as_number(), std::atan2(1.0, 0.0), 1e-12); + CHECK(eval(wb, "=ATAN2(0, 0)").as_error() == ErrorCode::Div0); + CHECK_NEAR(eval(wb, "=COS(0)").as_number(), 1.0, 1e-12); + CHECK_NEAR(eval(wb, "=DEGREES(PI())").as_number(), 180.0, 1e-12); + CHECK_NEAR(eval(wb, "=EXP(1)").as_number(), std::exp(1.0), 1e-12); + CHECK_NEAR(eval(wb, "=FACT(5)").as_number(), 120.0, 1e-12); + CHECK_NEAR(eval(wb, "=INT(-8.9)").as_number(), -9.0, 1e-12); + CHECK_NEAR(eval(wb, "=LN(EXP(2))").as_number(), 2.0, 1e-12); + CHECK_NEAR(eval(wb, "=LOG(8, 2)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=LOG10(1000)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=MOD(-3, 2)").as_number(), 1.0, 1e-12); + CHECK_NEAR(eval(wb, "=PI()").as_number(), 3.14159265358979323846, 1e-12); + CHECK_NEAR(eval(wb, "=POWER(2, 10)").as_number(), 1024.0, 1e-12); + CHECK_NEAR(eval(wb, "=PRODUCT(2, 3, 4)").as_number(), 24.0, 1e-12); + CHECK_NEAR(eval(wb, "=RADIANS(180)").as_number(), 3.14159265358979323846, 1e-12); + Value rnd = eval(wb, "=RAND()"); + CHECK(rnd.is_number() && rnd.as_number() >= 0.0 && rnd.as_number() < 1.0); + CHECK_NEAR(eval(wb, "=ROUND(2.5, 0)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=ROUND(-2.5, 0)").as_number(), -3.0, 1e-12); + CHECK_NEAR(eval(wb, "=ROUND(1234, -2)").as_number(), 1200.0, 1e-12); + CHECK_NEAR(eval(wb, "=SIN(PI()/2)").as_number(), 1.0, 1e-12); + CHECK_NEAR(eval(wb, "=SQRT(81)").as_number(), 9.0, 1e-12); + CHECK(eval(wb, "=SQRT(-1)").as_error() == ErrorCode::Num); + CHECK_NEAR(eval(wb, "=TAN(0)").as_number(), 0.0, 1e-12); + CHECK_NEAR(eval(wb, "=TRUNC(-8.95, 1)").as_number(), -8.9, 1e-12); + + // SUM, SUMIF, SUMIFS + wb.set_cell_input(0, 0, 0, "East"); wb.set_cell_input(0, 0, 1, "10"); wb.set_cell_input(0, 0, 2, "100"); + wb.set_cell_input(0, 1, 0, "West"); wb.set_cell_input(0, 1, 1, "20"); wb.set_cell_input(0, 1, 2, "200"); + wb.set_cell_input(0, 2, 0, "East"); wb.set_cell_input(0, 2, 1, "30"); wb.set_cell_input(0, 2, 2, "300"); + wb.set_cell_input(0, 3, 0, "East2"); wb.set_cell_input(0, 3, 1, "5"); wb.set_cell_input(0, 3, 2, "50"); + + CHECK_NEAR(eval(wb, "=SUM(B1:B4)").as_number(), 65.0, 1e-12); + CHECK_NEAR(eval(wb, "=SUMIF(A1:A4, \"East\", C1:C4)").as_number(), 400.0, 1e-12); + CHECK_NEAR(eval(wb, "=SUMIF(A1:A4, \"East*\", C1:C4)").as_number(), 450.0, 1e-12); + CHECK_NEAR(eval(wb, "=SUMIFS(C1:C4, A1:A4, \"East*\", B1:B4, \">=10\")").as_number(), 400.0, 1e-12); +} + +TEST_CASE("Phase3: Logical and Statistical (18 functions)") { + Workbook wb; + CHECK(eval(wb, "=AND(TRUE, 1, 5>2)").as_bool()); + CHECK(!eval(wb, "=AND(TRUE, 0)").as_bool()); + CHECK(eval(wb, "=OR(FALSE, 0, 3=3)").as_bool()); + CHECK(!eval(wb, "=OR(FALSE, 0)").as_bool()); + CHECK(!eval(wb, "=NOT(TRUE)").as_bool()); + CHECK(eval(wb, "=TRUE()").as_bool()); + CHECK(!eval(wb, "=FALSE()").as_bool()); + CHECK_NEAR(eval(wb, "=IF(1<2, 10, 1/0)").as_number(), 10.0, 1e-12); + + // Data: {2, 4, 4, 4, 5, 5, 7, 9} -> mean=5, varp=4, stdevp=2, var=32/7, stdev=sqrt(32/7) + double vals[] = {2, 4, 4, 4, 5, 5, 7, 9}; + for (int i = 0; i < 8; ++i) { + wb.set_cell_input(0, i, 0, std::to_string(static_cast(vals[i]))); + } + wb.set_cell_input(0, 8, 0, "text"); + // Row 9 (A10) left empty + + CHECK_NEAR(eval(wb, "=AVERAGE(A1:A10)").as_number(), 5.0, 1e-12); + CHECK_NEAR(eval(wb, "=COUNT(A1:A10)").as_number(), 8.0, 1e-12); + CHECK_NEAR(eval(wb, "=COUNTA(A1:A10)").as_number(), 9.0, 1e-12); + CHECK_NEAR(eval(wb, "=COUNTBLANK(A1:A10)").as_number(), 1.0, 1e-12); + CHECK_NEAR(eval(wb, "=COUNTIF(A1:A8, 4)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=COUNTIFS(A1:A8, \">=4\", A1:A8, \"<=5\")").as_number(), 5.0, 1e-12); + CHECK_NEAR(eval(wb, "=MAX(A1:A10)").as_number(), 9.0, 1e-12); + CHECK_NEAR(eval(wb, "=MIN(A1:A10)").as_number(), 2.0, 1e-12); + CHECK_NEAR(eval(wb, "=VARP(A1:A8)").as_number(), 4.0, 1e-12); + CHECK_NEAR(eval(wb, "=STDEVP(A1:A8)").as_number(), 2.0, 1e-12); + CHECK_NEAR(eval(wb, "=VAR(A1:A8)").as_number(), 32.0 / 7.0, 1e-12); + CHECK_NEAR(eval(wb, "=STDEV(A1:A8)").as_number(), std::sqrt(32.0 / 7.0), 1e-12); +} + +TEST_CASE("Phase3: Lookup & Reference + FILTER dynamic spilling (8 functions)") { + Workbook wb; + // Table A1:C5 + wb.set_cell_input(0, 0, 0, "ID"); wb.set_cell_input(0, 0, 1, "Region"); wb.set_cell_input(0, 0, 2, "Sales"); + wb.set_cell_input(0, 1, 0, "10"); wb.set_cell_input(0, 1, 1, "East"); wb.set_cell_input(0, 1, 2, "100"); + wb.set_cell_input(0, 2, 0, "20"); wb.set_cell_input(0, 2, 1, "West"); wb.set_cell_input(0, 2, 2, "250"); + wb.set_cell_input(0, 3, 0, "30"); wb.set_cell_input(0, 3, 1, "East"); wb.set_cell_input(0, 3, 2, "400"); + wb.set_cell_input(0, 4, 0, "40"); wb.set_cell_input(0, 4, 1, "North"); wb.set_cell_input(0, 4, 2, "50"); + + CHECK_EQ(eval(wb, "=CHOOSE(2, \"A\", \"B\", \"C\")").as_string(), std::string("B")); + CHECK_NEAR(eval(wb, "=ROWS(A1:C5)").as_number(), 5.0, 1e-12); + CHECK_NEAR(eval(wb, "=COLUMNS(A1:C5)").as_number(), 3.0, 1e-12); + CHECK_EQ(eval(wb, "=INDEX(A1:C5, 3, 2)").as_string(), std::string("West")); + CHECK_NEAR(eval(wb, "=SUM(A2:INDEX(A2:C5, 3, 1))").as_number(), 60.0, 1e-12); + CHECK_NEAR(eval(wb, "=MATCH(\"West\", B2:B5, 0)").as_number(), 2.0, 1e-12); + CHECK_NEAR(eval(wb, "=MATCH(25, A2:A5, 1)").as_number(), 2.0, 1e-12); + CHECK_NEAR(eval(wb, "=VLOOKUP(30, A2:C5, 3, FALSE)").as_number(), 400.0, 1e-12); + CHECK_NEAR(eval(wb, "=VLOOKUP(25, A2:C5, 3, TRUE)").as_number(), 250.0, 1e-12); + CHECK_EQ(eval(wb, "=HLOOKUP(\"Region\", A1:C5, 4, FALSE)").as_string(), std::string("East")); + + // FILTER spilling into E1:G2 (rows where Region=="East" AND Sales>=100) + wb.set_cell_input(0, 0, 4, "=FILTER(A2:C5, (B2:B5=\"East\")*(C2:C5>=100))"); + CHECK_NEAR(wb.get_scalar_value(0, 0, 4).as_number(), 10.0, 1e-12); + CHECK_EQ(wb.get_scalar_value(0, 0, 5).as_string(), std::string("East")); + CHECK_NEAR(wb.get_scalar_value(0, 0, 6).as_number(), 100.0, 1e-12); + CHECK_NEAR(wb.get_scalar_value(0, 1, 4).as_number(), 30.0, 1e-12); + CHECK_EQ(wb.get_scalar_value(0, 1, 5).as_string(), std::string("East")); + CHECK_NEAR(wb.get_scalar_value(0, 1, 6).as_number(), 400.0, 1e-12); + + // Empty FILTER with if_empty and without if_empty + CHECK_EQ(eval(wb, "=FILTER(A2:C5, C2:C5>9999, \"None\")").as_string(), std::string("None")); + CHECK(eval(wb, "=FILTER(A2:C5, C2:C5>9999)").as_error() == ErrorCode::NA); +} + +TEST_CASE("Phase3: Text (all 14 functions)") { + Workbook wb; + CHECK(!eval(wb, "=EXACT(\"Abc\", \"abc\")").as_bool()); + CHECK(eval(wb, "=EXACT(\"Abc\", \"Abc\")").as_bool()); + CHECK_NEAR(eval(wb, "=FIND(\"cd\", \"abcdef\")").as_number(), 3.0, 1e-12); + CHECK_EQ(eval(wb, "=LEFT(\"Spreadsheet\", 6)").as_string(), std::string("Spread")); + CHECK_NEAR(eval(wb, "=LEN(\"hello\")").as_number(), 5.0, 1e-12); + CHECK_EQ(eval(wb, "=LOWER(\"HeLLo\")").as_string(), std::string("hello")); + CHECK_EQ(eval(wb, "=MID(\"Spreadsheet\", 7, 5)").as_string(), std::string("sheet")); + CHECK_EQ(eval(wb, "=PROPER(\"hELLO wORLD-test\")").as_string(), std::string("Hello World-Test")); + CHECK_EQ(eval(wb, "=REPLACE(\"abcdef\", 3, 2, \"XY\")").as_string(), std::string("abXYef")); + CHECK_EQ(eval(wb, "=REPT(\"ab\", 3)").as_string(), std::string("ababab")); + CHECK_EQ(eval(wb, "=RIGHT(\"Spreadsheet\", 5)").as_string(), std::string("sheet")); + CHECK_EQ(eval(wb, "=SUBSTITUTE(\"a-b-a-b\", \"a\", \"X\", 2)").as_string(), std::string("a-b-X-b")); + CHECK_EQ(eval(wb, "=T(\"text\")").as_string(), std::string("text")); + CHECK_EQ(eval(wb, "=T(123)").as_string(), std::string("")); + CHECK_EQ(eval(wb, "=TRIM(\" hello world \")").as_string(), std::string("hello world")); + CHECK_EQ(eval(wb, "=UPPER(\"HeLLo\")").as_string(), std::string("HELLO")); +} + +TEST_CASE("Phase3: Date & Time (all 11 functions)") { + Workbook wb; + Value d = eval(wb, "=DATE(2024, 3, 15)"); + CHECK(d.is_number()); + CHECK_NEAR(eval(wb, "=YEAR(DATE(2024, 3, 15))").as_number(), 2024.0, 1e-12); + CHECK_NEAR(eval(wb, "=MONTH(DATE(2024, 3, 15))").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=DAY(DATE(2024, 3, 15))").as_number(), 15.0, 1e-12); + CHECK_NEAR(eval(wb, "=DATEVALUE(\"2024-03-15\")").as_number(), d.as_number(), 1e-12); + CHECK_NEAR(eval(wb, "=DATEVALUE(\"Mar 15, 2024\")").as_number(), d.as_number(), 1e-12); + + Value t = eval(wb, "=TIME(14, 30, 45)"); + CHECK_NEAR(eval(wb, "=HOUR(TIME(14, 30, 45))").as_number(), 14.0, 1e-12); + CHECK_NEAR(eval(wb, "=MINUTE(TIME(14, 30, 45))").as_number(), 30.0, 1e-12); + CHECK_NEAR(eval(wb, "=SECOND(TIME(14, 30, 45))").as_number(), 45.0, 1e-12); + CHECK_NEAR(eval(wb, "=TIMEVALUE(\"2:30:45 PM\")").as_number(), t.as_number(), 1e-12); + + Value now = eval(wb, "=NOW()"); + CHECK(now.is_number() && now.as_number() > 40000.0); +} + +TEST_CASE("Phase3: Financial (all 10 functions)") { + Workbook wb; + // Standard 30-year 5% $200,000 mortgage + CHECK_NEAR(eval(wb, "=PMT(0.05/12, 360, 200000)").as_number(), -1073.643246, 1e-4); + CHECK_NEAR(eval(wb, "=PV(0.05/12, 360, -1073.643246)").as_number(), 200000.0, 1e-1); + CHECK_NEAR(eval(wb, "=FV(0.06/12, 120, -100, 0, 0)").as_number(), 16387.93468, 1e-3); + CHECK_NEAR(eval(wb, "=NPER(0.05/12, -1073.643246, 200000)").as_number(), 360.0, 1e-3); + CHECK_NEAR(eval(wb, "=RATE(360, -1073.643246, 200000)").as_number(), 0.05 / 12.0, 1e-6); + + // NPV & IRR + wb.set_cell_input(0, 0, 0, "-100"); + wb.set_cell_input(0, 1, 0, "60"); + wb.set_cell_input(0, 2, 0, "60"); + CHECK_NEAR(eval(wb, "=NPV(0.1, A2:A3) + A1").as_number(), 4.132231, 1e-5); + CHECK_NEAR(eval(wb, "=IRR(A1:A3)").as_number(), 0.130662386, 1e-5); + + // Depreciation: SLN, SYD, DDB + CHECK_NEAR(eval(wb, "=SLN(10000, 1000, 5)").as_number(), 1800.0, 1e-12); + CHECK_NEAR(eval(wb, "=SYD(10000, 1000, 5, 1)").as_number(), 3000.0, 1e-12); + CHECK_NEAR(eval(wb, "=DDB(2400, 300, 10, 1, 2)").as_number(), 480.0, 1e-12); + CHECK_NEAR(eval(wb, "=DDB(2400, 300, 10, 2, 2)").as_number(), 384.0, 1e-12); +} + +TEST_CASE("Phase3: Database (all 12 functions sharing filterDatabase)") { + Workbook wb; + // Database A1:C6 + wb.set_cell_input(0, 0, 0, "Tree"); wb.set_cell_input(0, 0, 1, "Height"); wb.set_cell_input(0, 0, 2, "Yield"); + wb.set_cell_input(0, 1, 0, "Apple"); wb.set_cell_input(0, 1, 1, "18"); wb.set_cell_input(0, 1, 2, "14"); + wb.set_cell_input(0, 2, 0, "Pear"); wb.set_cell_input(0, 2, 1, "12"); wb.set_cell_input(0, 2, 2, "10"); + wb.set_cell_input(0, 3, 0, "Cherry"); wb.set_cell_input(0, 3, 1, "13"); wb.set_cell_input(0, 3, 2, "9"); + wb.set_cell_input(0, 4, 0, "Apple"); wb.set_cell_input(0, 4, 1, "14"); wb.set_cell_input(0, 4, 2, "10"); + wb.set_cell_input(0, 5, 0, "Pear"); wb.set_cell_input(0, 5, 1, "9"); wb.set_cell_input(0, 5, 2, "8"); + + // Criteria E1:F3: + // Row 1 (headers): Tree | Height + // Row 2 (AND): Apple | >10 (matches rows 2 & 5: Apple 18->14, Apple 14->10) + // Row 3 (OR): Cherry | (matches row 4: Cherry 13->9) + wb.set_cell_input(0, 0, 4, "Tree"); wb.set_cell_input(0, 0, 5, "Height"); + wb.set_cell_input(0, 1, 4, "Apple"); wb.set_cell_input(0, 1, 5, ">10"); + wb.set_cell_input(0, 2, 4, "Cherry"); + + // Matching Yields (AND+OR via E1:F3): {14, 10, 9} + CHECK_NEAR(eval(wb, "=DSUM(A1:C6, \"Yield\", E1:F3)").as_number(), 33.0, 1e-12); + CHECK_NEAR(eval(wb, "=DAVERAGE(A1:C6, \"Yield\", E1:F3)").as_number(), 11.0, 1e-12); + CHECK_NEAR(eval(wb, "=DCOUNT(A1:C6, 3, E1:F3)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=DCOUNTA(A1:C6, \"Tree\", E1:F3)").as_number(), 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=DMAX(A1:C6, \"Yield\", E1:F3)").as_number(), 14.0, 1e-12); + CHECK_NEAR(eval(wb, "=DMIN(A1:C6, \"Yield\", E1:F3)").as_number(), 9.0, 1e-12); + CHECK_NEAR(eval(wb, "=DPRODUCT(A1:C6, \"Yield\", E1:F3)").as_number(), 1260.0, 1e-12); + + // Yields {14, 10, 9}, mean=11, sq devs = 9+1+4 = 14 -> var=7, varp=14/3 + CHECK_NEAR(eval(wb, "=DVAR(A1:C6, \"Yield\", E1:F3)").as_number(), 7.0, 1e-12); + CHECK_NEAR(eval(wb, "=DVARP(A1:C6, \"Yield\", E1:F3)").as_number(), 14.0 / 3.0, 1e-12); + CHECK_NEAR(eval(wb, "=DSTDEV(A1:C6, \"Yield\", E1:F3)").as_number(), std::sqrt(7.0), 1e-12); + CHECK_NEAR(eval(wb, "=DSTDEVP(A1:C6, \"Yield\", E1:F3)").as_number(), std::sqrt(14.0 / 3.0), 1e-12); + + // DGET: multiple matches -> #NUM!; unique match (E1:F2 with >15 -> Apple 18) -> 14; 0 matches -> #VALUE! + CHECK(eval(wb, "=DGET(A1:C6, \"Yield\", E1:F3)").as_error() == ErrorCode::Num); + wb.set_cell_input(0, 1, 5, ">15"); + CHECK_NEAR(eval(wb, "=DGET(A1:C6, \"Yield\", E1:F2)").as_number(), 14.0, 1e-12); + wb.set_cell_input(0, 1, 5, ">100"); + CHECK(eval(wb, "=DGET(A1:C6, \"Yield\", E1:F2)").as_error() == ErrorCode::Value); +} diff --git a/tests/test_phase4.cpp b/tests/test_phase4.cpp new file mode 100644 index 0000000..d1f877c --- /dev/null +++ b/tests/test_phase4.cpp @@ -0,0 +1,100 @@ +#include "tests/test_framework.hpp" + +#include "engine/io_csv.hpp" +#include "engine/io_native.hpp" +#include "engine/workbook.hpp" + +#include + +using namespace htab; + +TEST_CASE("Phase4: RFC 4180 CSV import/export round-trip and spills") { + const std::string csv_in = + "\xEF\xBB\xBF" + "Name,Value,Note\r\n" + "\"Smith, John\",10,\"He said \"\"Hi\"\"\"\r\n" + "\"Line1\nLine2\",25,TRUE\r\n" + "Total,=SUM(B2:B3),\"=IF(B4>30, \"\"Big\"\", \"\"Small\"\")\"\r\n"; + + Workbook wb; + std::string err; + CHECK(import_csv_string(wb, 0, csv_in, &err)); + CHECK_EQ(wb.get_scalar_value(0, 1, 0).as_string(), std::string("Smith, John")); + CHECK_NEAR(wb.get_scalar_value(0, 1, 1).as_number(), 10.0, 1e-12); + CHECK_EQ(wb.get_scalar_value(0, 1, 2).as_string(), std::string("He said \"Hi\"")); + CHECK_EQ(wb.get_scalar_value(0, 2, 0).as_string(), std::string("Line1\nLine2")); + CHECK(wb.get_scalar_value(0, 2, 2).as_bool()); + CHECK_NEAR(wb.get_scalar_value(0, 3, 1).as_number(), 35.0, 1e-12); + CHECK_EQ(wb.get_scalar_value(0, 3, 2).as_string(), std::string("Big")); + + // Add a FILTER spill in column E (index 4) + wb.set_cell_input(0, 0, 4, "=FILTER(A2:B3, B2:B3>15)"); + CHECK_EQ(wb.get_scalar_value(0, 0, 4).as_string(), std::string("Line1\nLine2")); + CHECK_NEAR(wb.get_scalar_value(0, 0, 5).as_number(), 25.0, 1e-12); + + // Export evaluated values (default) + std::string csv_vals = export_csv_string(wb, 0, false); + Workbook wb2; + CHECK(import_csv_string(wb2, 0, csv_vals, &err)); + CHECK_EQ(wb2.get_scalar_value(0, 1, 0).as_string(), std::string("Smith, John")); + CHECK_EQ(wb2.get_scalar_value(0, 1, 2).as_string(), std::string("He said \"Hi\"")); + CHECK_EQ(wb2.get_scalar_value(0, 2, 0).as_string(), std::string("Line1\nLine2")); + CHECK_NEAR(wb2.get_scalar_value(0, 3, 1).as_number(), 35.0, 1e-12); + CHECK_EQ(wb2.get_scalar_value(0, 3, 2).as_string(), std::string("Big")); + CHECK_NEAR(wb2.get_scalar_value(0, 0, 5).as_number(), 25.0, 1e-12); + + // Export raw formulas and re-import -> formula & spill intact + std::string csv_forms = export_csv_string(wb, 0, true); + Workbook wb3; + CHECK(import_csv_string(wb3, 0, csv_forms, &err)); + CHECK_EQ(wb3.get_cell(0, 3, 1)->raw_input, std::string("=SUM(B2:B3)")); + CHECK_NEAR(wb3.get_scalar_value(0, 3, 1).as_number(), 35.0, 1e-12); + CHECK_EQ(wb3.get_cell(0, 0, 4)->raw_input, std::string("=FILTER(A2:B3, B2:B3>15)")); + CHECK_NEAR(wb3.get_scalar_value(0, 0, 5).as_number(), 25.0, 1e-12); + + // Reject malformed CSV + Workbook bad_wb; + CHECK(!import_csv_string(bad_wb, 0, "\"unterminated", &err)); + CHECK(!err.empty()); +} + +TEST_CASE("Phase4: Native workbook JSON serialization round-trip") { + Workbook wb; + wb.rename_sheet(0, "Summary"); + int s2 = wb.add_sheet("Raw Data"); + wb.set_active_sheet(1); + + wb.set_col_width(0, 0, 120); + wb.set_row_height(0, 1, 28); + wb.set_cell_input(0, 0, 0, "Total:"); + wb.set_cell_input(0, 0, 1, "=SUM('Raw Data'!B1:B3)"); + wb.set_cell_format(0, 0, 1, "$#,##0.00"); + wb.set_cell_input(0, 1, 0, "=FILTER('Raw Data'!A1:B3, 'Raw Data'!B1:B3>=20)"); + + wb.set_cell_input(s2, 0, 0, "Alpha"); wb.set_cell_input(s2, 0, 1, "10"); + wb.set_cell_input(s2, 1, 0, "Beta"); wb.set_cell_input(s2, 1, 1, "20"); + wb.set_cell_input(s2, 2, 0, "Gamma"); wb.set_cell_input(s2, 2, 1, "30"); + + std::string json = save_native_string(wb); + + Workbook loaded; + std::string err; + CHECK(load_native_string(loaded, json, &err)); + CHECK_EQ(loaded.sheet_count(), 2); + CHECK_EQ(loaded.active_sheet(), 1); + CHECK_EQ(loaded.sheet(0).name, std::string("Summary")); + CHECK_EQ(loaded.sheet(1).name, std::string("Raw Data")); + CHECK_EQ(loaded.get_col_width(0, 0, 80), 120); + CHECK_EQ(loaded.get_row_height(0, 1, 20), 28); + CHECK_EQ(loaded.get_cell(0, 0, 1)->raw_input, std::string("=SUM('Raw Data'!B1:B3)")); + CHECK_EQ(loaded.get_formatted_value(0, 0, 1), std::string("$60.00")); + CHECK_EQ(loaded.get_scalar_value(0, 1, 0).as_string(), std::string("Beta")); + CHECK_NEAR(loaded.get_scalar_value(0, 1, 1).as_number(), 20.0, 1e-12); + CHECK_EQ(loaded.get_scalar_value(0, 2, 0).as_string(), std::string("Gamma")); + CHECK_NEAR(loaded.get_scalar_value(0, 2, 1).as_number(), 30.0, 1e-12); + + // Corrupted JSON rejected cleanly + Workbook bad; + CHECK(!load_native_string(bad, "{bad json", &err)); + CHECK(!err.empty()); +} diff --git a/ui/app_window.cpp b/ui/app_window.cpp new file mode 100644 index 0000000..12f3c4e --- /dev/null +++ b/ui/app_window.cpp @@ -0,0 +1,1746 @@ +#include "ui/app_window.hpp" + +#include "engine/address.hpp" +#include "engine/io_csv.hpp" +#include "engine/io_native.hpp" + +#include +#include +#include +#include +#include + +namespace htab::ui { + +namespace { + +struct MenuItemDef { + const char* label; +}; + +constexpr MenuItemDef kMenuItems[] = { + {"New Workbook"}, + {"Open File..."}, + {"Save (.htab)..."}, + {"Export CSV (Values)..."}, + {"Export CSV (Formulas)..."}, + {"Insert Row"}, + {"Delete Row"}, + {"Insert Column"}, + {"Delete Column"}, + {"Format Cell..."}, + {"Add Sheet"}, + {"Rename Sheet..."}, + {"Delete Sheet"}, + {"Go To Cell..."}, + {"Keyboard Hints (F1)"}, + {"Quit"}, +}; +constexpr int kMenuItemCount = static_cast(sizeof(kMenuItems) / sizeof(kMenuItems[0])); + +struct HelpItemDef { + const char* key; + const char* compact_desc; + const char* desc; +}; + +constexpr HelpItemDef kHelpItems[] = { + {"F1", "Keyboard hints", "Show or hide these keyboard hints"}, + {"F10", "Main menu", "Open main menu"}, + {"Arrows", "Move / Shift sel", "Move cell (Shift extends selection)"}, + {"Enter / Tab", "Confirm & move", "Commit edit & move (Shift reverses)"}, + {"PgUp / PgDn", "Jump 10 rows", "Move active cell 10 rows up/down"}, + {"Home / ^Home", "Col A / Cell A1", "Jump to Col A (Ctrl+Home -> A1)"}, + {"F2 / Type", "Edit cell", "Edit active cell in place"}, + {"Esc", "Cancel / close", "Cancel cell edit or close dialog"}, + {"Del / BkSp", "Clear cells", "Clear selected cell contents"}, + {"Ctrl+C/X/V", "Copy/Cut/Paste", "Copy, cut, or paste (relative refs)"}, + {"Ctrl+Z / Y", "Undo / Redo", "Undo or redo last change"}, + {"Ctrl+N", "New workbook", "Start a new blank workbook"}, + {"Ctrl+O", "Open file", "Open .htab, .json, or .csv file"}, + {"Ctrl+S", "Save (.htab)", "Save workbook natively"}, + {"Ctrl+E", "Export CSV", "Export active sheet to CSV (Values)"}, + {"Ctrl+G", "Go to cell", "Jump to cell/range (or click cell box)"}, + {"^PgUp / ^PgDn", "Switch sheet", "Switch to previous / next sheet"}, + {"Ctrl+Q", "Quit (confirm)", "Quit HTab (asks if unsaved)"}, + {"Right-click", "Context menu", "Actions for cell, header, or tab"}, + {"Mid-click tab", "Close sheet", "Close clicked worksheet tab"}, +}; +constexpr int kHelpItemCount = static_cast(sizeof(kHelpItems) / sizeof(kHelpItems[0])); + +struct FormatPreset { + const char* label; + const char* fmt; +}; + +constexpr FormatPreset kFormatPresets[] = { + {"General", ""}, + {"Fixed (0.00)", "0.00"}, + {"Integer (#,##0)", "#,##0"}, + {"Currency ($#,##0.00)", "$#,##0.00"}, + {"Percentage (0.00%)", "0.00%"}, + {"Date (yyyy-mm-dd)", "yyyy-mm-dd"}, + {"Time (hh:mm:ss)", "hh:mm:ss"}, +}; +constexpr int kFormatPresetCount = + static_cast(sizeof(kFormatPresets) / sizeof(kFormatPresets[0])); + +void draw_ui_button(gemui_app_t* app, + cairo_t* cr, + gemui_rect_t r, + const char* label, + int logical_font_px, + const UiScale& ui, + int hit_id, + int hit_val, + bool primary, + bool active, + bool focused) { + const gemui_theme_t* t = gemui_theme(app); + gemui_color_t bg = active ? t->sel_bg : (primary ? t->accent : t->bg_button); + double bg_lum = 0.299 * bg.r + 0.587 * bg.g + 0.114 * bg.b; + gemui_color_t fg = (bg_lum > 0.58) ? t->bg_main : ((active || primary) ? t->sel_fg : t->fg_bright); + gemui_color_t bd = focused ? t->highlight : (active ? t->accent : t->border); + double rad = 3.0 * ui.scale; + double lw = std::max(1.0, (focused ? 1.5 : 1.0) * ui.scale); + gemui_fill_round(cr, r, rad, bg); + gemui_stroke_round(cr, r, rad, lw, bd); + int pad = spx(2, ui); + if (r.w > pad * 2 + 4 && r.h > 4) { + gemui_draw_text(cr, t, gemui_rect_t{r.x + pad, r.y, r.w - pad * 2, r.h}, label, + pt_delta_for_ui(t, logical_font_px, ui), primary || active, + GEMUI_ALIGN_CENTER, fg); + } + if (hit_id >= 0) { + gemui_hit_add(app, r, hit_id, hit_val); + } +} + +std::string compact_tab_label(const std::string& name) { + if (name.rfind("Sheet", 0) == 0 && name.size() > 5) { + bool all_digits = true; + for (size_t i = 5; i < name.size(); ++i) { + if (!std::isdigit(static_cast(name[i]))) { + all_digits = false; + break; + } + } + if (all_digits) return "S" + name.substr(5); + } + if (name.size() <= 5) return name; + return name.substr(0, 5); +} + +KeySym normalize_ctrl_keysym(KeySym ks) { + if (ks >= XK_A && ks <= XK_Z) return ks - XK_A + XK_a; + return ks; +} + +bool ends_with_ci(std::string_view s, std::string_view suffix) { + if (s.size() < suffix.size()) return false; + return iequals_ascii(s.substr(s.size() - suffix.size()), suffix); +} + +bool point_in_rect(gemui_rect_t r, int x, int y) { + return x >= r.x && x < r.x + r.w && y >= r.y && y < r.y + r.h; +} + +} // namespace + +void AppWindow::cb_draw(gemui_app_t*, cairo_t* cr, int w, int h, void* ud) { + static_cast(ud)->draw(cr, w, h); +} + +void AppWindow::cb_key(gemui_app_t*, KeySym ks, unsigned int state, const char* utf8, void* ud) { + static_cast(ud)->handle_key(ks, state, utf8); +} + +void AppWindow::cb_ptr(gemui_app_t*, int type, int x, int y, unsigned int btn, void* ud) { + static_cast(ud)->handle_ptr(type, x, y, btn); +} + +void AppWindow::cb_resize(gemui_app_t*, int, int, void* ud) { + auto* self = static_cast(ud); + self->grid_.ensure_visible(self->wb_, self->grid_.active_row(), self->grid_.active_col()); + gemui_request_redraw(self->app_); +} + +void AppWindow::cb_theme(gemui_app_t*, void* ud) { + auto* self = static_cast(ud); + self->grid_.ensure_visible(self->wb_, self->grid_.active_row(), self->grid_.active_col()); + gemui_request_redraw(self->app_); +} + +bool AppWindow::cb_close(gemui_app_t*, void* ud) { + static_cast(ud)->request_quit(); + return false; +} + +void AppWindow::cb_open_file_done(gemui_app_t*, bool accepted, const char* path, void* ud) { + if (accepted && path && path[0]) { + static_cast(ud)->load_file_auto(path); + } +} + +void AppWindow::cb_save_native_done(gemui_app_t*, bool accepted, const char* path, void* ud) { + auto* self = static_cast(ud); + bool should_quit = self->quit_after_save_; + self->quit_after_save_ = false; + if (accepted && path && path[0]) { + if (self->save_native_to(path) && should_quit) { + gemui_quit(self->app_, 0); + } + } +} + +void AppWindow::cb_export_csv_values_done(gemui_app_t*, bool accepted, const char* path, void* ud) { + if (accepted && path && path[0]) { + static_cast(ud)->export_csv_to(path, false); + } +} + +void AppWindow::cb_export_csv_formulas_done(gemui_app_t*, bool accepted, const char* path, void* ud) { + if (accepted && path && path[0]) { + static_cast(ud)->export_csv_to(path, true); + } +} + +int AppWindow::run(int req_w, int req_h, bool explicit_geometry, const std::string& initial_file) { + app_ = gemui_create("htab", "HTab", req_w, req_h, false); + if (!app_) return 1; + + if (explicit_geometry) { + Display* dpy = gemui_display(app_); + Window win = gemui_window(app_); + int scr = DefaultScreen(dpy); + XSizeHints* sh = XAllocSizeHints(); + if (sh) { + sh->flags = PMinSize | PSize; + sh->min_width = 200; + sh->min_height = 200; + sh->width = req_w; + sh->height = req_h; + XSetWMNormalHints(dpy, win, sh); + XFree(sh); + } + if (req_w >= DisplayWidth(dpy, scr) || req_h >= DisplayHeight(dpy, scr)) { + XMoveResizeWindow(dpy, win, 0, 0, static_cast(req_w), + static_cast(req_h)); + } else { + XResizeWindow(dpy, win, static_cast(req_w), static_cast(req_h)); + } + XFlush(dpy); + } + + clipboard_.init(app_); + + gemui_handlers_t handlers{}; + handlers.on_draw = &AppWindow::cb_draw; + handlers.on_key = &AppWindow::cb_key; + handlers.on_ptr = &AppWindow::cb_ptr; + handlers.on_resize = &AppWindow::cb_resize; + handlers.on_theme = &AppWindow::cb_theme; + gemui_set_handlers(app_, &handlers, this); + gemui_set_close_handler(app_, &AppWindow::cb_close, this); + + if (!initial_file.empty()) { + load_file_auto(initial_file); + } + grid_.sync_editor_from_cell(wb_); + update_title(); + + int code = gemui_run(app_); + clipboard_.shutdown(app_); + gemui_destroy(app_); + app_ = nullptr; + return code; +} + +AppWindow::Layout AppWindow::compute_layout(int w, int h) const { + Layout lay; + lay.ui = compute_ui_scale(app_, w, h); + const UiScale& ui = lay.ui; + + int top_h = ui.compact ? spx(20, ui) : spx(ui.touch ? 38 : 34, ui); + int fbar_h = ui.compact ? spx(22, ui) : spx(ui.touch ? 36 : 32, ui); + int bot_h = ui.compact ? spx(20, ui) : spx(ui.touch ? 34 : 30, ui); + int grid_h = std::max(spx(30, ui), h - top_h - fbar_h - bot_h); + + lay.top_bar = gemui_rect_t{0, 0, w, top_h}; + lay.formula_bar = gemui_rect_t{0, top_h, w, fbar_h}; + lay.grid = gemui_rect_t{0, top_h + fbar_h, w, grid_h}; + lay.bottom_bar = gemui_rect_t{0, top_h + fbar_h + grid_h, w, bot_h}; + + int tabs_w = ui.compact ? std::max(spx(80, ui), (w * 60) / 100) + : std::max(spx(140, ui), (w * 55) / 100); + lay.tabs_area = gemui_rect_t{0, lay.bottom_bar.y, tabs_w, bot_h}; + int hs_pad = spx(3, ui); + int hscroll_w = std::max(spx(24, ui), w - tabs_w - hs_pad * 2); + if (!ui.compact) hscroll_w = std::min(spx(240, ui), hscroll_w); + lay.hscroll = gemui_rect_t{w - hscroll_w - hs_pad, lay.bottom_bar.y + hs_pad, + hscroll_w, std::max(4, bot_h - hs_pad * 2)}; + return lay; +} + +std::string AppWindow::display_filename() const { + if (current_path_.empty()) return "untitled"; + size_t slash = current_path_.find_last_of('/'); + std::string base = (slash == std::string::npos) ? current_path_ : current_path_.substr(slash + 1); + return base.empty() ? "untitled" : base; +} + +void AppWindow::update_title() { + if (!app_) return; + std::string title = "HTab - " + display_filename() + (dirty_ ? " *" : ""); + gemui_set_title(app_, title.c_str()); +} + +void AppWindow::draw_top_bar(cairo_t* cr, const Layout& lay) { + const gemui_theme_t* t = gemui_theme(app_); + const UiScale& ui = lay.ui; + int div_h = std::max(1, spx(1, ui)); + gemui_fill_rect(cr, lay.top_bar, t->bg_header); + gemui_fill_rect(cr, gemui_rect_t{0, lay.top_bar.h - div_h, lay.top_bar.w, div_h}, t->divider); + + int x = spx(ui.compact ? 2 : 6, ui); + int y = spx(ui.compact ? 2 : 4, ui); + int bh = std::max(6, lay.top_bar.h - y * 2 - div_h); + int fpx = ui.compact ? 10 : 13; + int gap = spx(ui.compact ? 2 : 4, ui); + + auto add_btn = [&](const char* lbl, int fixed_logical_w, HitId id, bool primary = false) { + int bw = (fixed_logical_w > 0) + ? spx(fixed_logical_w, ui) + : (measure_text_px(cr, t, lbl, fpx, ui, primary) + spx(14, ui)); + if (x + bw > lay.top_bar.w - spx(2, ui)) return; + draw_ui_button(app_, cr, gemui_rect_t{x, y, bw, bh}, lbl, fpx, ui, id, 0, + primary, false, false); + x += bw + gap; + }; + + if (ui.compact) { + add_btn("Menu", 40, HIT_MENU_BTN, true); + add_btn("<", 20, HIT_UNDO_BTN); + add_btn(">", 20, HIT_REDO_BTN); + add_btn("Fmt", 30, HIT_FORMAT_BTN); + } else { + add_btn("Menu", 0, HIT_MENU_BTN, true); + add_btn("Open", 0, HIT_OPEN_BTN); + add_btn("Save", 0, HIT_SAVE_BTN); + add_btn("CSV", 0, HIT_CSV_BTN); + add_btn("Undo", 0, HIT_UNDO_BTN); + add_btn("Redo", 0, HIT_REDO_BTN); + add_btn("Fmt", 0, HIT_FORMAT_BTN); + add_btn("+Row", 0, HIT_INS_ROW_BTN); + add_btn("-Row", 0, HIT_DEL_ROW_BTN); + add_btn("+Col", 0, HIT_INS_COL_BTN); + add_btn("-Col", 0, HIT_DEL_COL_BTN); + } + + int rpad = spx(4, ui); + int rem_w = lay.top_bar.w - x - rpad; + if (rem_w > spx(16, ui)) { + std::string fname = display_filename() + (dirty_ ? "*" : ""); + gemui_draw_text(cr, t, gemui_rect_t{x, y, rem_w, bh}, fname.c_str(), + pt_delta_for_ui(t, fpx, ui), false, GEMUI_ALIGN_RIGHT, t->fg_muted); + } +} + +void AppWindow::draw_bottom_bar(cairo_t* cr, const Layout& lay) { + const gemui_theme_t* t = gemui_theme(app_); + const UiScale& ui = lay.ui; + int div_h = std::max(1, spx(1, ui)); + gemui_fill_rect(cr, lay.bottom_bar, t->bg_footer); + gemui_fill_rect(cr, gemui_rect_t{0, lay.bottom_bar.y, lay.bottom_bar.w, div_h}, t->divider); + + int fpx = ui.compact ? 9 : 12; + int y = lay.bottom_bar.y + spx(2, ui); + int bh = std::max(6, lay.bottom_bar.h - spx(4, ui)); + int x = spx(2, ui); + int add_btn_w = spx(ui.compact ? 18 : 26, ui); + int tab_gap = spx(2, ui); + int max_tabs_x = lay.tabs_area.x + lay.tabs_area.w - add_btn_w - spx(4, ui); + + if (tab_scroll_ >= wb_.sheet_count()) tab_scroll_ = 0; + last_tab_rects_.clear(); + + for (int i = tab_scroll_; i < wb_.sheet_count(); ++i) { + bool active = (i == wb_.active_sheet()); + bool show_close = (wb_.sheet_count() > 1) && (!ui.compact || active); + int close_w = show_close ? spx(ui.compact ? 12 : 18, ui) : 0; + + std::string lbl = ui.compact ? compact_tab_label(wb_.sheet(i).name) : wb_.sheet(i).name; + int tw = measure_text_px(cr, t, lbl, fpx, ui, active) + + spx(ui.compact ? 10 : 18, ui) + close_w; + tw = std::clamp(tw, spx(ui.compact ? 24 : 52, ui), spx(ui.compact ? 64 : 156, ui)); + if (x + tw > max_tabs_x) break; + + gemui_rect_t tab_r{x, y, tw, bh}; + last_tab_rects_.emplace_back(tab_r, i); + + gemui_color_t bg = active ? t->sel_bg : t->bg_button; + gemui_color_t bd = active ? t->highlight : t->border; + gemui_color_t fg = active ? t->sel_fg : t->fg_bright; + double rad = 3.0 * ui.scale; + double lw = std::max(1.0, (active ? 1.5 : 1.0) * ui.scale); + gemui_fill_round(cr, tab_r, rad, bg); + gemui_stroke_round(cr, tab_r, rad, lw, bd); + gemui_hit_add(app_, tab_r, HIT_SHEET_TAB, i); + + int lpad = spx(ui.compact ? 3 : 6, ui); + int label_w = std::max(1, tab_r.w - lpad - close_w - spx(2, ui)); + gemui_draw_text(cr, t, gemui_rect_t{tab_r.x + lpad, tab_r.y, label_w, tab_r.h}, + lbl.c_str(), pt_delta_for_ui(t, fpx, ui), active, + show_close ? GEMUI_ALIGN_LEFT : GEMUI_ALIGN_CENTER, fg); + + if (show_close) { + gemui_rect_t close_r{tab_r.x + tab_r.w - close_w - spx(2, ui), + tab_r.y + spx(1, ui), + close_w, + std::max(4, tab_r.h - spx(2, ui))}; + gemui_draw_text(cr, t, close_r, "x", pt_delta_for_ui(t, fpx, ui), false, + GEMUI_ALIGN_CENTER, active ? t->sel_fg : t->fg_muted); + gemui_hit_add(app_, close_r, HIT_SHEET_CLOSE, i); + } + + x += tw + tab_gap; + } + + if (x + add_btn_w <= lay.tabs_area.x + lay.tabs_area.w) { + draw_ui_button(app_, cr, gemui_rect_t{x, y, add_btn_w, bh}, "+", fpx, ui, + HIT_ADD_SHEET, 0, false, false, false); + } + + if (!ui.compact) { + CellRange sel = grid_.selection_range(wb_.active_sheet()); + int cells_checked = 0; + int num_count = 0; + double num_sum = 0.0; + for (int r = sel.r1; r <= sel.r2 && cells_checked < 2000; ++r) { + for (int c = sel.c1; c <= sel.c2 && cells_checked < 2000; ++c) { + ++cells_checked; + Value v = wb_.get_scalar_value(sel.sheet, r, c); + if (v.is_number()) { + ++num_count; + num_sum += v.as_number(); + } + } + } + int status_x = lay.tabs_area.x + lay.tabs_area.w + spx(4, ui); + int status_w = lay.hscroll.x - status_x - spx(6, ui); + if (status_w > spx(40, ui) && num_count > 0) { + char buf[96]; + std::snprintf(buf, sizeof(buf), "N:%d Sum:%.6g", num_count, num_sum); + gemui_draw_text(cr, t, gemui_rect_t{status_x, y, status_w, bh}, buf, + pt_delta_for_ui(t, fpx, ui), false, GEMUI_ALIGN_RIGHT, t->fg_muted); + } + } + + last_hscroll_r_ = lay.hscroll; + grid_.draw_hscroll(app_, cr, wb_, lay.hscroll, ui, HIT_HSCROLL); +} + +void AppWindow::draw_modal(cairo_t* cr, int w, int h, const UiScale& ui) { + if (modal_ == ModalKind::Closed) return; + const gemui_theme_t* t = gemui_theme(app_); + int fpx = ui.compact ? 10 : 13; + int font_delta = pt_delta_for_ui(t, fpx, ui); + double box_rad = 5.0 * ui.scale; + double box_lw = std::max(1.5, 1.5 * ui.scale); + int pad = spx(8, ui); + int margin_x = spx(12, ui); + int margin_y = spx(16, ui); + + if (modal_ == ModalKind::ContextMenu) { + // Transparent click-catcher outside context menu + gemui_hit_add(app_, gemui_rect_t{0, 0, w, h}, HIT_MODAL_BACKDROP, 0); + if (ctx_items_.empty()) return; + + int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 26), ui); + int max_text_w = 0; + for (const auto& item : ctx_items_) { + int tw = measure_text_px(cr, t, item.label, fpx, ui, false); + if (tw > max_text_w) max_text_w = tw; + } + int mw = std::clamp(max_text_w + spx(28, ui), spx(130, ui), + std::max(spx(130, ui), w - spx(8, ui))); + int mh = std::min(h - spx(8, ui), + static_cast(ctx_items_.size()) * row_h + spx(8, ui)); + int edge = spx(4, ui); + int bx = std::clamp(ctx_x_, edge, std::max(edge, w - mw - edge)); + int by = std::clamp(ctx_y_, edge, std::max(edge, h - mh - edge)); + gemui_rect_t box{bx, by, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + int item_inset = spx(4, ui); + int text_inset = spx(6, ui); + for (size_t i = 0; i < ctx_items_.size(); ++i) { + int iy = box.y + spx(4, ui) + static_cast(i) * row_h; + if (iy + row_h > box.y + box.h) break; + gemui_rect_t ir{box.x + item_inset, iy, box.w - item_inset * 2, std::max(4, row_h - 1)}; + bool sel = (static_cast(i) == ctx_sel_); + if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg); + gemui_draw_text(cr, t, + gemui_rect_t{ir.x + text_inset, ir.y, + std::max(1, ir.w - text_inset * 2), ir.h}, + ctx_items_[i].label, font_delta, sel, GEMUI_ALIGN_LEFT, + sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app_, ir, HIT_CTX_ITEM, static_cast(i)); + } + return; + } + + cairo_set_source_rgba(cr, 0.0, 0.0, 0.0, 0.55); + cairo_rectangle(cr, 0, 0, w, h); + cairo_fill(cr); + gemui_hit_add(app_, gemui_rect_t{0, 0, w, h}, HIT_MODAL_BACKDROP, 0); + + if (modal_ == ModalKind::Menu) { + int mw = std::min(w - margin_x, spx(ui.compact ? 224 : 280, ui)); + int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 28), ui); + int title_h = spx(ui.compact ? 20 : 28, ui); + int max_h = std::max(spx(60, ui), h - margin_y); + int vis_rows = std::min(kMenuItemCount, + std::max(3, (max_h - title_h - spx(8, ui)) / std::max(1, row_h))); + int mh = title_h + vis_rows * row_h + spx(6, ui); + gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(2, ui), box.w - pad * 2, title_h}, + "Menu (Up/Down, Enter)", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright); + gemui_fill_rect(cr, gemui_rect_t{box.x + spx(4, ui), box.y + title_h, + box.w - spx(8, ui), std::max(1, spx(1, ui))}, + t->divider); + + if (menu_sel_ < menu_scroll_) menu_scroll_ = menu_sel_; + if (menu_sel_ >= menu_scroll_ + vis_rows) menu_scroll_ = menu_sel_ - vis_rows + 1; + menu_scroll_ = std::clamp(menu_scroll_, 0, std::max(0, kMenuItemCount - vis_rows)); + + int item_inset = spx(4, ui); + int text_inset = spx(6, ui); + for (int i = 0; i < vis_rows; ++i) { + int idx = menu_scroll_ + i; + if (idx >= kMenuItemCount) break; + gemui_rect_t ir{box.x + item_inset, box.y + title_h + spx(3, ui) + i * row_h, + box.w - item_inset * 2, std::max(4, row_h - 1)}; + bool sel = (idx == menu_sel_); + if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg); + gemui_draw_text(cr, t, + gemui_rect_t{ir.x + text_inset, ir.y, + std::max(1, ir.w - text_inset * 2), ir.h}, + kMenuItems[idx].label, font_delta, sel, GEMUI_ALIGN_LEFT, + sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app_, ir, HIT_MENU_ITEM, idx); + } + return; + } + + if (modal_ == ModalKind::FormatCell) { + int mw = std::min(w - margin_x, spx(ui.compact ? 224 : 280, ui)); + int row_h = spx(ui.compact ? 18 : (ui.touch ? 32 : 28), ui); + int title_h = spx(ui.compact ? 20 : 28, ui); + int mh = std::min(h - margin_y, title_h + kFormatPresetCount * row_h + spx(8, ui)); + gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(2, ui), box.w - pad * 2, title_h}, + "Cell Format", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright); + gemui_fill_rect(cr, gemui_rect_t{box.x + spx(4, ui), box.y + title_h, + box.w - spx(8, ui), std::max(1, spx(1, ui))}, + t->divider); + + int item_inset = spx(4, ui); + int text_inset = spx(6, ui); + for (int i = 0; i < kFormatPresetCount; ++i) { + gemui_rect_t ir{box.x + item_inset, box.y + title_h + spx(4, ui) + i * row_h, + box.w - item_inset * 2, std::max(4, row_h - 1)}; + bool sel = (i == format_sel_); + if (sel) gemui_fill_round(cr, ir, 3.0 * ui.scale, t->sel_bg); + gemui_draw_text(cr, t, + gemui_rect_t{ir.x + text_inset, ir.y, + std::max(1, ir.w - text_inset * 2), ir.h}, + kFormatPresets[i].label, font_delta, sel, GEMUI_ALIGN_LEFT, + sel ? t->sel_fg : t->fg_main); + gemui_hit_add(app_, ir, HIT_FORMAT_ITEM, i); + } + return; + } + + if (modal_ == ModalKind::Help) { + int edge_pad = spx(ui.compact ? 4 : 8, ui); + int inner_pad = spx(ui.compact ? 4 : 8, ui); + int mw = std::min(w - edge_pad * 2, spx(ui.compact ? 232 : 540, ui)); + int mh = std::min(h - edge_pad * 2, spx(ui.compact ? 284 : 460, ui)); + gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + int gap = spx(ui.compact ? 3 : 6, ui); + int title_h = spx(ui.compact ? 20 : 28, ui); + int foot_h = spx(ui.compact ? 20 : (ui.touch ? 32 : 26), ui); + int close_w = spx(ui.compact ? 20 : 28, ui); + int ix = box.x + inner_pad; + int iw = box.w - inner_pad * 2; + int y = box.y + inner_pad; + + gemui_draw_text(cr, t, gemui_rect_t{ix + 2, y, std::max(1, iw - close_w - gap), title_h}, + ui.compact ? "Shortcuts (F1)" : "Keyboard Hints (F1)", font_delta, true, + GEMUI_ALIGN_LEFT, t->fg_bright); + draw_ui_button(app_, cr, gemui_rect_t{ix + iw - close_w, y, close_w, title_h}, "x", fpx, ui, + HIT_MODAL_CANCEL, 0, false, false, false); + + y += title_h + spx(2, ui); + gemui_fill_rect(cr, gemui_rect_t{ix, y, iw, std::max(1, spx(1, ui))}, t->divider); + y += gap; + + int foot_y = box.y + box.h - inner_pad - foot_h; + int list_h = std::max(spx(30, ui), foot_y - gap - y); + gemui_rect_t list_r{ix, y, iw, list_h}; + gemui_fill_round(cr, list_r, 3.0 * ui.scale, t->bg_main); + gemui_stroke_round(cr, list_r, 3.0 * ui.scale, std::max(1.0, ui.scale), t->border); + + int row_h = spx(ui.compact ? 17 : (ui.touch ? 28 : 22), ui); + int vis = std::max(1, (list_r.h - 4) / std::max(1, row_h)); + help_visible_rows_ = vis; + int max_scroll = std::max(0, kHelpItemCount - vis); + help_scroll_ = std::clamp(help_scroll_, 0, max_scroll); + + bool need_sb = (kHelpItemCount > vis); + int sb_w = need_sb ? spx(ui.compact ? 5 : 8, ui) : 0; + int row_w = std::max(10, list_r.w - 4 - sb_w - (need_sb ? 2 : 0)); + int key_w = spx(ui.compact ? 84 : 155, ui); + int desc_x_off = key_w + spx(ui.compact ? 4 : 10, ui); + int small_delta = pt_delta_for_ui(t, ui.compact ? 9 : 12, ui); + + for (int i = 0; i < vis; ++i) { + int idx = help_scroll_ + i; + if (idx >= kHelpItemCount) break; + int ry = list_r.y + 2 + i * row_h; + gemui_rect_t rr{list_r.x + 2, ry, row_w, std::max(4, row_h - 1)}; + if ((idx % 2) == 1) { + gemui_fill_rect(cr, rr, t->bg_bar); + } + gemui_draw_text(cr, t, gemui_rect_t{rr.x + spx(3, ui), rr.y, key_w, rr.h}, + kHelpItems[idx].key, small_delta, true, GEMUI_ALIGN_LEFT, t->accent); + const char* desc = ui.compact ? kHelpItems[idx].compact_desc : kHelpItems[idx].desc; + int dw = std::max(4, rr.w - desc_x_off - spx(2, ui)); + gemui_draw_text(cr, t, gemui_rect_t{rr.x + desc_x_off, rr.y, dw, rr.h}, + desc, small_delta, false, GEMUI_ALIGN_LEFT, t->fg_main); + } + + if (need_sb) { + gemui_rect_t sb_r{list_r.x + list_r.w - sb_w - 2, list_r.y + 2, sb_w, + std::max(8, list_r.h - 4)}; + gemui_fill_round(cr, sb_r, sb_w * 0.5, t->bg_bar); + int thumb_h = std::max(spx(14, ui), (sb_r.h * vis) / kHelpItemCount); + thumb_h = std::min(sb_r.h, thumb_h); + int thumb_y = sb_r.y; + if (max_scroll > 0 && sb_r.h > thumb_h) { + thumb_y += ((sb_r.h - thumb_h) * help_scroll_) / max_scroll; + } + gemui_fill_round(cr, gemui_rect_t{sb_r.x + 1, thumb_y, std::max(2, sb_r.w - 2), thumb_h}, + sb_w * 0.5, t->accent); + } + + int close_btn_w = spx(ui.compact ? 56 : 86, ui); + int hint_w = std::max(1, iw - close_btn_w - gap); + gemui_draw_text(cr, t, gemui_rect_t{ix, foot_y, hint_w, foot_h}, + ui.compact ? "Up/Dn Esc:Close" : "Scroll: Up/Down Close: F1 or Esc", + small_delta, false, GEMUI_ALIGN_LEFT, t->fg_muted); + draw_ui_button(app_, cr, gemui_rect_t{ix + iw - close_btn_w, foot_y, close_btn_w, foot_h}, + "Close", fpx, ui, HIT_MODAL_CANCEL, 0, true, false, true); + return; + } + + if (modal_ == ModalKind::ConfirmExit) { + int edge_pad = spx(ui.compact ? 4 : 12, ui); + int inner_pad = spx(ui.compact ? 6 : 12, ui); + int gap = spx(ui.compact ? 4 : 8, ui); + int mw = std::min(w - edge_pad * 2, spx(ui.compact ? 232 : 420, ui)); + int title_h = spx(ui.compact ? 20 : 28, ui); + int msg_h = spx(ui.compact ? 26 : 36, ui); + int btn_h = spx(ui.compact ? 22 : (ui.touch ? 32 : 28), ui); + int mh = title_h + msg_h + btn_h + inner_pad * 2 + gap * 2 + spx(4, ui); + gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + int ix = box.x + inner_pad; + int iw = box.w - inner_pad * 2; + int y = box.y + inner_pad; + + gemui_draw_text(cr, t, gemui_rect_t{ix, y, iw, title_h}, + "Unsaved Changes", font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright); + y += title_h + spx(2, ui); + gemui_fill_rect(cr, gemui_rect_t{ix, y, iw, std::max(1, spx(1, ui))}, t->divider); + y += gap; + + std::string fname = display_filename(); + std::string prompt = ui.compact ? ("Save " + fname + "?") + : ("Save changes to " + fname + " before exiting?"); + gemui_draw_text(cr, t, gemui_rect_t{ix, y, iw, msg_h}, prompt.c_str(), font_delta, false, + GEMUI_ALIGN_LEFT, t->fg_main); + + int btn_y = box.y + box.h - inner_pad - btn_h; + int btn_gap = spx(ui.compact ? 4 : 8, ui); + int btn_w = std::max(spx(32, ui), (iw - btn_gap * 2) / 3); + draw_ui_button(app_, cr, gemui_rect_t{ix, btn_y, btn_w, btn_h}, "Save", fpx, ui, + HIT_EXIT_SAVE, 0, true, false, exit_sel_ == 0); + draw_ui_button(app_, cr, gemui_rect_t{ix + btn_w + btn_gap, btn_y, btn_w, btn_h}, "Discard", + fpx, ui, HIT_EXIT_DISCARD, 0, false, false, exit_sel_ == 1); + draw_ui_button(app_, cr, gemui_rect_t{ix + (btn_w + btn_gap) * 2, btn_y, + iw - (btn_w + btn_gap) * 2, btn_h}, + "Cancel", fpx, ui, HIT_EXIT_CANCEL, 0, false, false, exit_sel_ == 2); + return; + } + + const char* title = "Rename Sheet"; + const char* ph = "Sheet name"; + if (modal_ == ModalKind::GoToCell) { + title = "Go To Cell"; + ph = ui.compact ? "C25 or Sheet2!A1" : "e.g. C25, Sheet2!B4, A1:C10"; + } + + int mw = std::min(w - spx(10, ui), spx(ui.compact ? 300 : 380, ui)); + int title_h = spx(ui.compact ? 20 : 26, ui); + int inp_h = spx(ui.compact ? 22 : 32, ui); + int btn_h = spx(ui.compact ? 20 : (ui.touch ? 32 : 28), ui); + int btn_w = spx(ui.compact ? 64 : 88, ui); + int mh = title_h + inp_h + btn_h + spx(22, ui); + gemui_rect_t box{(w - mw) / 2, (h - mh) / 2, mw, mh}; + + gemui_fill_round(cr, box, box_rad, t->bg_overlay); + gemui_stroke_round(cr, box, box_rad, box_lw, t->accent); + gemui_hit_add(app_, box, HIT_NONE, 0); + + gemui_draw_text(cr, t, gemui_rect_t{box.x + pad, box.y + spx(3, ui), box.w - pad * 2, title_h}, + title, font_delta, true, GEMUI_ALIGN_LEFT, t->fg_bright); + + gemui_rect_t inp_r{box.x + pad, box.y + title_h + spx(6, ui), box.w - pad * 2, inp_h}; + draw_single_line_editor(cr, t, inp_r, modal_editor_, ph, true, fpx, ui); + gemui_hit_add(app_, inp_r, HIT_MODAL_INPUT, 0); + + int btn_y = box.y + box.h - btn_h - pad; + gemui_rect_t cancel_r{box.x + box.w - btn_w - pad, btn_y, btn_w, btn_h}; + gemui_rect_t ok_r{cancel_r.x - btn_w - spx(6, ui), btn_y, btn_w, btn_h}; + draw_ui_button(app_, cr, ok_r, "OK", fpx, ui, HIT_MODAL_OK, 0, true, false, false); + draw_ui_button(app_, cr, cancel_r, "Cancel", fpx, ui, HIT_MODAL_CANCEL, 0, false, false, false); +} + +void AppWindow::draw(cairo_t* cr, int w, int h) { + Layout lay = compute_layout(w, h); + draw_top_bar(cr, lay); + + std::string addr = col_to_letters(grid_.active_col()) + std::to_string(grid_.active_row() + 1); + formula_bar_.draw(app_, cr, lay.formula_bar, addr, grid_.editor(), + grid_.is_editing() && grid_.is_formula_bar_focused(), lay.ui, + HIT_ADDR_BOX, HIT_FORMULA_INPUT); + + grid_.draw(app_, cr, wb_, lay.grid, lay.ui); + draw_bottom_bar(cr, lay); + draw_modal(cr, w, h, lay.ui); +} + +void AppWindow::commit_edit_if_active() { + if (!grid_.is_editing()) return; + const Cell* c = wb_.get_cell(wb_.active_sheet(), grid_.active_row(), grid_.active_col()); + std::string prev = c ? c->raw_input : ""; + std::string next = grid_.editor().text; + grid_.commit_edit(wb_); + if (next != prev) { + dirty_ = true; + update_title(); + } +} + +void AppWindow::open_modal(ModalKind kind, const std::string& initial_text) { + commit_edit_if_active(); + modal_ = kind; + if (kind == ModalKind::Menu) { + menu_sel_ = 0; + menu_scroll_ = 0; + } else if (kind == ModalKind::Help) { + help_scroll_ = 0; + } else if (kind == ModalKind::ConfirmExit) { + exit_sel_ = 0; + quit_after_save_ = false; + } else if (kind == ModalKind::FormatCell) { + format_sel_ = 0; + const Cell* c = wb_.get_cell(wb_.active_sheet(), grid_.active_row(), grid_.active_col()); + std::string cur = c ? c->number_format : ""; + for (int i = 0; i < kFormatPresetCount; ++i) { + if (cur == kFormatPresets[i].fmt) { + format_sel_ = i; + break; + } + } + } else if (kind != ModalKind::ContextMenu) { + modal_editor_.set_text(initial_text); + } + gemui_request_redraw(app_); +} + +void AppWindow::close_modal() { + modal_ = ModalKind::Closed; + ctx_items_.clear(); + gemui_request_redraw(app_); +} + +void AppWindow::request_quit() { + commit_edit_if_active(); + if (gemui_file_dialog_active(app_)) { + gemui_file_dialog_close(app_); + } + if (!dirty_) { + gemui_quit(app_, 0); + return; + } + open_modal(ModalKind::ConfirmExit); +} + +void AppWindow::confirm_exit_save() { + close_modal(); + if (!current_path_.empty() && + (ends_with_ci(current_path_, ".htab") || ends_with_ci(current_path_, ".json"))) { + if (save_native_to(current_path_)) { + gemui_quit(app_, 0); + } + return; + } + quit_after_save_ = true; + save_native_dialog(); +} + +std::string AppWindow::dialog_initial_dir() const { + if (current_path_.empty()) return ""; + size_t slash = current_path_.find_last_of('/'); + if (slash == std::string::npos) return ""; + if (slash == 0) return "/"; + return current_path_.substr(0, slash); +} + +std::string AppWindow::dialog_initial_name(const std::string& default_name, + const std::string& ext_override, + const std::string& suffix_before_ext) const { + if (current_path_.empty()) return default_name; + size_t slash = current_path_.find_last_of('/'); + std::string base = (slash == std::string::npos) ? current_path_ : current_path_.substr(slash + 1); + if (base.empty()) return default_name; + size_t dot = base.find_last_of('.'); + std::string stem = (dot == std::string::npos) ? base : base.substr(0, dot); + if (stem.empty()) return default_name; + return stem + suffix_before_ext + ext_override; +} + +void AppWindow::open_file_dialog() { + if (grid_.is_editing()) grid_.commit_edit(wb_); + if (modal_ != ModalKind::Closed) close_modal(); + std::string dir = dialog_initial_dir(); + gemui_open_file_dialog(app_, "Open Workbook / CSV", dir.empty() ? nullptr : dir.c_str(), + ".htab,.csv,.json", &AppWindow::cb_open_file_done, this); +} + +void AppWindow::save_native_dialog() { + if (grid_.is_editing()) grid_.commit_edit(wb_); + if (modal_ != ModalKind::Closed) close_modal(); + std::string dir = dialog_initial_dir(); + std::string name = dialog_initial_name("workbook.htab", ".htab"); + gemui_save_file_dialog(app_, "Save Workbook (.htab)", + dir.empty() ? nullptr : dir.c_str(), name.c_str(), + ".htab,.json", ".htab", &AppWindow::cb_save_native_done, this); +} + +void AppWindow::export_csv_dialog(bool formulas) { + if (grid_.is_editing()) grid_.commit_edit(wb_); + if (modal_ != ModalKind::Closed) close_modal(); + std::string dir = dialog_initial_dir(); + std::string name = dialog_initial_name(formulas ? "export_formulas.csv" : "export.csv", + ".csv", formulas ? "_formulas" : ""); + gemui_save_file_dialog(app_, + formulas ? "Export CSV (Formulas)" : "Export CSV (Values)", + dir.empty() ? nullptr : dir.c_str(), name.c_str(), + ".csv", ".csv", + formulas ? &AppWindow::cb_export_csv_formulas_done + : &AppWindow::cb_export_csv_values_done, + this); +} + +void AppWindow::delete_selected_rows() { + if (grid_.is_editing()) grid_.commit_edit(wb_); + int sheet = wb_.active_sheet(); + CellRange sel = grid_.selection_range(sheet); + wb_.delete_rows(sheet, sel.r1, sel.row_count()); + grid_.set_active_cell(wb_, sel.r1, grid_.active_col(), false); + grid_.sync_editor_from_cell(wb_); + dirty_ = true; + update_title(); +} + +void AppWindow::delete_selected_cols() { + if (grid_.is_editing()) grid_.commit_edit(wb_); + int sheet = wb_.active_sheet(); + CellRange sel = grid_.selection_range(sheet); + wb_.delete_cols(sheet, sel.c1, sel.col_count()); + grid_.set_active_cell(wb_, grid_.active_row(), sel.c1, false); + grid_.sync_editor_from_cell(wb_); + dirty_ = true; + update_title(); +} + +void AppWindow::close_sheet(int idx) { + if (grid_.is_editing()) grid_.commit_edit(wb_); + if (wb_.delete_sheet(idx)) { + dirty_ = true; + if (tab_scroll_ >= wb_.sheet_count()) { + tab_scroll_ = std::max(0, wb_.sheet_count() - 1); + } + grid_.reset_for_sheet(wb_, wb_.active_sheet()); + update_title(); + gemui_show_toast(app_, "Sheet closed", 1400); + } else { + gemui_show_toast(app_, "Cannot delete last sheet", 1800); + } + gemui_request_redraw(app_); +} + +void AppWindow::execute_menu_action(int index) { + close_modal(); + switch (index) { + case 0: { + std::vector fresh(1); + fresh[0].name = "Sheet1"; + wb_.replace_all_sheets(std::move(fresh), 0); + current_path_.clear(); + dirty_ = false; + grid_.reset_for_sheet(wb_, 0); + update_title(); + gemui_show_toast(app_, "New workbook", 1500); + break; + } + case 1: + open_file_dialog(); + break; + case 2: + save_native_dialog(); + break; + case 3: + export_csv_dialog(false); + break; + case 4: + export_csv_dialog(true); + break; + case 5: + wb_.insert_rows(wb_.active_sheet(), grid_.active_row(), 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case 6: + delete_selected_rows(); + break; + case 7: + wb_.insert_cols(wb_.active_sheet(), grid_.active_col(), 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case 8: + delete_selected_cols(); + break; + case 9: + open_modal(ModalKind::FormatCell); + break; + case 10: + add_new_sheet(); + break; + case 11: + open_modal(ModalKind::RenameSheet, wb_.sheet(wb_.active_sheet()).name); + break; + case 12: + close_sheet(wb_.active_sheet()); + break; + case 13: + open_modal(ModalKind::GoToCell); + break; + case 14: + open_modal(ModalKind::Help); + break; + case 15: + request_quit(); + break; + default: + break; + } + gemui_request_redraw(app_); +} + +void AppWindow::execute_ctx_action(CtxAction action) { + int target_sheet = ctx_target_sheet_; + close_modal(); + int active = wb_.active_sheet(); + CellRange sel = grid_.selection_range(active); + + switch (action) { + case CtxAction::Copy: + do_copy(false); + break; + case CtxAction::Cut: + do_copy(true); + break; + case CtxAction::Paste: + do_paste(); + break; + case CtxAction::ClearCells: + clear_selection(); + break; + case CtxAction::FormatCell: + open_modal(ModalKind::FormatCell); + break; + case CtxAction::InsertRowAbove: + wb_.insert_rows(active, sel.r1, 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case CtxAction::InsertRowBelow: + wb_.insert_rows(active, sel.r2 + 1, 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case CtxAction::DeleteRow: + delete_selected_rows(); + break; + case CtxAction::InsertColLeft: + wb_.insert_cols(active, sel.c1, 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case CtxAction::InsertColRight: + wb_.insert_cols(active, sel.c2 + 1, 1); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + break; + case CtxAction::DeleteCol: + delete_selected_cols(); + break; + case CtxAction::RenameSheet: + if (target_sheet >= 0 && target_sheet < wb_.sheet_count()) { + switch_sheet(target_sheet); + open_modal(ModalKind::RenameSheet, wb_.sheet(target_sheet).name); + } + break; + case CtxAction::AddSheet: + add_new_sheet(); + break; + case CtxAction::DeleteSheet: + close_sheet(target_sheet); + break; + } + gemui_request_redraw(app_); +} + +void AppWindow::handle_right_click(int x, int y) { + if (modal_ == ModalKind::ContextMenu) { + close_modal(); + } else if (modal_ != ModalKind::Closed) { + return; + } + + if (grid_.is_editing()) { + grid_.commit_edit(wb_); + } + + // Check sheet tabs first + for (const auto& [rect, sidx] : last_tab_rects_) { + if (point_in_rect(rect, x, y)) { + ctx_items_.clear(); + ctx_items_.push_back({"Rename Sheet...", CtxAction::RenameSheet}); + ctx_items_.push_back({"Add Sheet", CtxAction::AddSheet}); + if (wb_.sheet_count() > 1) { + ctx_items_.push_back({"Close Sheet", CtxAction::DeleteSheet}); + } + ctx_x_ = x; + ctx_y_ = y; + ctx_sel_ = 0; + ctx_target_sheet_ = sidx; + open_modal(ModalKind::ContextMenu); + return; + } + } + + int r = 0, c = 0; + GridHitRegion reg = grid_.hit_region(wb_, x, y, r, c); + if (reg == GridHitRegion::Outside) return; + + int active = wb_.active_sheet(); + CellRange sel = grid_.selection_range(active); + + ctx_items_.clear(); + if (reg == GridHitRegion::RowHeader) { + if (r < sel.r1 || r > sel.r2) { + grid_.set_active_cell(wb_, r, grid_.active_col(), false); + } + ctx_items_.push_back({"Insert Row Above", CtxAction::InsertRowAbove}); + ctx_items_.push_back({"Insert Row Below", CtxAction::InsertRowBelow}); + ctx_items_.push_back({"Delete Row", CtxAction::DeleteRow}); + ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell}); + } else if (reg == GridHitRegion::ColHeader) { + if (c < sel.c1 || c > sel.c2) { + grid_.set_active_cell(wb_, grid_.active_row(), c, false); + } + ctx_items_.push_back({"Insert Column Left", CtxAction::InsertColLeft}); + ctx_items_.push_back({"Insert Column Right", CtxAction::InsertColRight}); + ctx_items_.push_back({"Delete Column", CtxAction::DeleteCol}); + ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell}); + } else { // DataCell + if (!sel.contains(active, r, c)) { + grid_.set_active_cell(wb_, r, c, false); + } + ctx_items_.push_back({"Copy", CtxAction::Copy}); + ctx_items_.push_back({"Cut", CtxAction::Cut}); + ctx_items_.push_back({"Paste", CtxAction::Paste}); + ctx_items_.push_back({"Clear Cell(s)", CtxAction::ClearCells}); + ctx_items_.push_back({"Format Cell...", CtxAction::FormatCell}); + ctx_items_.push_back({"Insert Row Above", CtxAction::InsertRowAbove}); + ctx_items_.push_back({"Delete Row", CtxAction::DeleteRow}); + ctx_items_.push_back({"Insert Column Left", CtxAction::InsertColLeft}); + ctx_items_.push_back({"Delete Column", CtxAction::DeleteCol}); + } + + ctx_x_ = x; + ctx_y_ = y; + ctx_sel_ = 0; + ctx_target_sheet_ = active; + open_modal(ModalKind::ContextMenu); +} + +bool AppWindow::jump_to_address(const std::string& raw) { + std::string s(trim_ascii(raw)); + if (s.empty()) return false; + + // Skip over optional sheet prefix before searching for range separator ':'. + size_t search_from = 0; + if (s[0] == '\'') { + size_t pos = 1; + while (pos < s.size()) { + if (s[pos] == '\'') { + if (pos + 1 < s.size() && s[pos + 1] == '\'') { + pos += 2; + } else { + ++pos; + break; + } + } else { + ++pos; + } + } + if (pos < s.size() && s[pos] == '!') search_from = pos + 1; + } else { + size_t bang = s.find('!'); + if (bang != std::string::npos) search_from = bang + 1; + } + + size_t colon = s.find(':', search_from); + std::string_view left_sv = + (colon == std::string::npos) + ? std::string_view(s) + : trim_ascii(std::string_view(s).substr(0, colon)); + auto left = parse_cell_ref(left_sv); + if (!left.has_value() || left->invalid) { + gemui_show_toast(app_, "Invalid cell reference", 1800); + return false; + } + + std::optional right; + if (colon != std::string::npos) { + std::string_view right_sv = trim_ascii(std::string_view(s).substr(colon + 1)); + right = parse_cell_ref(right_sv); + if (!right.has_value() || right->invalid || + (!right->sheet_name.empty() && right->sheet_name != left->sheet_name)) { + gemui_show_toast(app_, "Invalid cell reference", 1800); + return false; + } + } + + if (!left->sheet_name.empty()) { + int sidx = wb_.find_sheet(left->sheet_name); + if (sidx < 0) { + gemui_show_toast(app_, "Sheet not found", 1800); + return false; + } + if (sidx != wb_.active_sheet()) { + switch_sheet(sidx); + } + } + + if (right.has_value()) { + grid_.set_active_cell(wb_, right->row, right->col, false); + grid_.set_active_cell(wb_, left->row, left->col, true); + } else { + grid_.set_active_cell(wb_, left->row, left->col, false); + } + gemui_request_redraw(app_); + return true; +} + +void AppWindow::accept_modal_dialog() { + std::string val(trim_ascii(modal_editor_.text)); + ModalKind kind = modal_; + close_modal(); + if (val.empty()) return; + + if (kind == ModalKind::GoToCell) { + jump_to_address(val); + } else if (kind == ModalKind::RenameSheet) { + if (wb_.rename_sheet(wb_.active_sheet(), val)) { + dirty_ = true; + update_title(); + gemui_show_toast(app_, "Sheet renamed", 1500); + } else { + gemui_show_toast(app_, "Invalid or duplicate sheet name", 2000); + } + } +} + +bool AppWindow::load_file_auto(const std::string& path) { + std::string err; + bool ok = false; + if (ends_with_ci(path, ".csv")) { + ok = import_csv_file(wb_, wb_.active_sheet(), path, &err); + } else { + ok = load_native_file(wb_, path, &err); + if (!ok && !ends_with_ci(path, ".htab") && !ends_with_ci(path, ".json")) { + std::string csv_err; + if (import_csv_file(wb_, wb_.active_sheet(), path, &csv_err)) { + ok = true; + } + } + } + if (ok) { + current_path_ = path; + dirty_ = false; + grid_.reset_for_sheet(wb_, wb_.active_sheet()); + update_title(); + gemui_show_toast(app_, "Loaded", 1200); + } else { + gemui_show_toast(app_, err.empty() ? "Load failed" : err.c_str(), 2200); + } + gemui_request_redraw(app_); + return ok; +} + +bool AppWindow::save_native_to(const std::string& path) { + std::string err; + if (save_native_file(wb_, path, &err)) { + current_path_ = path; + dirty_ = false; + update_title(); + gemui_show_toast(app_, "Saved", 1200); + gemui_request_redraw(app_); + return true; + } + gemui_show_toast(app_, err.empty() ? "Save failed" : err.c_str(), 2500); + gemui_request_redraw(app_); + return false; +} + +void AppWindow::export_csv_to(const std::string& path, bool formulas) { + std::string err; + if (export_csv_file(wb_, wb_.active_sheet(), path, formulas, &err)) { + gemui_show_toast(app_, "CSV exported", 1800); + } else { + gemui_show_toast(app_, err.c_str(), 2500); + } +} + +void AppWindow::do_copy(bool is_cut) { + CellRange sel = grid_.selection_range(wb_.active_sheet()); + ClipboardGrid grid = wb_.copy_range(wb_.active_sheet(), sel, is_cut); + clipboard_.copy_grid(grid); + gemui_show_toast(app_, is_cut ? "Cut" : "Copied", 1000); +} + +void AppWindow::do_paste() { + if (clipboard_.has_internal()) { + wb_.paste_range(wb_.active_sheet(), grid_.active_row(), grid_.active_col(), + clipboard_.internal_grid(), true); + clipboard_.clear_cut_flag(); + } else { + std::string ext = clipboard_.get_external_text(app_); + if (ext.empty()) return; + auto edits = X11Clipboard::parse_tsv_to_edits(ext, grid_.active_row(), grid_.active_col()); + wb_.apply_cell_edits(wb_.active_sheet(), edits); + } + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); +} + +void AppWindow::clear_selection() { + int sheet = wb_.active_sheet(); + CellRange sel = grid_.selection_range(sheet); + if (static_cast(sel.row_count()) * sel.col_count() > 10000) return; + std::vector edits; + for (int r = sel.r1; r <= sel.r2; ++r) { + for (int c = sel.c1; c <= sel.c2; ++c) { + if (wb_.get_cell(sheet, r, c)) { + edits.push_back(CellEdit{r, c, "", std::nullopt}); + } + } + } + if (!edits.empty()) { + wb_.apply_cell_edits(sheet, edits); + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + } +} + +void AppWindow::switch_sheet(int idx) { + if (idx < 0 || idx >= wb_.sheet_count()) return; + if (grid_.is_editing()) grid_.commit_edit(wb_); + wb_.set_active_sheet(idx); + grid_.reset_for_sheet(wb_, idx); + if (idx < tab_scroll_) tab_scroll_ = idx; + gemui_request_redraw(app_); +} + +void AppWindow::add_new_sheet() { + if (grid_.is_editing()) grid_.commit_edit(wb_); + int idx = wb_.add_sheet(); + if (idx >= 0) { + dirty_ = true; + wb_.set_active_sheet(idx); + grid_.reset_for_sheet(wb_, idx); + update_title(); + gemui_show_toast(app_, wb_.sheet(idx).name.c_str(), 1000); + } +} + +void AppWindow::handle_modal_key(KeySym ks, unsigned int state, const char* utf8) { + if (ks == XK_Escape) { + close_modal(); + return; + } + + if (modal_ == ModalKind::ContextMenu) { + if (ctx_items_.empty()) { + close_modal(); + return; + } + int n = static_cast(ctx_items_.size()); + if (ks == XK_Up) { + ctx_sel_ = (ctx_sel_ - 1 + n) % n; + } else if (ks == XK_Down) { + ctx_sel_ = (ctx_sel_ + 1) % n; + } else if (ks == XK_Return || ks == XK_KP_Enter) { + execute_ctx_action(ctx_items_[static_cast(ctx_sel_)].action); + } + gemui_request_redraw(app_); + return; + } + + if (modal_ == ModalKind::Menu) { + if (ks == XK_Up) { + menu_sel_ = (menu_sel_ - 1 + kMenuItemCount) % kMenuItemCount; + } else if (ks == XK_Down) { + menu_sel_ = (menu_sel_ + 1) % kMenuItemCount; + } else if (ks == XK_Return || ks == XK_KP_Enter) { + execute_menu_action(menu_sel_); + } + gemui_request_redraw(app_); + return; + } + + if (modal_ == ModalKind::FormatCell) { + if (ks == XK_Up) { + format_sel_ = (format_sel_ - 1 + kFormatPresetCount) % kFormatPresetCount; + } else if (ks == XK_Down) { + format_sel_ = (format_sel_ + 1) % kFormatPresetCount; + } else if (ks == XK_Return || ks == XK_KP_Enter) { + CellRange sel = grid_.selection_range(wb_.active_sheet()); + wb_.apply_range_format(wb_.active_sheet(), sel, kFormatPresets[format_sel_].fmt); + dirty_ = true; + close_modal(); + update_title(); + } + gemui_request_redraw(app_); + return; + } + + if (modal_ == ModalKind::Help) { + int max_scroll = std::max(0, kHelpItemCount - std::max(1, help_visible_rows_)); + if (ks == XK_F1 || ks == XK_Return || ks == XK_KP_Enter || ks == XK_q || ks == XK_Q) { + close_modal(); + return; + } + if (ks == XK_Up) { + help_scroll_ = std::max(0, help_scroll_ - 1); + } else if (ks == XK_Down) { + help_scroll_ = std::min(max_scroll, help_scroll_ + 1); + } else if (ks == XK_Page_Up) { + help_scroll_ = std::max(0, help_scroll_ - std::max(1, help_visible_rows_ - 1)); + } else if (ks == XK_Page_Down) { + help_scroll_ = std::min(max_scroll, help_scroll_ + std::max(1, help_visible_rows_ - 1)); + } else if (ks == XK_Home) { + help_scroll_ = 0; + } else if (ks == XK_End) { + help_scroll_ = max_scroll; + } + gemui_request_redraw(app_); + return; + } + + if (modal_ == ModalKind::ConfirmExit) { + bool shift = (state & ShiftMask) != 0; + if (ks == XK_Left || (ks == XK_Tab && shift) || ks == XK_ISO_Left_Tab) { + exit_sel_ = (exit_sel_ + 2) % 3; + gemui_request_redraw(app_); + return; + } + if (ks == XK_Right || ks == XK_Tab) { + exit_sel_ = (exit_sel_ + 1) % 3; + gemui_request_redraw(app_); + return; + } + if (ks == XK_s || ks == XK_S) { + confirm_exit_save(); + return; + } + if (ks == XK_d || ks == XK_D) { + gemui_quit(app_, 0); + return; + } + if (ks == XK_c || ks == XK_C) { + close_modal(); + return; + } + if (ks == XK_Return || ks == XK_KP_Enter) { + if (exit_sel_ == 0) confirm_exit_save(); + else if (exit_sel_ == 1) gemui_quit(app_, 0); + else close_modal(); + return; + } + return; + } + + if (ks == XK_Return || ks == XK_KP_Enter) { + accept_modal_dialog(); + return; + } + bool ctrl = (state & ControlMask) != 0; + if (ctrl && normalize_ctrl_keysym(ks) == XK_v) { + std::string ext = clipboard_.get_external_text(app_); + if (!ext.empty()) modal_editor_.insert_utf8(ext.c_str()); + gemui_request_redraw(app_); + return; + } + if (modal_editor_.handle_key(ks, state, utf8)) { + gemui_request_redraw(app_); + } +} + +void AppWindow::handle_key(KeySym ks, unsigned int state, const char* utf8) { + if (modal_ != ModalKind::Closed) { + handle_modal_key(ks, state, utf8); + return; + } + + bool shift = (state & ShiftMask) != 0; + bool ctrl = (state & ControlMask) != 0; + bool alt = (state & Mod1Mask) != 0; + + if (grid_.is_editing()) { + if (ctrl && normalize_ctrl_keysym(ks) == XK_q) { + request_quit(); + return; + } + if (ctrl && normalize_ctrl_keysym(ks) == XK_g) { + open_modal(ModalKind::GoToCell); + return; + } + if (ks == XK_F1) { + open_modal(ModalKind::Help); + return; + } + if (ks == XK_Escape) { + grid_.cancel_edit(wb_); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Return || ks == XK_KP_Enter) { + grid_.commit_edit(wb_); + dirty_ = true; + grid_.move_active(wb_, shift ? -1 : 1, 0, false); + update_title(); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Tab || ks == XK_ISO_Left_Tab) { + bool rev = shift || (ks == XK_ISO_Left_Tab); + grid_.commit_edit(wb_); + dirty_ = true; + grid_.move_active(wb_, 0, rev ? -1 : 1, false); + update_title(); + gemui_request_redraw(app_); + return; + } + if (ctrl && normalize_ctrl_keysym(ks) == XK_v) { + std::string ext = clipboard_.get_external_text(app_); + if (!ext.empty()) grid_.editor().insert_utf8(ext.c_str()); + gemui_request_redraw(app_); + return; + } + if (grid_.editor().handle_key(ks, state, utf8)) { + gemui_request_redraw(app_); + } + return; + } + + if (ctrl) { + KeySym ck = normalize_ctrl_keysym(ks); + if (ck == XK_c) { do_copy(false); gemui_request_redraw(app_); return; } + if (ck == XK_x) { do_copy(true); gemui_request_redraw(app_); return; } + if (ck == XK_v) { do_paste(); gemui_request_redraw(app_); return; } + if (ck == XK_z) { + if (wb_.undo()) { + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + gemui_show_toast(app_, "Undo", 900); + } + gemui_request_redraw(app_); + return; + } + if (ck == XK_y) { + if (wb_.redo()) { + dirty_ = true; + grid_.sync_editor_from_cell(wb_); + update_title(); + gemui_show_toast(app_, "Redo", 900); + } + gemui_request_redraw(app_); + return; + } + if (ck == XK_s) { + if (!current_path_.empty() && + (ends_with_ci(current_path_, ".htab") || ends_with_ci(current_path_, ".json"))) { + save_native_to(current_path_); + } else { + save_native_dialog(); + } + return; + } + if (ck == XK_o) { open_file_dialog(); return; } + if (ck == XK_e) { export_csv_dialog(false); return; } + if (ck == XK_g) { open_modal(ModalKind::GoToCell); return; } + if (ck == XK_n) { execute_menu_action(0); return; } + if (ck == XK_q) { request_quit(); return; } + if (ks == XK_Page_Up) { + if (wb_.active_sheet() > 0) switch_sheet(wb_.active_sheet() - 1); + return; + } + if (ks == XK_Page_Down) { + if (wb_.active_sheet() + 1 < wb_.sheet_count()) switch_sheet(wb_.active_sheet() + 1); + return; + } + if (ks == XK_Home) { + grid_.set_active_cell(wb_, 0, 0, shift); + gemui_request_redraw(app_); + return; + } + } + + if (ks == XK_F1) { open_modal(ModalKind::Help); return; } + if (ks == XK_F10) { open_modal(ModalKind::Menu); return; } + if (ks == XK_F2) { grid_.start_edit(wb_, false); gemui_request_redraw(app_); return; } + + if (ks == XK_Up) { grid_.move_active(wb_, -1, 0, shift); gemui_request_redraw(app_); return; } + if (ks == XK_Down) { grid_.move_active(wb_, 1, 0, shift); gemui_request_redraw(app_); return; } + if (ks == XK_Left) { grid_.move_active(wb_, 0, -1, shift); gemui_request_redraw(app_); return; } + if (ks == XK_Right) { grid_.move_active(wb_, 0, 1, shift); gemui_request_redraw(app_); return; } + + if (ks == XK_Return || ks == XK_KP_Enter) { + grid_.move_active(wb_, shift ? -1 : 1, 0, false); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Tab || ks == XK_ISO_Left_Tab) { + bool rev = shift || (ks == XK_ISO_Left_Tab); + grid_.move_active(wb_, 0, rev ? -1 : 1, false); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Page_Up) { + grid_.move_active(wb_, -10, 0, shift); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Page_Down) { + grid_.move_active(wb_, 10, 0, shift); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Home) { + grid_.set_active_cell(wb_, grid_.active_row(), 0, shift); + gemui_request_redraw(app_); + return; + } + if (ks == XK_Delete || ks == XK_BackSpace) { + clear_selection(); + gemui_request_redraw(app_); + return; + } + + if (!ctrl && !alt && utf8 && utf8[0]) { + std::string init(utf8); + grid_.start_edit(wb_, false, &init); + gemui_request_redraw(app_); + } +} + +void AppWindow::handle_ptr(int type, int x, int y, unsigned int btn) { + if (type == GEMUI_PTR_UP && hscroll_dragging_) { + hscroll_dragging_ = false; + gemui_request_redraw(app_); + return; + } + if (type == GEMUI_PTR_MOVE && hscroll_dragging_) { + grid_.handle_hscroll_drag(wb_, x, last_hscroll_r_); + gemui_request_redraw(app_); + return; + } + + if (type == GEMUI_PTR_DOWN && btn == Button3) { + handle_right_click(x, y); + return; + } + + if (modal_ != ModalKind::Closed) { + if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) { + int delta = (type == GEMUI_PTR_SCROLL_UP) ? -2 : 2; + if (modal_ == ModalKind::Help) { + int max_scroll = std::max(0, kHelpItemCount - std::max(1, help_visible_rows_)); + help_scroll_ = std::clamp(help_scroll_ + delta, 0, max_scroll); + gemui_request_redraw(app_); + } else if (modal_ == ModalKind::Menu) { + menu_sel_ = std::clamp(menu_sel_ + (delta > 0 ? 1 : -1), 0, kMenuItemCount - 1); + gemui_request_redraw(app_); + } + return; + } + if (type == GEMUI_PTR_DOWN && btn == Button1) { + const gemui_hit_t* hit = gemui_hit_test(app_, x, y); + if (!hit) return; + if (hit->id == HIT_MODAL_BACKDROP || hit->id == HIT_MODAL_CANCEL || + hit->id == HIT_EXIT_CANCEL) { + close_modal(); + } else if (hit->id == HIT_EXIT_SAVE) { + confirm_exit_save(); + return; + } else if (hit->id == HIT_EXIT_DISCARD) { + gemui_quit(app_, 0); + return; + } else if (hit->id == HIT_MENU_ITEM) { + execute_menu_action(hit->val); + } else if (hit->id == HIT_FORMAT_ITEM) { + CellRange sel = grid_.selection_range(wb_.active_sheet()); + wb_.apply_range_format(wb_.active_sheet(), sel, kFormatPresets[hit->val].fmt); + dirty_ = true; + close_modal(); + update_title(); + } else if (hit->id == HIT_CTX_ITEM) { + if (hit->val >= 0 && hit->val < static_cast(ctx_items_.size())) { + execute_ctx_action(ctx_items_[static_cast(hit->val)].action); + } + } else if (hit->id == HIT_MODAL_OK) { + accept_modal_dialog(); + } + gemui_request_redraw(app_); + } + return; + } + + if (type == GEMUI_PTR_DOWN) { + const gemui_hit_t* hit = gemui_hit_test(app_, x, y); + if (hit) { + if (btn == Button2 && hit->id == HIT_SHEET_TAB) { + close_sheet(hit->val); + return; + } + if (btn == Button1) { + switch (hit->id) { + case HIT_MENU_BTN: open_modal(ModalKind::Menu); return; + case HIT_OPEN_BTN: open_file_dialog(); return; + case HIT_SAVE_BTN: save_native_dialog(); return; + case HIT_CSV_BTN: export_csv_dialog(false); return; + case HIT_UNDO_BTN: + if (wb_.undo()) { dirty_ = true; grid_.sync_editor_from_cell(wb_); update_title(); } + gemui_request_redraw(app_); + return; + case HIT_REDO_BTN: + if (wb_.redo()) { dirty_ = true; grid_.sync_editor_from_cell(wb_); update_title(); } + gemui_request_redraw(app_); + return; + case HIT_FORMAT_BTN: open_modal(ModalKind::FormatCell); return; + case HIT_INS_ROW_BTN: execute_menu_action(5); return; + case HIT_DEL_ROW_BTN: delete_selected_rows(); return; + case HIT_INS_COL_BTN: execute_menu_action(7); return; + case HIT_DEL_COL_BTN: delete_selected_cols(); return; + case HIT_ADDR_BOX: + open_modal(ModalKind::GoToCell); + return; + case HIT_FORMULA_INPUT: + if (!grid_.is_editing()) grid_.start_edit(wb_, true); + else grid_.start_edit(wb_, true, &grid_.editor().text); + gemui_request_redraw(app_); + return; + case HIT_SHEET_TAB: + switch_sheet(hit->val); + return; + case HIT_SHEET_CLOSE: + close_sheet(hit->val); + return; + case HIT_ADD_SHEET: + add_new_sheet(); + gemui_request_redraw(app_); + return; + case HIT_HSCROLL: + hscroll_dragging_ = true; + grid_.handle_hscroll_drag(wb_, x, last_hscroll_r_); + gemui_request_redraw(app_); + return; + default: + break; + } + } + } + } + + bool committed = false; + if (grid_.handle_pointer(wb_, type, x, y, btn, last_hscroll_r_, committed)) { + if (committed) { + dirty_ = true; + update_title(); + } + gemui_request_redraw(app_); + } +} + +} // namespace htab::ui diff --git a/ui/app_window.hpp b/ui/app_window.hpp new file mode 100644 index 0000000..57d2394 --- /dev/null +++ b/ui/app_window.hpp @@ -0,0 +1,177 @@ +#pragma once + +#include "engine/workbook.hpp" +#include "ui/clipboard.hpp" +#include "ui/formula_bar.hpp" +#include "ui/grid_widget.hpp" +#include "ui/text_edit.hpp" + +#include +#include +#include +#include +#include + +namespace htab::ui { + +class AppWindow { + public: + int run(int req_w, int req_h, bool explicit_geometry, const std::string& initial_file); + + private: + enum HitId { + HIT_NONE = 0, + HIT_MENU_BTN, + HIT_UNDO_BTN, + HIT_REDO_BTN, + HIT_FORMAT_BTN, + HIT_OPEN_BTN, + HIT_SAVE_BTN, + HIT_CSV_BTN, + HIT_INS_ROW_BTN, + HIT_DEL_ROW_BTN, + HIT_INS_COL_BTN, + HIT_DEL_COL_BTN, + HIT_ADDR_BOX, + HIT_FORMULA_INPUT, + HIT_SHEET_TAB, + HIT_SHEET_CLOSE, + HIT_ADD_SHEET, + HIT_HSCROLL, + HIT_MENU_ITEM, + HIT_FORMAT_ITEM, + HIT_CTX_ITEM, + HIT_MODAL_INPUT, + HIT_MODAL_OK, + HIT_MODAL_CANCEL, + HIT_MODAL_BACKDROP, + HIT_EXIT_SAVE, + HIT_EXIT_DISCARD, + HIT_EXIT_CANCEL, + }; + + enum class ModalKind { + Closed, + Menu, + ContextMenu, + FormatCell, + RenameSheet, + GoToCell, + Help, + ConfirmExit, + }; + + enum class CtxAction { + Copy, + Cut, + Paste, + ClearCells, + FormatCell, + InsertRowAbove, + InsertRowBelow, + DeleteRow, + InsertColLeft, + InsertColRight, + DeleteCol, + RenameSheet, + AddSheet, + DeleteSheet, + }; + + struct CtxItem { + const char* label; + CtxAction action; + }; + + struct Layout { + UiScale ui; + gemui_rect_t top_bar{0, 0, 0, 0}; + gemui_rect_t formula_bar{0, 0, 0, 0}; + gemui_rect_t grid{0, 0, 0, 0}; + gemui_rect_t bottom_bar{0, 0, 0, 0}; + gemui_rect_t tabs_area{0, 0, 0, 0}; + gemui_rect_t hscroll{0, 0, 0, 0}; + }; + + static void cb_draw(gemui_app_t* app, cairo_t* cr, int w, int h, void* ud); + static void cb_key(gemui_app_t* app, KeySym ks, unsigned int state, const char* utf8, void* ud); + static void cb_ptr(gemui_app_t* app, int type, int x, int y, unsigned int btn, void* ud); + static void cb_resize(gemui_app_t* app, int w, int h, void* ud); + static void cb_theme(gemui_app_t* app, void* ud); + static bool cb_close(gemui_app_t* app, void* ud); + static void cb_open_file_done(gemui_app_t* app, bool accepted, const char* path, void* ud); + static void cb_save_native_done(gemui_app_t* app, bool accepted, const char* path, void* ud); + static void cb_export_csv_values_done(gemui_app_t* app, bool accepted, const char* path, void* ud); + static void cb_export_csv_formulas_done(gemui_app_t* app, bool accepted, const char* path, void* ud); + + Layout compute_layout(int w, int h) const; + void draw(cairo_t* cr, int w, int h); + void draw_top_bar(cairo_t* cr, const Layout& lay); + void draw_bottom_bar(cairo_t* cr, const Layout& lay); + void draw_modal(cairo_t* cr, int w, int h, const UiScale& ui); + + void handle_key(KeySym ks, unsigned int state, const char* utf8); + void handle_modal_key(KeySym ks, unsigned int state, const char* utf8); + void handle_ptr(int type, int x, int y, unsigned int btn); + void handle_right_click(int x, int y); + + void execute_menu_action(int index); + void execute_ctx_action(CtxAction action); + void accept_modal_dialog(); + void commit_edit_if_active(); + bool jump_to_address(const std::string& raw); + void open_modal(ModalKind kind, const std::string& initial_text = ""); + void close_modal(); + void request_quit(); + void confirm_exit_save(); + void open_file_dialog(); + void save_native_dialog(); + void export_csv_dialog(bool formulas); + std::string dialog_initial_dir() const; + std::string dialog_initial_name(const std::string& default_name, + const std::string& ext_override, + const std::string& suffix_before_ext = "") const; + + bool load_file_auto(const std::string& path); + bool save_native_to(const std::string& path); + void export_csv_to(const std::string& path, bool formulas); + void do_copy(bool is_cut); + void do_paste(); + void clear_selection(); + void delete_selected_rows(); + void delete_selected_cols(); + void switch_sheet(int idx); + void add_new_sheet(); + void close_sheet(int idx); + void update_title(); + std::string display_filename() const; + + Workbook wb_; + gemui_app_t* app_ = nullptr; + X11Clipboard clipboard_; + FormulaBar formula_bar_; + GridWidget grid_; + + ModalKind modal_ = ModalKind::Closed; + int menu_sel_ = 0; + int menu_scroll_ = 0; + int format_sel_ = 0; + int help_scroll_ = 0; + int help_visible_rows_ = 12; + int exit_sel_ = 0; + bool quit_after_save_ = false; + std::vector ctx_items_; + int ctx_x_ = 0; + int ctx_y_ = 0; + int ctx_sel_ = 0; + int ctx_target_sheet_ = 0; + TextEditor modal_editor_; + int tab_scroll_ = 0; + bool hscroll_dragging_ = false; + std::string current_path_; + bool dirty_ = false; + gemui_rect_t last_hscroll_r_{0, 0, 0, 0}; + std::vector> last_tab_rects_; +}; + +} // namespace htab::ui diff --git a/ui/clipboard.cpp b/ui/clipboard.cpp new file mode 100644 index 0000000..1792149 --- /dev/null +++ b/ui/clipboard.cpp @@ -0,0 +1,174 @@ +#include "ui/clipboard.hpp" + +#include +#include +#include + +namespace htab::ui { + +X11Clipboard::~X11Clipboard() { + if (dpy_) { + if (win_ != None) XDestroyWindow(dpy_, win_); + XCloseDisplay(dpy_); + dpy_ = nullptr; + } +} + +void X11Clipboard::init(gemui_app_t* app) { + if (dpy_) return; + dpy_ = XOpenDisplay(nullptr); + if (!dpy_) return; + int screen = DefaultScreen(dpy_); + win_ = XCreateSimpleWindow(dpy_, RootWindow(dpy_, screen), -10, -10, 1, 1, 0, 0, 0); + XSelectInput(dpy_, win_, PropertyChangeMask); + atom_clipboard_ = XInternAtom(dpy_, "CLIPBOARD", False); + atom_targets_ = XInternAtom(dpy_, "TARGETS", False); + atom_utf8_ = XInternAtom(dpy_, "UTF8_STRING", False); + atom_text_ = XInternAtom(dpy_, "TEXT", False); + xfd_ = ConnectionNumber(dpy_); + if (app && xfd_ >= 0) { + gemui_add_fd(app, xfd_, &X11Clipboard::on_fd_ready, this); + } +} + +void X11Clipboard::shutdown(gemui_app_t* app) { + if (app && xfd_ >= 0) { + gemui_del_fd(app, xfd_); + } + if (dpy_) { + if (win_ != None) { + XDestroyWindow(dpy_, win_); + win_ = None; + } + XCloseDisplay(dpy_); + dpy_ = nullptr; + } + xfd_ = -1; +} + +void X11Clipboard::on_fd_ready(gemui_app_t*, int, void* ud) { + if (ud) static_cast(ud)->process_events(); +} + +void X11Clipboard::process_events() { + if (!dpy_) return; + while (XPending(dpy_) > 0) { + XEvent ev; + XNextEvent(dpy_, &ev); + if (ev.type == SelectionRequest) { + handle_selection_request(ev.xselectionrequest); + } else if (ev.type == SelectionClear) { + if (ev.xselectionclear.selection == atom_clipboard_) { + owns_clipboard_ = false; + } + } + } +} + +void X11Clipboard::handle_selection_request(const XSelectionRequestEvent& req) { + XSelectionEvent resp; + std::memset(&resp, 0, sizeof(resp)); + resp.type = SelectionNotify; + resp.display = req.display; + resp.requestor = req.requestor; + resp.selection = req.selection; + resp.target = req.target; + resp.time = req.time; + resp.property = None; + + if (req.property != None) { + if (req.target == atom_targets_) { + Atom targets[4] = {atom_targets_, atom_utf8_, XA_STRING, atom_text_}; + XChangeProperty(dpy_, req.requestor, req.property, XA_ATOM, 32, PropModeReplace, + reinterpret_cast(targets), 4); + resp.property = req.property; + } else if (req.target == atom_utf8_ || req.target == XA_STRING || req.target == atom_text_) { + Atom type = (req.target == XA_STRING) ? XA_STRING : atom_utf8_; + XChangeProperty(dpy_, req.requestor, req.property, type, 8, PropModeReplace, + reinterpret_cast(text_.data()), + static_cast(text_.size())); + resp.property = req.property; + } + } + XSendEvent(dpy_, req.requestor, False, 0, reinterpret_cast(&resp)); + XFlush(dpy_); +} + +void X11Clipboard::copy_grid(const ClipboardGrid& grid) { + internal_ = grid; + set_text(grid_to_tsv(grid)); +} + +void X11Clipboard::set_text(const std::string& text) { + text_ = text; + if (!dpy_ || win_ == None) return; + XSetSelectionOwner(dpy_, atom_clipboard_, win_, CurrentTime); + XSetSelectionOwner(dpy_, XA_PRIMARY, win_, CurrentTime); + XFlush(dpy_); + owns_clipboard_ = (XGetSelectionOwner(dpy_, atom_clipboard_) == win_); +} + +std::string X11Clipboard::get_external_text(gemui_app_t* app) const { + if (!app) return ""; + std::vector buf(65536, '\0'); + if (!gemui_clipboard_get(app, buf.data(), buf.size())) { + return ""; + } + return std::string(buf.data()); +} + +std::string X11Clipboard::grid_to_tsv(const ClipboardGrid& grid) { + int rows = grid.src_range.row_count(); + int cols = grid.src_range.col_count(); + if (rows <= 0 || cols <= 0) return ""; + std::vector> table(static_cast(rows), + std::vector(static_cast(cols))); + for (const auto& c : grid.cells) { + if (c.dr >= 0 && c.dr < rows && c.dc >= 0 && c.dc < cols) { + auto sv = to_string(c.evaluated_value); + table[static_cast(c.dr)][static_cast(c.dc)] = + std::holds_alternative(sv) ? std::get(sv) : c.raw_input; + } + } + std::string out; + for (int r = 0; r < rows; ++r) { + if (r > 0) out.push_back('\n'); + for (int c = 0; c < cols; ++c) { + if (c > 0) out.push_back('\t'); + out += table[static_cast(r)][static_cast(c)]; + } + } + return out; +} + +std::vector X11Clipboard::parse_tsv_to_edits(const std::string& text, + int dest_row, + int dest_col) { + std::vector edits; + if (text.empty()) return edits; + + int r = dest_row; + int c = dest_col; + size_t start = 0; + for (size_t i = 0; i <= text.size(); ++i) { + bool at_end = (i == text.size()); + char ch = at_end ? '\n' : text[i]; + if (ch == '\t' || ch == '\n' || ch == '\r') { + if (at_end && start == i && c == dest_col && i > 0 && text[i - 1] == '\n') { + break; + } + edits.push_back(CellEdit{r, c, text.substr(start, i - start), std::nullopt}); + if (ch == '\t') { + ++c; + } else { + if (ch == '\r' && i + 1 < text.size() && text[i + 1] == '\n') ++i; + ++r; + c = dest_col; + } + start = i + 1; + } + } + return edits; +} + +} // namespace htab::ui diff --git a/ui/clipboard.hpp b/ui/clipboard.hpp new file mode 100644 index 0000000..ce83677 --- /dev/null +++ b/ui/clipboard.hpp @@ -0,0 +1,56 @@ +#pragma once + +#include "engine/workbook.hpp" + +#include +#include + +#include +#include + +namespace htab::ui { + +class X11Clipboard { + public: + X11Clipboard() = default; + ~X11Clipboard(); + + X11Clipboard(const X11Clipboard&) = delete; + X11Clipboard& operator=(const X11Clipboard&) = delete; + + void init(gemui_app_t* app); + void shutdown(gemui_app_t* app); + + void copy_grid(const ClipboardGrid& grid); + void set_text(const std::string& text); + + bool owns_clipboard() const { return owns_clipboard_; } + bool has_internal() const { return owns_clipboard_ && !internal_.cells.empty(); } + const ClipboardGrid& internal_grid() const { return internal_; } + void clear_cut_flag() { internal_.is_cut = false; } + + std::string get_external_text(gemui_app_t* app) const; + + static std::string grid_to_tsv(const ClipboardGrid& grid); + static std::vector parse_tsv_to_edits(const std::string& text, + int dest_row, + int dest_col); + + private: + static void on_fd_ready(gemui_app_t* app, int fd, void* ud); + void process_events(); + void handle_selection_request(const XSelectionRequestEvent& req); + + Display* dpy_ = nullptr; + Window win_ = None; + int xfd_ = -1; + Atom atom_clipboard_ = None; + Atom atom_targets_ = None; + Atom atom_utf8_ = None; + Atom atom_text_ = None; + bool owns_clipboard_ = false; + std::string text_; + ClipboardGrid internal_; +}; + +} // namespace htab::ui diff --git a/ui/formula_bar.cpp b/ui/formula_bar.cpp new file mode 100644 index 0000000..3f10a4c --- /dev/null +++ b/ui/formula_bar.cpp @@ -0,0 +1,49 @@ +#include "ui/formula_bar.hpp" + +#include + +namespace htab::ui { + +void FormulaBar::draw(gemui_app_t* app, + cairo_t* cr, + gemui_rect_t rect, + const std::string& cell_addr, + const TextEditor& editor, + bool bar_focused, + const UiScale& ui, + int hit_id_addr, + int hit_id_input) { + const gemui_theme_t* t = gemui_theme(app); + int div_h = std::max(1, spx(1, ui)); + gemui_fill_rect(cr, rect, t->bg_bar); + gemui_fill_rect(cr, gemui_rect_t{rect.x, rect.y + rect.h - div_h, rect.w, div_h}, t->divider); + + int font_px = ui.compact ? 10 : 14; + int pad_x = spx(ui.compact ? 2 : 6, ui); + int pad_y = spx(ui.compact ? 2 : 4, ui); + int addr_w = spx(ui.compact ? 46 : 84, ui); + int inner_h = std::max(6, rect.h - pad_y * 2 - div_h); + + gemui_rect_t addr_r{rect.x + pad_x, rect.y + pad_y, addr_w, inner_h}; + double rad = 3.0 * ui.scale; + double lw = std::max(1.0, ui.scale); + gemui_fill_round(cr, addr_r, rad, t->bg_button); + gemui_stroke_round(cr, addr_r, rad, lw, t->border); + int addr_pad = spx(2, ui); + gemui_draw_text(cr, t, + gemui_rect_t{addr_r.x + addr_pad, addr_r.y, + std::max(1, addr_r.w - addr_pad * 2), addr_r.h}, + cell_addr.c_str(), pt_delta_for_ui(t, font_px, ui), true, + GEMUI_ALIGN_CENTER, t->accent); + if (hit_id_addr >= 0) { + gemui_hit_add(app, addr_r, hit_id_addr, 0); + } + + int input_x = addr_r.x + addr_r.w + pad_x; + int input_w = std::max(spx(20, ui), rect.x + rect.w - input_x - pad_x); + gemui_rect_t input_r{input_x, rect.y + pad_y, input_w, inner_h}; + draw_single_line_editor(cr, t, input_r, editor, "=formula or value", bar_focused, font_px, ui); + gemui_hit_add(app, input_r, hit_id_input, 0); +} + +} // namespace htab::ui diff --git a/ui/formula_bar.hpp b/ui/formula_bar.hpp new file mode 100644 index 0000000..d01f0da --- /dev/null +++ b/ui/formula_bar.hpp @@ -0,0 +1,24 @@ +#pragma once + +#include "ui/text_edit.hpp" + +#include +#include +#include + +namespace htab::ui { + +class FormulaBar { + public: + void draw(gemui_app_t* app, + cairo_t* cr, + gemui_rect_t rect, + const std::string& cell_addr, + const TextEditor& editor, + bool bar_focused, + const UiScale& ui, + int hit_id_addr, + int hit_id_input); +}; + +} // namespace htab::ui diff --git a/ui/grid_widget.cpp b/ui/grid_widget.cpp new file mode 100644 index 0000000..a21b579 --- /dev/null +++ b/ui/grid_widget.cpp @@ -0,0 +1,833 @@ +#include "ui/grid_widget.hpp" + +#include "engine/address.hpp" + +#include +#include +#include +#include + +namespace htab::ui { + +namespace { + +uint64_t monotonic_ms() { + struct timespec ts{}; + clock_gettime(CLOCK_MONOTONIC, &ts); + return static_cast(ts.tv_sec) * 1000ULL + + static_cast(ts.tv_nsec / 1000000L); +} + +gemui_color_t blend_color(gemui_color_t bg, gemui_color_t fg, double alpha) { + gemui_color_t out; + out.r = bg.r * (1.0 - alpha) + fg.r * alpha; + out.g = bg.g * (1.0 - alpha) + fg.g * alpha; + out.b = bg.b * (1.0 - alpha) + fg.b * alpha; + out.a = 1.0; + out.argb = 0xFF000000U; + return out; +} + +} // namespace + +GridMetrics GridWidget::metrics_for(const UiScale& ui) { + if (ui.compact) { + return GridMetrics{ + spx(24, ui), + spx(16, ui), + 50, + 17, + 10, + spx(6, ui), + }; + } + return GridMetrics{ + spx(48, ui), + spx(26, ui), + 96, + ui.touch ? 30 : 26, + 13, + spx(12, ui), + }; +} + +int GridWidget::col_w(const Workbook& wb, int col) const { + if (drag_mode_ == DragMode::ResizeCol && resize_index_ == col) { + return resize_live_size_; + } + int logical_w = wb.get_col_width(wb.active_sheet(), col, + metrics_for(last_ui_).default_col_w_logical); + return spx(logical_w, last_ui_); +} + +int GridWidget::row_h(const Workbook& wb, int row) const { + if (drag_mode_ == DragMode::ResizeRow && resize_index_ == row) { + return resize_live_size_; + } + int logical_h = wb.get_row_height(wb.active_sheet(), row, + metrics_for(last_ui_).default_row_h_logical); + return spx(logical_h, last_ui_); +} + +CellRange GridWidget::selection_range(int sheet_idx) const { + return CellRange{ + sheet_idx, + std::min(anchor_row_, active_row_), + std::min(anchor_col_, active_col_), + std::max(anchor_row_, active_row_), + std::max(anchor_col_, active_col_), + }; +} + +int GridWidget::max_scroll_rows(const Workbook& wb) const { + auto bounds = wb.get_used_bounds(wb.active_sheet()); + int used_r = bounds ? bounds->r2 : 0; + return std::max({60, used_r + 30, active_row_ + 20, scroll_row_ + 20}); +} + +int GridWidget::max_scroll_cols(const Workbook& wb) const { + auto bounds = wb.get_used_bounds(wb.active_sheet()); + int used_c = bounds ? bounds->c2 : 0; + return std::max({26, used_c + 10, active_col_ + 10, scroll_col_ + 10}); +} + +void GridWidget::reset_for_sheet(const Workbook& wb, int) { + editing_ = false; + formula_bar_focused_ = false; + scroll_row_ = 0; + scroll_col_ = 0; + active_row_ = 0; + active_col_ = 0; + anchor_row_ = 0; + anchor_col_ = 0; + sync_editor_from_cell(wb); +} + +void GridWidget::sync_editor_from_cell(const Workbook& wb) { + const Cell* c = wb.get_cell(wb.active_sheet(), active_row_, active_col_); + editor_.set_text(c ? c->raw_input : ""); +} + +void GridWidget::set_active_cell(const Workbook& wb, int row, int col, bool keep_anchor) { + active_row_ = std::clamp(row, 0, kMaxRows - 1); + active_col_ = std::clamp(col, 0, kMaxCols - 1); + if (!keep_anchor) { + anchor_row_ = active_row_; + anchor_col_ = active_col_; + } + ensure_visible(wb, active_row_, active_col_); + if (!editing_) { + sync_editor_from_cell(wb); + } +} + +void GridWidget::move_active(const Workbook& wb, int drow, int dcol, bool extend_selection) { + set_active_cell(wb, active_row_ + drow, active_col_ + dcol, extend_selection); +} + +void GridWidget::ensure_visible(const Workbook& wb, int row, int col) { + if (row < scroll_row_) { + scroll_row_ = row; + } else if (last_data_rect_.h > 0) { + int y = 0; + int r = scroll_row_; + while (r <= row && y + row_h(wb, r) <= last_data_rect_.h) { + y += row_h(wb, r); + ++r; + } + if (r <= row) { + int needed = 0; + int new_top = row; + while (new_top > 0) { + int h = row_h(wb, new_top); + if (needed + h > last_data_rect_.h) break; + needed += h; + --new_top; + } + if (needed + row_h(wb, new_top) <= last_data_rect_.h) { + scroll_row_ = new_top; + } else { + scroll_row_ = std::min(row, new_top + 1); + } + } + } + + if (col < scroll_col_) { + scroll_col_ = col; + } else if (last_data_rect_.w > 0) { + int x = 0; + int c = scroll_col_; + while (c <= col && x + col_w(wb, c) <= last_data_rect_.w) { + x += col_w(wb, c); + ++c; + } + if (c <= col) { + int needed = 0; + int new_left = col; + while (new_left > 0) { + int w = col_w(wb, new_left); + if (needed + w > last_data_rect_.w) break; + needed += w; + --new_left; + } + if (needed + col_w(wb, new_left) <= last_data_rect_.w) { + scroll_col_ = new_left; + } else { + scroll_col_ = std::min(col, new_left + 1); + } + } + } +} + +void GridWidget::start_edit(const Workbook& wb, + bool focus_formula_bar, + const std::string* initial) { + editing_ = true; + formula_bar_focused_ = focus_formula_bar; + if (initial) { + editor_.set_text(*initial); + } else { + sync_editor_from_cell(wb); + } +} + +void GridWidget::commit_edit(Workbook& wb) { + if (!editing_) return; + editing_ = false; + formula_bar_focused_ = false; + wb.set_cell_input(wb.active_sheet(), active_row_, active_col_, editor_.text); + sync_editor_from_cell(wb); +} + +void GridWidget::cancel_edit(const Workbook& wb) { + editing_ = false; + formula_bar_focused_ = false; + sync_editor_from_cell(wb); +} + +CellRange GridWidget::compute_fill_preview(int sheet_idx) const { + CellRange base = selection_range(sheet_idx); + int dr = 0; + if (fill_hover_row_ > base.r2) dr = fill_hover_row_ - base.r2; + else if (fill_hover_row_ < base.r1) dr = base.r1 - fill_hover_row_; + + int dc = 0; + if (fill_hover_col_ > base.c2) dc = fill_hover_col_ - base.c2; + else if (fill_hover_col_ < base.c1) dc = base.c1 - fill_hover_col_; + + if (dr >= dc && dr > 0) { + if (fill_hover_row_ > base.r2) base.r2 = fill_hover_row_; + else base.r1 = fill_hover_row_; + } else if (dc > 0) { + if (fill_hover_col_ > base.c2) base.c2 = fill_hover_col_; + else base.c1 = fill_hover_col_; + } + return base; +} + +void GridWidget::draw(gemui_app_t* app, + cairo_t* cr, + const Workbook& wb, + gemui_rect_t rect, + const UiScale& ui) { + last_rect_ = rect; + last_ui_ = ui; + has_fill_handle_ = false; + if (rect.w < spx(40, ui) || rect.h < spx(30, ui)) return; + + const gemui_theme_t* t = gemui_theme(app); + const GridMetrics m = metrics_for(ui); + const int sheet = wb.active_sheet(); + + gemui_rect_t vscroll_r{rect.x + rect.w - m.vscroll_w, rect.y + m.col_hdr_h, + m.vscroll_w, std::max(1, rect.h - m.col_hdr_h)}; + last_vscroll_rect_ = vscroll_r; + + gemui_rect_t data_r{rect.x + m.row_hdr_w, rect.y + m.col_hdr_h, + std::max(1, rect.w - m.row_hdr_w - m.vscroll_w), + std::max(1, rect.h - m.col_hdr_h)}; + last_data_rect_ = data_r; + + // Build visible column & row slices ONLY + std::vector cols; + { + int x = data_r.x; + int c = scroll_col_; + int end_x = data_r.x + data_r.w; + while (x < end_x && c < kMaxCols) { + int w = col_w(wb, c); + cols.push_back({c, x, w}); + x += w; + ++c; + } + } + std::vector rows; + { + int y = data_r.y; + int r = scroll_row_; + int end_y = data_r.y + data_r.h; + while (y < end_y && r < kMaxRows) { + int h = row_h(wb, r); + rows.push_back({r, y, h}); + y += h; + ++r; + } + } + + CellRange sel = selection_range(sheet); + gemui_color_t sel_fill = blend_color(t->bg_main, t->sel_bg, 0.45); + gemui_color_t hdr_sel = blend_color(t->bg_header, t->accent, 0.22); + gemui_color_t spill_fill = blend_color(t->bg_main, t->info, 0.12); + int font_delta = pt_delta_for_ui(t, m.font_logical_px, ui); + + gemui_fill_rect(cr, data_r, t->bg_main); + + gemui_rect_t corner_r{rect.x, rect.y, m.row_hdr_w, m.col_hdr_h}; + gemui_fill_rect(cr, corner_r, t->bg_header); + + // Column headers + cairo_save(cr); + cairo_rectangle(cr, data_r.x, rect.y, data_r.w, m.col_hdr_h); + cairo_clip(cr); + for (const auto& cl : cols) { + bool in_sel = (cl.col >= sel.c1 && cl.col <= sel.c2); + gemui_rect_t hr{cl.x, rect.y, cl.w, m.col_hdr_h}; + gemui_fill_rect(cr, hr, in_sel ? hdr_sel : t->bg_header); + std::string label = col_to_letters(cl.col); + int hpad = spx(1, ui); + gemui_draw_text(cr, t, + gemui_rect_t{hr.x + hpad, hr.y, std::max(1, hr.w - hpad * 2), hr.h}, + label.c_str(), font_delta, in_sel, GEMUI_ALIGN_CENTER, + in_sel ? t->fg_bright : t->fg_muted); + } + cairo_restore(cr); + + // Row headers + cairo_save(cr); + cairo_rectangle(cr, rect.x, data_r.y, m.row_hdr_w, data_r.h); + cairo_clip(cr); + for (const auto& rl : rows) { + bool in_sel = (rl.row >= sel.r1 && rl.row <= sel.r2); + gemui_rect_t hr{rect.x, rl.y, m.row_hdr_w, rl.h}; + gemui_fill_rect(cr, hr, in_sel ? hdr_sel : t->bg_header); + std::string label = std::to_string(rl.row + 1); + int hpad = spx(1, ui); + gemui_draw_text(cr, t, + gemui_rect_t{hr.x + hpad, hr.y, std::max(1, hr.w - hpad * 2), hr.h}, + label.c_str(), font_delta, in_sel, GEMUI_ALIGN_CENTER, + in_sel ? t->fg_bright : t->fg_muted); + } + cairo_restore(cr); + + // Visible cells (clipped to data_r) + cairo_save(cr); + cairo_rectangle(cr, data_r.x, data_r.y, data_r.w, data_r.h); + cairo_clip(cr); + + int cell_pad_x = spx(ui.compact ? 2 : 5, ui); + int cell_pad_y = std::max(1, spx(1, ui)); + + for (const auto& rl : rows) { + for (const auto& cl : cols) { + gemui_rect_t cr_rect{cl.x, rl.y, cl.w, rl.h}; + bool in_sel = sel.contains(sheet, rl.row, cl.col); + bool is_active = (rl.row == active_row_ && cl.col == active_col_); + bool is_spilled = wb.is_spilled_cell(sheet, rl.row, cl.col); + + if (in_sel && !is_active) { + gemui_fill_rect(cr, cr_rect, sel_fill); + } else if (is_spilled) { + gemui_fill_rect(cr, cr_rect, spill_fill); + } + + if (editing_ && !formula_bar_focused_ && is_active) { + continue; + } + + Value val = wb.get_scalar_value(sheet, rl.row, cl.col); + if (!val.is_empty()) { + std::string txt = wb.get_formatted_value(sheet, rl.row, cl.col); + if (!txt.empty()) { + int align = GEMUI_ALIGN_LEFT; + gemui_color_t fg = t->fg_main; + if (val.is_error()) { + align = GEMUI_ALIGN_CENTER; + fg = t->danger; + } else if (val.is_bool()) { + align = GEMUI_ALIGN_CENTER; + fg = t->info; + } else if (val.is_number()) { + align = GEMUI_ALIGN_RIGHT; + fg = t->fg_bright; + } + gemui_rect_t text_r{cr_rect.x + cell_pad_x, cr_rect.y + cell_pad_y, + std::max(1, cr_rect.w - cell_pad_x * 2), + std::max(1, cr_rect.h - cell_pad_y * 2)}; + if (text_r.w > 4 && text_r.h > 4) { + cairo_save(cr); + cairo_rectangle(cr, cr_rect.x + 1, cr_rect.y + 1, + std::max(1, cr_rect.w - 2), std::max(1, cr_rect.h - 2)); + cairo_clip(cr); + gemui_draw_text(cr, t, text_r, txt.c_str(), font_delta, false, align, fg); + cairo_restore(cr); + } + } + } + } + } + + // Gridlines + double line_w = (ui.scale >= 1.5) ? 1.5 : 1.0; + gemui_set_source(cr, t->divider); + cairo_set_line_width(cr, line_w); + for (const auto& cl : cols) { + double lx = static_cast(cl.x + cl.w) + 0.5; + cairo_move_to(cr, lx, data_r.y); + cairo_line_to(cr, lx, data_r.y + data_r.h); + } + for (const auto& rl : rows) { + double ly = static_cast(rl.y + rl.h) + 0.5; + cairo_move_to(cr, data_r.x, ly); + cairo_line_to(cr, data_r.x + data_r.w, ly); + } + cairo_stroke(cr); + + auto col_x_range = [&](int c_idx, int& out_x, int& out_w) -> bool { + for (const auto& cl : cols) { + if (cl.col == c_idx) { out_x = cl.x; out_w = cl.w; return true; } + } + return false; + }; + auto row_y_range = [&](int r_idx, int& out_y, int& out_h) -> bool { + for (const auto& rl : rows) { + if (rl.row == r_idx) { out_y = rl.y; out_h = rl.h; return true; } + } + return false; + }; + + int sx1 = data_r.x, sy1 = data_r.y, sx2 = data_r.x, sy2 = data_r.y; + bool sel_vis = !cols.empty() && !rows.empty() && + sel.c2 >= cols.front().col && sel.c1 <= cols.back().col && + sel.r2 >= rows.front().row && sel.r1 <= rows.back().row; + if (sel_vis) { + if (sel.c1 < cols.front().col) sx1 = data_r.x; + else { int w_unused = 0; col_x_range(sel.c1, sx1, w_unused); } + + if (sel.c2 > cols.back().col) sx2 = cols.back().x + cols.back().w; + else { int x0 = 0, w0 = 0; col_x_range(sel.c2, x0, w0); sx2 = x0 + w0; } + + if (sel.r1 < rows.front().row) sy1 = data_r.y; + else { int h_unused = 0; row_y_range(sel.r1, sy1, h_unused); } + + if (sel.r2 > rows.back().row) sy2 = rows.back().y + rows.back().h; + else { int y0 = 0, h0 = 0; row_y_range(sel.r2, y0, h0); sy2 = y0 + h0; } + + gemui_set_source(cr, t->accent); + cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale)); + cairo_rectangle(cr, sx1 + 0.5, sy1 + 0.5, std::max(1, sx2 - sx1 - 1), + std::max(1, sy2 - sy1 - 1)); + cairo_stroke(cr); + + if (sel.c2 <= cols.back().col && sel.r2 <= rows.back().row) { + int hs = spx(ui.compact ? 5 : 7, ui); + last_fill_handle_ = gemui_rect_t{sx2 - hs / 2 - 1, sy2 - hs / 2 - 1, hs, hs}; + has_fill_handle_ = true; + gemui_fill_rect(cr, last_fill_handle_, t->highlight); + } + } + + int ax = 0, aw = 0, ay = 0, ah = 0; + if (col_x_range(active_col_, ax, aw) && row_y_range(active_row_, ay, ah)) { + if (editing_ && !formula_bar_focused_) { + int min_ed_w = spx(140, ui); + int edit_w = std::min(std::max(aw, min_ed_w), std::max(aw, data_r.x + data_r.w - ax)); + draw_single_line_editor(cr, t, gemui_rect_t{ax, ay, edit_w, ah}, editor_, "", true, + m.font_logical_px, ui); + } else { + double active_lw = std::max(2.0, 2.0 * ui.scale); + gemui_set_source(cr, t->highlight); + cairo_set_line_width(cr, active_lw); + cairo_rectangle(cr, ax + 1.0, ay + 1.0, std::max(1, aw - 2), std::max(1, ah - 2)); + cairo_stroke(cr); + } + } + + if (drag_mode_ == DragMode::FillHandle && !cols.empty() && !rows.empty()) { + CellRange fp = compute_fill_preview(sheet); + int fx1 = data_r.x, fy1 = data_r.y, fx2 = data_r.x, fy2 = data_r.y; + if (fp.c1 < cols.front().col) fx1 = data_r.x; + else { int wu = 0; if (!col_x_range(fp.c1, fx1, wu)) fx1 = data_r.x; } + if (fp.c2 > cols.back().col) fx2 = cols.back().x + cols.back().w; + else { int x0 = 0, w0 = 0; if (col_x_range(fp.c2, x0, w0)) fx2 = x0 + w0; } + if (fp.r1 < rows.front().row) fy1 = data_r.y; + else { int hu = 0; if (!row_y_range(fp.r1, fy1, hu)) fy1 = data_r.y; } + if (fp.r2 > rows.back().row) fy2 = rows.back().y + rows.back().h; + else { int y0 = 0, h0 = 0; if (row_y_range(fp.r2, y0, h0)) fy2 = y0 + h0; } + + const double dash[2] = {4.0 * ui.scale, 3.0 * ui.scale}; + gemui_set_source(cr, t->highlight); + cairo_set_dash(cr, dash, 2, 0.0); + cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale)); + cairo_rectangle(cr, fx1 + 1.0, fy1 + 1.0, std::max(1, fx2 - fx1 - 2), + std::max(1, fy2 - fy1 - 2)); + cairo_stroke(cr); + cairo_set_dash(cr, nullptr, 0, 0.0); + } + + cairo_restore(cr); + + // Header dividers + gemui_set_source(cr, t->border); + cairo_set_line_width(cr, line_w); + for (const auto& cl : cols) { + double lx = static_cast(cl.x + cl.w) + 0.5; + cairo_move_to(cr, lx, rect.y); + cairo_line_to(cr, lx, rect.y + m.col_hdr_h); + } + for (const auto& rl : rows) { + double ly = static_cast(rl.y + rl.h) + 0.5; + cairo_move_to(cr, rect.x, ly); + cairo_line_to(cr, rect.x + m.row_hdr_w, ly); + } + cairo_stroke(cr); + + int div_px = std::max(1, spx(1, ui)); + gemui_fill_rect(cr, gemui_rect_t{rect.x, rect.y + m.col_hdr_h - div_px, rect.w, div_px}, + t->border); + gemui_fill_rect(cr, gemui_rect_t{rect.x + m.row_hdr_w - div_px, rect.y, div_px, rect.h}, + t->border); + + // Vertical scrollbar + gemui_fill_rect(cr, vscroll_r, t->bg_bar); + int total_rows = max_scroll_rows(wb); + int vis_rows = std::max(1, static_cast(rows.size())); + int min_thumb_h = spx(14, ui); + int thumb_h = std::max(min_thumb_h, (vscroll_r.h * vis_rows) / std::max(1, total_rows)); + if (thumb_h > vscroll_r.h) thumb_h = vscroll_r.h; + int max_top = std::max(1, total_rows - vis_rows); + int thumb_y = vscroll_r.y + + ((vscroll_r.h - thumb_h) * std::min(scroll_row_, max_top)) / max_top; + int sb_pad = std::max(1, spx(1, ui)); + gemui_fill_round(cr, + gemui_rect_t{vscroll_r.x + sb_pad, thumb_y + sb_pad, + std::max(2, vscroll_r.w - sb_pad * 2), + std::max(4, thumb_h - sb_pad * 2)}, + 2.0 * ui.scale, drag_mode_ == DragMode::ScrollV ? t->accent : t->border); +} + +void GridWidget::draw_hscroll(gemui_app_t* app, + cairo_t* cr, + const Workbook& wb, + gemui_rect_t rect, + const UiScale& ui, + int hit_id_hscroll) { + if (rect.w < spx(12, ui) || rect.h < spx(6, ui)) return; + const gemui_theme_t* t = gemui_theme(app); + double rad = 2.0 * ui.scale; + gemui_fill_round(cr, rect, rad, t->bg_input); + gemui_stroke_round(cr, rect, rad, std::max(1.0, ui.scale), t->border); + + int total_cols = max_scroll_cols(wb); + int vis_cols = 4; + if (last_data_rect_.w > 0) { + int def_col_px = std::max(1, spx(metrics_for(ui).default_col_w_logical, ui)); + vis_cols = std::max(1, last_data_rect_.w / def_col_px); + } + int min_thumb_w = spx(12, ui); + int thumb_w = std::max(min_thumb_w, (rect.w * vis_cols) / std::max(1, total_cols)); + if (thumb_w > rect.w) thumb_w = rect.w; + int max_left = std::max(1, total_cols - vis_cols); + int thumb_x = rect.x + ((rect.w - thumb_w) * std::min(scroll_col_, max_left)) / max_left; + int pad = std::max(1, spx(1, ui)); + gemui_fill_round(cr, + gemui_rect_t{thumb_x + pad, rect.y + pad, + std::max(4, thumb_w - pad * 2), + std::max(3, rect.h - pad * 2)}, + rad, drag_mode_ == DragMode::ScrollH ? t->accent : t->border); + gemui_hit_add(app, rect, hit_id_hscroll, 0); +} + +void GridWidget::hit_cell_at(const Workbook& wb, int x, int y, int& out_row, int& out_col) const { + int cx = last_data_rect_.x; + int c = scroll_col_; + while (c + 1 < kMaxCols && cx + col_w(wb, c) <= x) { + cx += col_w(wb, c); + ++c; + } + int cy = last_data_rect_.y; + int r = scroll_row_; + while (r + 1 < kMaxRows && cy + row_h(wb, r) <= y) { + cy += row_h(wb, r); + ++r; + } + out_row = std::max(0, r); + out_col = std::max(0, c); +} + +void GridWidget::update_scroll_v_from_y(const Workbook& wb, int y) { + if (last_vscroll_rect_.h <= 0) return; + double norm = static_cast(y - last_vscroll_rect_.y) / + static_cast(last_vscroll_rect_.h); + norm = std::clamp(norm, 0.0, 1.0); + int max_r = std::max(1, max_scroll_rows(wb) - 5); + scroll_row_ = static_cast(std::llround(norm * max_r)); +} + +void GridWidget::handle_hscroll_drag(const Workbook& wb, int x, gemui_rect_t hscroll_rect) { + if (hscroll_rect.w <= 0) return; + double norm = static_cast(x - hscroll_rect.x) / static_cast(hscroll_rect.w); + norm = std::clamp(norm, 0.0, 1.0); + int max_c = std::max(1, max_scroll_cols(wb) - 2); + scroll_col_ = static_cast(std::llround(norm * max_c)); +} + +GridHitRegion GridWidget::hit_region(const Workbook& wb, + int x, + int y, + int& out_row, + int& out_col) const { + if (x >= last_data_rect_.x && x < last_data_rect_.x + last_data_rect_.w && + y >= last_data_rect_.y && y < last_data_rect_.y + last_data_rect_.h) { + hit_cell_at(wb, x, y, out_row, out_col); + return GridHitRegion::DataCell; + } + if (y >= last_rect_.y && y < last_data_rect_.y && + x >= last_data_rect_.x && x < last_data_rect_.x + last_data_rect_.w) { + int cx = last_data_rect_.x; + int c = scroll_col_; + while (c + 1 < kMaxCols && cx + col_w(wb, c) <= x) { + cx += col_w(wb, c); + ++c; + } + out_row = active_row_; + out_col = c; + return GridHitRegion::ColHeader; + } + if (x >= last_rect_.x && x < last_data_rect_.x && + y >= last_data_rect_.y && y < last_data_rect_.y + last_data_rect_.h) { + int cy = last_data_rect_.y; + int r = scroll_row_; + while (r + 1 < kMaxRows && cy + row_h(wb, r) <= y) { + cy += row_h(wb, r); + ++r; + } + out_row = r; + out_col = active_col_; + return GridHitRegion::RowHeader; + } + return GridHitRegion::Outside; +} + +bool GridWidget::handle_pointer(Workbook& wb, + int type, + int x, + int y, + unsigned int btn, + gemui_rect_t hscroll_rect, + bool& edited_or_committed_out) { + edited_or_committed_out = false; + const GridMetrics m = metrics_for(last_ui_); + int hit_tol = spx(5, last_ui_); + + auto in_rect = [](gemui_rect_t r, int px, int py) { + return px >= r.x && px < r.x + r.w && py >= r.y && py < r.y + r.h; + }; + + if (type == GEMUI_PTR_SCROLL_UP || type == GEMUI_PTR_SCROLL_DOWN) { + int delta = (type == GEMUI_PTR_SCROLL_UP) ? -3 : 3; + if (in_rect(hscroll_rect, x, y)) { + scroll_col_ = std::clamp(scroll_col_ + (delta > 0 ? 2 : -2), 0, kMaxCols - 1); + return true; + } + if (in_rect(last_rect_, x, y)) { + scroll_row_ = std::clamp(scroll_row_ + delta, 0, kMaxRows - 1); + return true; + } + return false; + } + + if (type == GEMUI_PTR_DOWN) { + if (btn == 6) { + scroll_col_ = std::clamp(scroll_col_ - 2, 0, kMaxCols - 1); + return true; + } + if (btn == 7) { + scroll_col_ = std::clamp(scroll_col_ + 2, 0, kMaxCols - 1); + return true; + } + if (btn != Button1) { + return false; + } + if (in_rect(hscroll_rect, x, y)) { + drag_mode_ = DragMode::ScrollH; + handle_hscroll_drag(wb, x, hscroll_rect); + return true; + } + if (in_rect(last_vscroll_rect_, x, y)) { + drag_mode_ = DragMode::ScrollV; + update_scroll_v_from_y(wb, y); + return true; + } + if (!in_rect(last_rect_, x, y)) { + return false; + } + + if (has_fill_handle_ && + x >= last_fill_handle_.x - hit_tol && + x <= last_fill_handle_.x + last_fill_handle_.w + hit_tol && + y >= last_fill_handle_.y - hit_tol && + y <= last_fill_handle_.y + last_fill_handle_.h + hit_tol) { + if (editing_) { commit_edit(wb); edited_or_committed_out = true; } + drag_mode_ = DragMode::FillHandle; + fill_hover_row_ = active_row_; + fill_hover_col_ = active_col_; + return true; + } + + if (y >= last_rect_.y && y < last_data_rect_.y && x >= last_data_rect_.x) { + if (editing_) { commit_edit(wb); edited_or_committed_out = true; } + int cx = last_data_rect_.x; + int c = scroll_col_; + while (cx < last_data_rect_.x + last_data_rect_.w && c < kMaxCols) { + int w = col_w(wb, c); + if (std::abs(x - (cx + w)) <= hit_tol) { + drag_mode_ = DragMode::ResizeCol; + resize_index_ = c; + resize_start_px_ = x; + resize_orig_size_ = w; + resize_live_size_ = w; + return true; + } + if (x >= cx && x < cx + w) { + set_active_cell(wb, active_row_, c, false); + return true; + } + cx += w; + ++c; + } + return true; + } + + if (x >= last_rect_.x && x < last_data_rect_.x && y >= last_data_rect_.y) { + if (editing_) { commit_edit(wb); edited_or_committed_out = true; } + int cy = last_data_rect_.y; + int r = scroll_row_; + while (cy < last_data_rect_.y + last_data_rect_.h && r < kMaxRows) { + int h = row_h(wb, r); + if (std::abs(y - (cy + h)) <= hit_tol) { + drag_mode_ = DragMode::ResizeRow; + resize_index_ = r; + resize_start_px_ = y; + resize_orig_size_ = h; + resize_live_size_ = h; + return true; + } + if (y >= cy && y < cy + h) { + set_active_cell(wb, r, active_col_, false); + return true; + } + cy += h; + ++r; + } + return true; + } + + if (in_rect(last_data_rect_, x, y)) { + int r = 0, c = 0; + hit_cell_at(wb, x, y, r, c); + if (editing_ && (r != active_row_ || c != active_col_)) { + commit_edit(wb); + edited_or_committed_out = true; + } + uint64_t now = monotonic_ms(); + bool dbl = (r == last_click_row_ && c == last_click_col_ && (now - last_click_ms_) <= 400); + last_click_row_ = r; + last_click_col_ = c; + last_click_ms_ = now; + + if (dbl && !editing_) { + set_active_cell(wb, r, c, false); + start_edit(wb, false); + } else { + set_active_cell(wb, r, c, false); + drag_mode_ = DragMode::SelectRange; + } + return true; + } + return true; + } + + if (type == GEMUI_PTR_MOVE) { + if (drag_mode_ == DragMode::Idle) return false; + if (drag_mode_ == DragMode::ScrollV) { + update_scroll_v_from_y(wb, y); + return true; + } + if (drag_mode_ == DragMode::ScrollH) { + handle_hscroll_drag(wb, x, hscroll_rect); + return true; + } + if (drag_mode_ == DragMode::ResizeCol) { + resize_live_size_ = std::clamp(resize_orig_size_ + (x - resize_start_px_), + spx(24, last_ui_), spx(360, last_ui_)); + return true; + } + if (drag_mode_ == DragMode::ResizeRow) { + resize_live_size_ = std::clamp(resize_orig_size_ + (y - resize_start_px_), + spx(m.font_logical_px + 4, last_ui_), spx(160, last_ui_)); + return true; + } + if (drag_mode_ == DragMode::SelectRange) { + int cx = std::clamp(x, last_data_rect_.x, last_data_rect_.x + last_data_rect_.w - 1); + int cy = std::clamp(y, last_data_rect_.y, last_data_rect_.y + last_data_rect_.h - 1); + int r = 0, c = 0; + hit_cell_at(wb, cx, cy, r, c); + if (y > last_data_rect_.y + last_data_rect_.h) ++r; + if (x > last_data_rect_.x + last_data_rect_.w) ++c; + set_active_cell(wb, r, c, true); + return true; + } + if (drag_mode_ == DragMode::FillHandle) { + int cx = std::clamp(x, last_data_rect_.x, last_data_rect_.x + last_data_rect_.w - 1); + int cy = std::clamp(y, last_data_rect_.y, last_data_rect_.y + last_data_rect_.h - 1); + hit_cell_at(wb, cx, cy, fill_hover_row_, fill_hover_col_); + return true; + } + return true; + } + + if (type == GEMUI_PTR_UP) { + if (drag_mode_ == DragMode::Idle) return false; + if (drag_mode_ == DragMode::ResizeCol && resize_index_ >= 0) { + int logical_w = std::max(24, static_cast(std::llround( + static_cast(resize_live_size_) / last_ui_.scale))); + wb.set_col_width(wb.active_sheet(), resize_index_, logical_w); + edited_or_committed_out = true; + } else if (drag_mode_ == DragMode::ResizeRow && resize_index_ >= 0) { + int logical_h = std::max(14, static_cast(std::llround( + static_cast(resize_live_size_) / last_ui_.scale))); + wb.set_row_height(wb.active_sheet(), resize_index_, logical_h); + edited_or_committed_out = true; + } else if (drag_mode_ == DragMode::FillHandle) { + int sheet = wb.active_sheet(); + CellRange src = selection_range(sheet); + CellRange dst = compute_fill_preview(sheet); + if (!(dst == src)) { + wb.autofill_range(sheet, src, dst); + anchor_row_ = dst.r1; + anchor_col_ = dst.c1; + active_row_ = dst.r2; + active_col_ = dst.c2; + sync_editor_from_cell(wb); + edited_or_committed_out = true; + } + } + drag_mode_ = DragMode::Idle; + resize_index_ = -1; + return true; + } + + return false; +} + +} // namespace htab::ui diff --git a/ui/grid_widget.hpp b/ui/grid_widget.hpp new file mode 100644 index 0000000..2152442 --- /dev/null +++ b/ui/grid_widget.hpp @@ -0,0 +1,147 @@ +#pragma once + +#include "engine/workbook.hpp" +#include "ui/text_edit.hpp" + +#include +#include + +#include +#include +#include + +namespace htab::ui { + +enum class GridHitRegion { + Outside, + DataCell, + ColHeader, + RowHeader, +}; + +struct GridMetrics { + int row_hdr_w = 48; + int col_hdr_h = 26; + int default_col_w_logical = 96; + int default_row_h_logical = 26; + int font_logical_px = 13; + int vscroll_w = 12; +}; + +class GridWidget { + public: + static GridMetrics metrics_for(const UiScale& ui); + + int active_row() const { return active_row_; } + int active_col() const { return active_col_; } + int scroll_row() const { return scroll_row_; } + int scroll_col() const { return scroll_col_; } + CellRange selection_range(int sheet_idx) const; + + bool is_editing() const { return editing_; } + bool is_formula_bar_focused() const { return formula_bar_focused_; } + TextEditor& editor() { return editor_; } + const TextEditor& editor() const { return editor_; } + + void reset_for_sheet(const Workbook& wb, int sheet_idx); + void set_active_cell(const Workbook& wb, int row, int col, bool keep_anchor = false); + void move_active(const Workbook& wb, int drow, int dcol, bool extend_selection); + void ensure_visible(const Workbook& wb, int row, int col); + + void start_edit(const Workbook& wb, bool focus_formula_bar, const std::string* initial = nullptr); + void commit_edit(Workbook& wb); + void cancel_edit(const Workbook& wb); + void sync_editor_from_cell(const Workbook& wb); + + void draw(gemui_app_t* app, + cairo_t* cr, + const Workbook& wb, + gemui_rect_t rect, + const UiScale& ui); + + void draw_hscroll(gemui_app_t* app, + cairo_t* cr, + const Workbook& wb, + gemui_rect_t rect, + const UiScale& ui, + int hit_id_hscroll); + + bool handle_pointer(Workbook& wb, + int type, + int x, + int y, + unsigned int btn, + gemui_rect_t hscroll_rect, + bool& edited_or_committed_out); + + GridHitRegion hit_region(const Workbook& wb, + int x, + int y, + int& out_row, + int& out_col) const; + + void handle_hscroll_drag(const Workbook& wb, int x, gemui_rect_t hscroll_rect); + + private: + enum class DragMode { + Idle, + SelectRange, + FillHandle, + ResizeCol, + ResizeRow, + ScrollV, + ScrollH, + }; + + struct ColLayout { + int col = 0; + int x = 0; + int w = 0; + }; + struct RowLayout { + int row = 0; + int y = 0; + int h = 0; + }; + + int col_w(const Workbook& wb, int col) const; + int row_h(const Workbook& wb, int row) const; + int max_scroll_rows(const Workbook& wb) const; + int max_scroll_cols(const Workbook& wb) const; + CellRange compute_fill_preview(int sheet_idx) const; + + void hit_cell_at(const Workbook& wb, int x, int y, int& out_row, int& out_col) const; + void update_scroll_v_from_y(const Workbook& wb, int y); + + int scroll_row_ = 0; + int scroll_col_ = 0; + int active_row_ = 0; + int active_col_ = 0; + int anchor_row_ = 0; + int anchor_col_ = 0; + + bool editing_ = false; + bool formula_bar_focused_ = false; + TextEditor editor_; + + gemui_rect_t last_rect_{0, 0, 0, 0}; + gemui_rect_t last_data_rect_{0, 0, 0, 0}; + gemui_rect_t last_vscroll_rect_{0, 0, 0, 0}; + gemui_rect_t last_fill_handle_{0, 0, 0, 0}; + UiScale last_ui_{}; + bool has_fill_handle_ = false; + + DragMode drag_mode_ = DragMode::Idle; + int resize_index_ = -1; + int resize_start_px_ = 0; + int resize_orig_size_ = 0; + int resize_live_size_ = 0; + int fill_hover_row_ = 0; + int fill_hover_col_ = 0; + + int last_click_row_ = -1; + int last_click_col_ = -1; + uint64_t last_click_ms_ = 0; +}; + +} // namespace htab::ui diff --git a/ui/main.cpp b/ui/main.cpp new file mode 100644 index 0000000..23ad56f --- /dev/null +++ b/ui/main.cpp @@ -0,0 +1,71 @@ +#include "ui/app_window.hpp" + +#include +#include +#include + +namespace { + +bool parse_geometry(const std::string& geom, int& w_out, int& h_out) { + size_t x_pos = geom.find('x'); + if (x_pos == std::string::npos) x_pos = geom.find('X'); + if (x_pos == std::string::npos || x_pos == 0) return false; + size_t end_h = geom.find_first_of("+-", x_pos + 1); + std::string ws = geom.substr(0, x_pos); + std::string hs = (end_h == std::string::npos) + ? geom.substr(x_pos + 1) + : geom.substr(x_pos + 1, end_h - (x_pos + 1)); + if (ws.empty() || hs.empty()) return false; + int w = std::atoi(ws.c_str()); + int h = std::atoi(hs.c_str()); + if (w <= 0 || h <= 0) return false; + w_out = w; + h_out = h; + return true; +} + +void print_usage(const char* prog) { + std::cout << "Usage: " << prog << " [OPTIONS] [FILE]\n" + << "Options:\n" + << " -g, --geometry WxH Initial window dimensions (e.g. 240x296 or 960x640)\n" + << " -h, --help Show this help message\n"; +} + +} // namespace + +int main(int argc, char** argv) { + int req_w = 960; + int req_h = 640; + bool explicit_geom = false; + std::string initial_file; + + for (int i = 1; i < argc; ++i) { + std::string arg = argv[i]; + if (arg == "-h" || arg == "--help") { + print_usage(argv[0]); + return 0; + } + if ((arg == "-g" || arg == "--geometry") && i + 1 < argc) { + if (!parse_geometry(argv[++i], req_w, req_h)) { + std::cerr << "Invalid geometry: " << argv[i] << "\n"; + return 1; + } + explicit_geom = true; + continue; + } + if (arg.rfind("--geometry=", 0) == 0) { + if (!parse_geometry(arg.substr(11), req_w, req_h)) { + std::cerr << "Invalid geometry: " << arg.substr(11) << "\n"; + return 1; + } + explicit_geom = true; + continue; + } + if (!arg.empty() && arg[0] != '-') { + initial_file = arg; + } + } + + htab::ui::AppWindow app; + return app.run(req_w, req_h, explicit_geom, initial_file); +} diff --git a/ui/text_edit.hpp b/ui/text_edit.hpp new file mode 100644 index 0000000..e740c61 --- /dev/null +++ b/ui/text_edit.hpp @@ -0,0 +1,214 @@ +#pragma once + +#include +#include +#include +#include + +#include +#include +#include + +namespace htab::ui { + +struct UiScale { + double scale = 1.0; + bool compact = false; + bool phys_tiny = false; + bool touch = false; +}; + +inline UiScale compute_ui_scale(const gemui_app_t* app, int w, int h) { + double sys_scale = std::max(0.5, gemui_scale(app)); + bool phys_tiny = (w <= 320 || h <= 360); + double eff_scale = phys_tiny ? 1.0 : sys_scale; + bool compact = phys_tiny || + (static_cast(w) / eff_scale <= 320.0) || + (static_cast(h) / eff_scale <= 360.0); + bool touch = !phys_tiny && gemui_touch_mode(app); + return UiScale{eff_scale, compact, phys_tiny, touch}; +} + +inline int spx(int logical_px, const UiScale& ui) { + if (logical_px <= 0) return 0; + int v = static_cast(std::floor(static_cast(logical_px) * ui.scale + 0.5)); + return v < 1 ? 1 : v; +} + +inline int pt_delta_for_ui(const gemui_theme_t* t, int logical_px, const UiScale& ui) { + double sc = (t && t->scale > 0.0) ? t->scale : 1.0; + int base_px = (t && t->base_font_size > 0) ? t->base_font_size : 15; + int pt_delta = 0; + if (ui.phys_tiny) { + int target = std::max(9, logical_px); + pt_delta = static_cast(std::ceil(static_cast(target - base_px) / sc)); + } else { + pt_delta = logical_px - 15; + } + while (base_px + static_cast(std::llround(static_cast(pt_delta) * sc)) < 9) { + ++pt_delta; + } + return pt_delta; +} + +inline int measure_text_px(cairo_t* cr, + const gemui_theme_t* t, + const std::string& text, + int logical_px, + const UiScale& ui, + bool bold = false) { + if (text.empty()) return 0; + cairo_save(cr); + cairo_rectangle(cr, 0, 0, 0, 0); + cairo_clip(cr); + int tw = gemui_draw_text(cr, t, gemui_rect_t{0, 0, 10000, 128}, text.c_str(), + pt_delta_for_ui(t, logical_px, ui), bold, GEMUI_ALIGN_LEFT, + t->fg_main); + cairo_restore(cr); + return tw; +} + +struct TextEditor { + std::string text; + size_t cursor = 0; + + void set_text(std::string s) { + text = std::move(s); + cursor = text.size(); + } + + void clear() { + text.clear(); + cursor = 0; + } + + size_t prev_cp_pos(size_t pos) const { + if (pos == 0) return 0; + size_t p = pos - 1; + while (p > 0 && (static_cast(text[p]) & 0xC0) == 0x80) { + --p; + } + return p; + } + + size_t next_cp_pos(size_t pos) const { + if (pos >= text.size()) return text.size(); + size_t p = pos + 1; + while (p < text.size() && (static_cast(text[p]) & 0xC0) == 0x80) { + ++p; + } + return p; + } + + void move_left() { cursor = prev_cp_pos(cursor); } + void move_right() { cursor = next_cp_pos(cursor); } + void move_home() { cursor = 0; } + void move_end() { cursor = text.size(); } + + void insert_utf8(const char* utf8) { + if (!utf8 || !utf8[0]) return; + std::string clean; + for (const char* p = utf8; *p; ++p) { + unsigned char uc = static_cast(*p); + if (uc >= 0x20 && uc != 0x7F) clean.push_back(*p); + } + if (clean.empty()) return; + text.insert(cursor, clean); + cursor += clean.size(); + } + + void backspace() { + if (cursor == 0) return; + size_t p = prev_cp_pos(cursor); + text.erase(p, cursor - p); + cursor = p; + } + + void del_char() { + if (cursor >= text.size()) return; + size_t n = next_cp_pos(cursor); + text.erase(cursor, n - cursor); + } + + bool handle_key(KeySym ks, unsigned int state, const char* utf8) { + bool ctrl = (state & ControlMask) != 0; + if (!ctrl) { + if (ks == XK_Left) { move_left(); return true; } + if (ks == XK_Right) { move_right(); return true; } + if (ks == XK_Home) { move_home(); return true; } + if (ks == XK_End) { move_end(); return true; } + if (ks == XK_BackSpace) { backspace(); return true; } + if (ks == XK_Delete) { del_char(); return true; } + if (utf8 && utf8[0]) { + insert_utf8(utf8); + return true; + } + } + return false; + } +}; + +inline void draw_single_line_editor(cairo_t* cr, + const gemui_theme_t* t, + gemui_rect_t r, + const TextEditor& ed, + const char* placeholder, + bool focused, + int logical_px, + const UiScale& ui) { + double rad = 3.0 * ui.scale; + double lw = std::max(1.0, (focused ? 1.5 : 1.0) * ui.scale); + gemui_fill_round(cr, r, rad, focused ? t->bg_input_focus : t->bg_input); + gemui_stroke_round(cr, r, rad, lw, focused ? t->highlight : t->border); + + int pad = spx(4, ui); + int vpad = std::max(1, spx(1, ui)); + gemui_rect_t inner{r.x + pad, r.y + vpad, std::max(1, r.w - pad * 2), + std::max(1, r.h - vpad * 2)}; + if (inner.w <= 4 || inner.h <= 4) return; + + int delta = pt_delta_for_ui(t, logical_px, ui); + if (ed.text.empty() && !focused) { + if (placeholder && placeholder[0]) { + gemui_draw_text(cr, t, inner, placeholder, delta, false, GEMUI_ALIGN_LEFT, t->fg_muted); + } + return; + } + + std::string prefix = ed.text.substr(0, std::min(ed.cursor, ed.text.size())); + int caret_x = measure_text_px(cr, t, prefix, logical_px, ui, false); + int edge_guard = spx(4, ui); + int scroll_x = 0; + if (caret_x > inner.w - edge_guard) { + scroll_x = caret_x - (inner.w - edge_guard); + } + + cairo_save(cr); + cairo_rectangle(cr, inner.x, inner.y, inner.w, inner.h); + cairo_clip(cr); + + if (!ed.text.empty()) { + gemui_rect_t draw_r{inner.x - scroll_x, inner.y, + std::max(inner.w + scroll_x + spx(32, ui), 8000), inner.h}; + gemui_draw_text(cr, t, draw_r, ed.text.c_str(), delta, false, GEMUI_ALIGN_LEFT, + t->fg_bright); + } else if (placeholder && placeholder[0]) { + gemui_draw_text(cr, t, inner, placeholder, delta, false, GEMUI_ALIGN_LEFT, t->fg_muted); + } + + if (focused) { + int cx = inner.x + caret_x - scroll_x; + if (cx >= inner.x && cx <= inner.x + inner.w - 1) { + int cpad = std::max(1, spx(2, ui)); + gemui_set_source(cr, t->highlight); + cairo_set_line_width(cr, std::max(1.5, 1.5 * ui.scale)); + cairo_move_to(cr, cx + 0.5, inner.y + cpad); + cairo_line_to(cr, cx + 0.5, inner.y + inner.h - cpad); + cairo_stroke(cr); + } + } + + cairo_restore(cr); +} + +} // namespace htab::ui