diff --git a/.github/workflows/release-deb.yml b/.github/workflows/release-deb.yml index 057901c..ad6dbdc 100644 --- a/.github/workflows/release-deb.yml +++ b/.github/workflows/release-deb.yml @@ -24,7 +24,7 @@ jobs: sudo apt-get update sudo apt-get install -y \ build-essential pkg-config xvfb xdotool xfwm4 dbus-x11 x11-utils imagemagick dpkg-dev \ - libsdl2-dev libcairo2-dev + libsdl2-dev libcairo2-dev gnumeric - name: Install the locked Ziran toolchain run: | diff --git a/.github/workflows/security.yml b/.github/workflows/security.yml index ffe91b1..58f3ba9 100644 --- a/.github/workflows/security.yml +++ b/.github/workflows/security.yml @@ -26,7 +26,7 @@ jobs: sudo apt-get update sudo apt-get install -y \ build-essential pkg-config xvfb xdotool xfwm4 dbus-x11 x11-utils imagemagick \ - libsdl2-dev libcairo2-dev + libsdl2-dev libcairo2-dev gnumeric - name: Install the locked Ziran toolchain run: | diff --git a/.gitignore b/.gitignore index 3af3256..11dabb6 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,5 @@ private/ dist/ ziran.local.toml + +/backup/ diff --git a/Makefile b/Makefile index c72eb7b..0e23d5a 100644 --- a/Makefile +++ b/Makefile @@ -11,7 +11,7 @@ DIST_DIR ?= dist APP := build/workbook-desktop CELL := build/cell -TESTS := source_audit_test structure_test conversion_test differential_fuzz desktop_test parity_test +TESTS := gnumeric_test source_audit_test structure_test conversion_test differential_fuzz desktop_test parity_test TEST_PROGRAMS := $(TESTS:%=build/%) SOURCES := $(wildcard src/*.zi) ziran.toml ziran.lock @@ -20,7 +20,7 @@ SOURCES := $(wildcard src/*.zi) ziran.toml ziran.lock # has the same layout. NATIVE_FLAGS := -std=c99 -O2 -ffunction-sections -fdata-sections -Wl,--gc-sections -.PHONY: build cell check run test test-ci structure-test conversion-test desktop-test parity fuzz audit install deb clean +.PHONY: build cell check run test test-ci structure-test conversion-test gnumeric-test desktop-test parity fuzz audit install deb clean build: $(APP) $(CELL) @@ -61,9 +61,9 @@ audit: build/source_audit_test # functions need a Gnumeric master build (see tests/parity_test.zi), which a # stock CI runner lacks, so CI runs test-ci and the full gate is `make test`. desktop-test: build build/desktop_test - @env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY build/desktop_test + @env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS YUE_DESKTOP_RECOVERY=0 GSETTINGS_BACKEND=memory build/desktop_test -test-ci: build audit structure-test conversion-test desktop-test +test-ci: build audit structure-test conversion-test gnumeric-test desktop-test test: test-ci parity @@ -88,6 +88,8 @@ install: build @$(ZIRAN) install --prefix $(PREFIX) @mkdir -p $(PREFIX)/bin $(PREFIX)/share/applications @install -m 0755 $(CELL) $(PREFIX)/bin/cell + @sed 's|^Exec=workbook %f$$|Exec=$(PREFIX)/bin/workbook %f|' packaging/workbook.desktop \ + > $(PREFIX)/share/applications/workbook.desktop @ln -sf workbook $(PREFIX)/bin/geld @sed 's|^Exec=geld$$|Exec=$(PREFIX)/bin/geld|' packaging/geld.desktop \ > $(PREFIX)/share/applications/geld.desktop @@ -103,7 +105,7 @@ Priority: optional Architecture: amd64 Maintainer: Waozi Installed-Size: INSTALLED_SIZE -Depends: libc6, libsdl2-2.0-0, libcairo2 +Depends: libc6, libsdl2-2.0-0, libcairo2, gnumeric Homepage: https://github.com/kryonlabs/workbook Description: Spreadsheet editor compatible with Gnumeric Workbook is a native spreadsheet editor written in Ziran with Kryon. It reads @@ -135,3 +137,6 @@ structure-test: build/structure_test conversion-test: build/conversion_test @build/conversion_test + +gnumeric-test: build/gnumeric_test + @env -u DISPLAY -u WAYLAND_DISPLAY -u XAUTHORITY -u DBUS_SESSION_BUS_ADDRESS GSETTINGS_BACKEND=memory build/gnumeric_test diff --git a/README.md b/README.md index 3f35d8f..106f356 100644 --- a/README.md +++ b/README.md @@ -8,18 +8,35 @@ from the Makefile and configuration. `src/app.zi` is the desktop application and function library, .gnumeric/CSV I/O). `src/cell.zi` is the headless driver built on the same engine, and `tests/*.zi` are the test programs. -The engine reads and writes `.gnumeric` (Gnumeric XML, gzipped or plain), -evaluates the Gnumeric expression language (references, ranges, sheets, -operators, 120+ functions with Gnumeric semantics including errors and -date serials), and is verified 1:1 against the installed Gnumeric by -`tests/parity_test.zi` — every fixture is evaluated by both engines and -compared cell by cell, including round-trips through our own -`.gnumeric` writer. Format notes: `docs/GNUMERIC_PARITY.md`. +Imported `.gnumeric` documents use the installed Gnumeric document library +(`libspreadsheet.so`). Workbook keeps that native document for reading, +calculation, editing, row and column operations, saving, and undo. Shared +expressions, arrays, named expressions, time arithmetic, number formats, +styles, merged regions, print settings and other Gnumeric document features +therefore survive a save. Dates and numbers display with Gnumeric's formatting. +Both gzip-compressed and plain XML documents are accepted. -The engine's helpers live beside it: `src/quad.zi` (double-double arithmetic), -`src/xml.zi` and `src/gzip.zi` (the Gnumeric file format), `src/formula_text.zi` -(cell names and rounding used by formulas), and `src/c_runtime.zi` (the C -library calls the engine makes). +The editor can open a file directly: + + workbook /path/to/file.gnumeric + +This saves edits back to that file. A file that fails to load is never replaced +by an autosaved empty workbook. Launching without a file keeps the existing +profile behavior described below. The desktop entry advertises Gnumeric files. + +Install `gnumeric` for native document support. The library loads on demand; +when it is unavailable, a Gnumeric import fails without changing its file. +Compatibility follows the installed Gnumeric version and plugins. Workbook's +UI remains a basic cell editor. Cell fonts, fills, borders, row/column sizes, +merged-cell geometry, charts, drawing objects and print layout are preserved +in the document; the grid retains its own visual layout and styling, and does +not render or edit drawing objects. Complete visual parity is still pending. + +New workbooks and CSV use Workbook's independent Ziran engine. Its helpers +live beside it: `src/quad.zi` (double-double arithmetic), `src/xml.zi`, +`src/gzip.zi`, `src/formula_text.zi`, and `src/c_runtime.zi`. +`src/gnumeric.zi` is the Ziran adapter for Gnumeric's public native ABI. +Format and verification notes: `docs/GNUMERIC_PARITY.md`. ## build & run @@ -35,7 +52,8 @@ development packages installed. make run # open the editor make test # source audit, structure and conversion tests, desktop test on a private display, gnumeric parity make test-ci # the same without parity, which is what CI runs - make parity # 1:1 evaluation tests against the installed gnumeric + make gnumeric-test # native document, edit, undo and round-trip regressions + make parity # evaluation and round-trip tests against Gnumeric make fuzz REFERENCE=PATH # compare this cell with another on generated inputs make install # install workbook, cell, and geld under ~/.local make deb # build a Debian package @@ -59,7 +77,9 @@ display; it never opens a window on your desktop. Parity compares against the against `GNUMERIC_SSCONVERT`, or a local master build at `~/Tools/gnumeric-1.12.62`; the newest catalog functions exist only in a Gnumeric master build, so an older distribution Gnumeric reports those fixtures -as different. CI therefore runs `make test-ci`. +as different. For imported documents, use a reference from the same installed +version, e.g. `GNUMERIC_SSCONVERT=/usr/bin/ssconvert make parity`. +CI runs `make test-ci` with Gnumeric installed. The menu test also runs a private Xfce window manager and D-Bus session. It checks that the first right-click after another window has focus shows the diff --git a/docs/GNUMERIC_PARITY.md b/docs/GNUMERIC_PARITY.md index 0c451c3..549ff27 100644 --- a/docs/GNUMERIC_PARITY.md +++ b/docs/GNUMERIC_PARITY.md @@ -1,14 +1,44 @@ # Workbook ↔ Gnumeric parity notes -Workbook targets drop-in compatibility with Gnumeric 1.12.x: it reads and -writes `.gnumeric` files, evaluates the same expression language, and is -tested 1:1 against the installed `gnumeric`/`ssconvert` (1.12.57) binaries. +Imported documents use Gnumeric's installed native library, loaded through +`src/gnumeric.zi`. The native document remains alive for calculation, edits, +structural operations and saves. Undo clones it through an in-memory native +save and load, so document metadata is part of the undo state too. + +`tests/gnumeric_test.zi` covers shared expressions, string time arithmetic, +named expressions, date and decimal formats, literal strings, booleans, +arrays and their edit boundaries, coordinates beyond 256 columns and 65,536 +rows, UTF-16 XML, edits, row changes, independent undo snapshots and native +round trips. The source URI is retained for relative workbook links. +Its synthetic `tests/document.gnumeric` lives outside the CSV fixture folder +because its large coordinates would produce millions of empty CSV fields. + +Compare imported files against `ssconvert` from the same installed Gnumeric +version. A newer reference can have functions or plugins missing from the +runtime library. For the distribution installation: + + GNUMERIC_SSCONVERT=/usr/bin/ssconvert make parity + +The basic grid displays Gnumeric's formatted cell values. Native document +support does not imply complete UI parity: the grid retains its own layout +and styling. Cell fonts, fills, borders, sizes, merged regions, charts, drawing +objects and print layout are retained on save; drawing objects and print +layout are not rendered or edited by the grid. +Gnumeric canonicalizes function names to lowercase and exposes a leading +apostrophe in entered text for literal strings that resemble formulas. +Unknown features from versions newer than the installed Gnumeric are subject +to that Gnumeric version's own import limitations. + +The notes below describe the file format and Workbook's independent Ziran +engine, which still serves new workbooks and CSV. They do not define the +native document library's feature inventory. ## The .gnumeric container A `.gnumeric` file is XML in the `http://www.gnumeric.org/v10.dtd` namespace, either plain or gzip-compressed. Gnumeric itself writes gzip; it accepts both -on read. Workbook reads both and writes plain XML (valid for Gnumeric). +on read. Workbook reads both. Imported documents are saved by Gnumeric in its native +compressed format; new workbooks use the Ziran writer and plain XML. Minimal document Gnumeric 1.12.57 accepts: @@ -16,7 +46,7 @@ Minimal document Gnumeric 1.12.57 accepts: - Cols="256" Rows="65536">Data + Data Data @@ -30,7 +60,6 @@ Minimal document Gnumeric 1.12.57 accepts: - ``` Full document order observed from Gnumeric output: @@ -87,12 +116,11 @@ math 63, stat 103, string 29, financial 40, complex 49, random 34, lookup 20, info 21, date 13, database 13, eng 12, numtheory 9, logical 5, flt 4, christian-date 6, tsa 4, hebrew-date 1, derivatives 1. -Workbook implements 131 functions today (arithmetic, aggregation, -statistics, text, logical, date/time, lookup, information, radix -conversions) — every one pinned 1:1 to Gnumeric's output by the fixture -suite. The full inventory of what Gnumeric provides is tracked in -`tests/functions-manifest.txt`; each addition follows the same recipe: -implement, add fixture rows, verify against `ssconvert` cell by cell. +The independent Ziran engine implements a subset of the function inventory +for new workbooks and CSV. Imported Gnumeric documents use the installed +native library's functions and plugins. The current parity suite verifies +that document integration, evaluated exports and saved round trips; it is not +a separate numerical oracle for the independent evaluator. ## 1:1 test methodology @@ -101,6 +129,6 @@ Ground truth is the installed Gnumeric itself, never hand-computed: 1. Fixture `.gnumeric` files live in `tests/fixtures/`. 2. `ssconvert fixture.gnumeric out.csv` (LC_ALL=C) → expected values. 3. `cell eval fixture.gnumeric` → workbook's own evaluation as CSV. -4. `scripts/parity-test.sh` diffs both outputs cell-by-cell. +4. `tests/parity_test.zi` compares both outputs cell by cell. 5. Round-trip: `cell copy in out.gnumeric` writes a `.gnumeric` that Gnumeric re-reads with identical evaluated values. diff --git a/packaging/workbook.desktop b/packaging/workbook.desktop index 3844963..535dba5 100644 --- a/packaging/workbook.desktop +++ b/packaging/workbook.desktop @@ -2,6 +2,7 @@ Type=Application Name=Workbook Comment=Spreadsheet editor compatible with Gnumeric -Exec=workbook +Exec=workbook %f Terminal=false Categories=Office; +MimeType=application/x-gnumeric; diff --git a/src/app.zi b/src/app.zi index 804e2ff..7e031ac 100644 --- a/src/app.zi +++ b/src/app.zi @@ -40,8 +40,8 @@ FreeBytes :: (block: *void) #foreign libc "free"; TimeSpec :: struct { seconds: s64; nanoseconds: s64; } ClockTime :: (clock: s32, value: *TimeSpec) -> s32 #foreign libc "clock_gettime"; -MaxRows :: 200; -MaxColumns :: 40; +MaxRows :: 16777216; // GNM_MAX_ROWS +MaxColumns :: 16384; // GNM_MAX_COLS CellTextMax :: 256; ColumnWidth :: 110.0; RowHeight :: 28.0; @@ -85,6 +85,7 @@ edit_sheet: s32 = 0; scroll_row: s32 = 0; scroll_column: s32 = 0; dirty: bool = false; +load_failed: bool = false; // A failed save is tried again at this monotonic time, in milliseconds. It is // a time, not a frame count: an idle window draws fewer frames. save_retry_at: s64 = 0; @@ -274,7 +275,13 @@ LoadWorkbook :: () { override = null if profile_name == "geld" { override = EnvironmentValue(CPath("GELD_DIR")) } } - if override != null && override[0] != 0 { + explicit: [4096]u8 + if OpenFileArgument(explicit[:]) { + SetText(data_path[:], TextUntilNul(explicit[:])) + name: string = TextUntilNul(explicit[:]) + base: s32 = cast(s32)name.count - cast(s32)FileName(name).count + if base > 0 { SetText(data_directory[:], name[0:base]) } + } else if override != null && override[0] != 0 { SetText(data_directory[:], TextFromCString(override)) SetText(data_path[:], TextFromCString(override)) AppendText(data_path[:], "/workbook.gnumeric") @@ -313,7 +320,11 @@ LoadWorkbook :: () { } } if !imported && PathAccess(*data_path[0], 0) == 0 { - unused Engine.WorkbookLoadFile(workbook, cast(*s8)*data_path[0]) + load_failed = Engine.WorkbookLoadFile(workbook, cast(*s8)*data_path[0]) == 0 + if load_failed { + SetText(status[:], "Could not open ") + AppendText(status[:], FileName(path)) + } } // A file supplies its own sheets; a new workbook starts with one. if Engine.WorkbookSheetCount(workbook) == 0 { @@ -346,6 +357,8 @@ EnsureDataDirectory :: () -> bool { } SaveWorkbook :: (finish_edit: bool) { + // A failed import must never autosave an empty grid over its source. + if load_failed { return } if finish_edit && edit_focused { CommitCell() EndEdit() @@ -1292,7 +1305,7 @@ DrawGrid :: (session: Session, viewport: Rectangle) { while column < scroll_column + visible_columns && column < columns { name: [8]u8 AppendCellColumn(name[:], column) - GridSquare(session, 20 + column, Rectangle.{ColumnX(table, column), table.y, + GridSquare(session, 20 + column - scroll_column, Rectangle.{ColumnX(table, column), table.y, ColumnWidth, HeaderHeight}, ifx here && selection_axis == 2 && column == selected_column then SelectedBackground() else HeaderBackground(), TextUntilNul(name[:])) column += 1 } @@ -1302,14 +1315,15 @@ DrawGrid :: (session: Session, viewport: Rectangle) { y: float32 = RowY(table, row) number: [16]u8 FormatBytes(*number[0], 16, cast(*u8)Engine.CText("%d"), row + 1) - GridSquare(session, 100 + row, Rectangle.{table.x, y, RowHeaderWidth, RowHeight}, + GridSquare(session, 1000 + shown, Rectangle.{table.x, y, RowHeaderWidth, RowHeight}, ifx here && selection_axis == 1 && row == selected_row then SelectedBackground() else HeaderBackground(), TextUntilNul(number[:])) column = scroll_column while column < scroll_column + visible_columns && column < columns { display: [256]u8 Engine.WorkbookCellDisplay(workbook, sheet_index, row, column, cast(*s8)*display[0], 256) - Engine.RoundForDisplay(cast(*s8)*display[0], 256) + // Imported cells already use Gnumeric's exact number format. + if workbook.native == null { Engine.RoundForDisplay(cast(*s8)*display[0], 256) } fill: Color = CellBackground() // A range is shaded around its active cell, as in Gnumeric. active: bool = row == selected_row && column == selected_column @@ -1317,7 +1331,7 @@ DrawGrid :: (session: Session, viewport: Rectangle) { in_rows: bool = selection_axis == 2 || (row >= first_row && row <= last_row) in_columns: bool = selection_axis == 1 || (column >= first_column && column <= last_column) if here && in_rows && in_columns && !(spans && active) { fill = SelectedBackground() } - GridSquare(session, 1000 + row * 64 + column, + GridSquare(session, 10000 + shown * visible_columns + column - scroll_column, Rectangle.{ColumnX(table, column), y, ColumnWidth, RowHeight}, fill, TextUntilNul(display[:])) column += 1 @@ -1703,14 +1717,14 @@ RowY :: (table: Rectangle, row: s32) -> float32 { // One grid square: a bordered box and its clipped text. GridSquare :: (session: Session, key: s32, bounds: Rectangle, fill: Color, text: string) { box: BoxProps - box.key = cast(u64)(100000 + key) + box.key = 1000000 + cast(u64)key * 2 box.bounds = bounds box.fill = fill box.border = GridLineColor() Box(session, box) if text.count == 0 { return } label: TextProps - label.key = cast(u64)(200000 + key) + label.key = 1000001 + cast(u64)key * 2 label.text = text label.font = Text14 label.wrap = cast(TextWrap)TextWrapNone @@ -1822,6 +1836,29 @@ ProfileName :: (name: string) -> bool { return true } +// Linux's native host owns main; read its file argument without changing +// the profile selection for launches that supplied no document. +OpenFileArgument :: (out: []u8) -> bool { + command: [8192]u8 + descriptor: s32 = OpenFile(CPath("/proc/self/cmdline"), 0) + if descriptor < 0 { return false } + length: s64 = ReadFileBytes(descriptor, *command[0], 8191) + CloseFile(descriptor) + if length <= 0 { return false } + at: s32 = 0 + while at < cast(s32)length && command[at] != 0 { at += 1 } + at += 1 + if at >= cast(s32)length { return false } + end: s32 = at + while end < cast(s32)length && command[end] != 0 { end += 1 } + name: string = TextView(command[at:end]) + if name.count < 9 { return false } + suffix: string = name[cast(s32)name.count - 9:cast(s32)name.count] + if Engine.TextCompareFoldLiteral(cast(*s8)CPath(suffix), ".gnumeric") != 0 { return false } + SetText(out, name) + return true +} + // Whether the program was started under the given name. `geld` is a link to // workbook, and it opens the geld profile because of the name it was run as. StartedAs :: (name: string) -> bool { diff --git a/src/engine.zi b/src/engine.zi index 80deadb..6c06afa 100644 --- a/src/engine.zi +++ b/src/engine.zi @@ -3,10 +3,11 @@ #load "formula_text.zi"; #load "xml.zi"; #load "gzip.zi"; +#load "gnumeric.zi"; WB_MAX_SHEETS :: 64; -WB_MAX_COLS :: 256; -WB_MAX_ROWS :: 65536; +WB_MAX_COLS :: 16384; +WB_MAX_ROWS :: 16777216; WB_TEXT_MAX :: 512; WB_ARGS_MAX :: 4096; WB_DEPTH_MAX :: 64; @@ -33,7 +34,7 @@ CELL_LITERAL :: 0; CELL_FORMULA :: 1; Cell :: struct { - key: s32 + key: s64 text: *s8 kind: s32 cached_kind: s32 @@ -56,6 +57,7 @@ Sheet :: struct { } Workbook :: struct { + native: *void sheets: *Sheet sheet_count: s32 sheet_cap: s32 @@ -396,6 +398,7 @@ WorkbookFree :: (wb: *Workbook) { SheetFree(*wb.sheets[i]) i += 1 } + NativeClose(wb.native) MemoryFree(cast(*void)wb.sheets) MemoryFree(cast(*void)wb) } @@ -404,6 +407,16 @@ WorkbookFree :: (wb: *Workbook) { // with its source, cached value and file value. The editor keeps such copies // as the states that undo and redo return to. Null when memory runs out. WorkbookClone :: (wb: *Workbook) -> *Workbook { + if wb.native != null { + copy: *Workbook = WorkbookNew() + if copy == null { return null } + copy.native = NativeClone(wb.native) + if copy.native == null || NativeRefresh(copy) == 0 { + WorkbookFree(copy) + return null + } + return copy + } copy: *Workbook = cast(*Workbook)MemoryAllocateZeroed(1, cast(u64)size_of(Workbook)) if copy == null { return null @@ -458,7 +471,7 @@ WorkbookCellCount :: (wb: *Workbook) -> s32 { } WorkbookAddSheet :: (wb: *Workbook, name: *s8) -> *Sheet { - if wb.sheet_count >= WB_MAX_SHEETS { + if wb.native == null && wb.sheet_count >= WB_MAX_SHEETS { return null } if wb.sheet_count >= wb.sheet_cap { @@ -488,19 +501,19 @@ WorkbookFindSheet :: (wb: *Workbook, name: *s8) -> *Sheet { return null } -CellKey :: (row: s32, col: s32) -> s32 { - return row * WB_MAX_COLS + col +CellKey :: (row: s32, col: s32) -> s64 { + return cast(s64)row * WB_MAX_COLS + col } -CellKeyRow :: (key: s32) -> s32 { - return key / WB_MAX_COLS +CellKeyRow :: (key: s64) -> s32 { + return cast(s32)(key / WB_MAX_COLS) } -CellKeyCol :: (key: s32) -> s32 { - return key % WB_MAX_COLS +CellKeyCol :: (key: s64) -> s32 { + return cast(s32)(key % WB_MAX_COLS) } -CellSearch :: (sheet: *Sheet, key: s32, at: *s32) -> s32 { +CellSearch :: (sheet: *Sheet, key: s64, at: *s32) -> s32 { lo: s32 = 0 hi: s32 = sheet.cell_count while lo < hi { @@ -528,7 +541,7 @@ CellAt :: (sheet: *Sheet, row: s32, col: s32) -> *Cell { CellObtain :: (sheet: *Sheet, row: s32, col: s32) -> *Cell { index: s32 = 0 - key: s32 = CellKey(row, col) + key: s64 = CellKey(row, col) if CellSearch(sheet, key, *index) != 0 { return *sheet.cells[index] } @@ -628,6 +641,7 @@ SetCellText :: (wb: *Workbook, sheet_index: s32, row: s32, col: s32, text: *s8) if row < 0 || row >= WB_MAX_ROWS || col < 0 || col >= WB_MAX_COLS { return 0 } + if wb.native != null { return NativeSet(wb, sheet_index, row, col, text) } if text == null || text[0] == 0 { SheetDrop(sheet, row, col) return 1 @@ -2282,6 +2296,7 @@ SheetDeleteColumn :: (sheet: *Sheet, at_col: s32) -> s32 { } WorkbookInsertRow :: (wb: *Workbook, sheet_index: s32, row: s32) -> s32 { + if wb.native != null { return NativeShift(wb, sheet_index, row, true, true) } if sheet_index < 0 || sheet_index >= wb.sheet_count { return 0 } @@ -2290,6 +2305,7 @@ WorkbookInsertRow :: (wb: *Workbook, sheet_index: s32, row: s32) -> s32 { } WorkbookDeleteRow :: (wb: *Workbook, sheet_index: s32, row: s32) -> s32 { + if wb.native != null { return NativeShift(wb, sheet_index, row, true, false) } if sheet_index < 0 || sheet_index >= wb.sheet_count { return 0 } @@ -2298,6 +2314,7 @@ WorkbookDeleteRow :: (wb: *Workbook, sheet_index: s32, row: s32) -> s32 { } WorkbookInsertColumn :: (wb: *Workbook, sheet_index: s32, col: s32) -> s32 { + if wb.native != null { return NativeShift(wb, sheet_index, col, false, true) } if sheet_index < 0 || sheet_index >= wb.sheet_count { return 0 } @@ -2306,6 +2323,7 @@ WorkbookInsertColumn :: (wb: *Workbook, sheet_index: s32, col: s32) -> s32 { } WorkbookDeleteColumn :: (wb: *Workbook, sheet_index: s32, col: s32) -> s32 { + if wb.native != null { return NativeShift(wb, sheet_index, col, false, false) } if sheet_index < 0 || sheet_index >= wb.sheet_count { return 0 } @@ -2314,6 +2332,7 @@ WorkbookDeleteColumn :: (wb: *Workbook, sheet_index: s32, col: s32) -> s32 { } WorkbookEvaluate :: (wb: *Workbook) { + if wb.native != null { unused NativeRefresh(wb); return } i: s32 = 0 while i < wb.sheet_count { EvaluateSheet(wb, *wb.sheets[i]) @@ -28740,53 +28759,45 @@ FnPochhammer :: (st: *EvalState, args: *Val, count: s32, marks: *s32) -> Val { } WorkbookLoadFile :: (wb: *Workbook, path: *s8) -> s32 { - raw: *u8 = null - bytes: *u8 = null size: s32 = 0 - text: *s8 = null - is_gzip: s32 = 0 - ok: s32 = 0 - raw = ReadFileBytes(path, *size) - if raw == null { - return 0 - } - bytes = cast(*u8)MemoryAllocate(cast(u64)(size + 1)) - if bytes == null { - FreeFileBytes(raw) - return 0 - } - if size > 0 { - MemoryCopy(cast(*void)bytes, cast(*void)raw, cast(u64)size) - } + raw: *u8 = ReadFileBytes(path, *size) + if raw == null { return 0 } + bytes: *u8 = cast(*u8)MemoryAllocate(cast(u64)size + 1) + if bytes == null { FreeFileBytes(raw); return 0 } + if size > 0 { MemoryCopy(cast(*void)bytes, cast(*void)raw, cast(u64)size) } bytes[size] = 0 FreeFileBytes(raw) - is_gzip = GzipIs(bytes, cast(u64)size) - if is_gzip != 0 { - inflated_len: u64 = 0 - text = cast(*s8)GzipDecompress(bytes, cast(u64)size, *inflated_len) + first: *u8 = bytes + if size >= 3 && first[0] == 239 && first[1] == 187 && first[2] == 191 { first = *first[3] } + while IsSpaceByte(cast(s32)first[0]) != 0 { first = *first[1] } + length: u64 = TextLength(path) + document: bool = length >= 9 && TextCompareFoldLiteral(*path[length - 9], ".gnumeric") == 0 + csv: bool = length >= 4 && TextCompareFoldLiteral(*path[length - 4], ".csv") == 0 + csv_gzip: bool = length >= 7 && TextCompareFoldLiteral(*path[length - 7], ".csv.gz") == 0 + if csv_gzip { + inflated: u64 = 0 + text: *u8 = GzipDecompress(bytes, cast(u64)size, *inflated) FreeFileBytes(bytes) - if text == null { - return 0 - } - } else { - text = cast(*s8)bytes - } - ok = 0 - if TextCompareNLiteral(text, " s32 { @@ -28902,6 +28913,7 @@ ParseGnumericCell :: (sheet: *Sheet, node: *XmlNode) { } WorkbookWriteGnumeric :: (wb: *Workbook, path: *s8) -> s32 { + if wb.native != null { return NativeSave(wb.native, path, false) } buf: XmlBuffer ok: s32 = 0 sheet_index: s32 = 0 @@ -28911,7 +28923,18 @@ WorkbookWriteGnumeric :: (wb: *Workbook, path: *s8) -> s32 { XmlBufferRaw(*buf, CText(" \n")) sheet_index = 0 while sheet_index < wb.sheet_count { - XmlBufferRaw(*buf, CText(" ")) + columns: s32 = 256 + rows: s32 = 65536 + while columns <= wb.sheets[sheet_index].max_col && columns < WB_MAX_COLS { columns *= 2 } + while rows <= wb.sheets[sheet_index].max_row && rows < WB_MAX_ROWS { rows *= 2 } + dimension: [32]s8 + XmlBufferRaw(*buf, CText(" ")) XmlBufferEsc(*buf, *wb.sheets[sheet_index].name[0]) XmlBufferRaw(*buf, CText("\n")) sheet_index += 1 @@ -29099,6 +29122,7 @@ WriteCsvField :: (buf: *XmlBuffer, text: *s8) { } WorkbookExportCsv :: (wb: *Workbook, path: *s8) -> s32 { + if wb.native != null { return NativeSave(wb.native, path, true) } buf: XmlBuffer ok: s32 = 0 if wb.sheet_count == 0 { @@ -29212,6 +29236,10 @@ WorkbookCellText :: (wb: *Workbook, index: s32, row: s32, col: s32) -> *s8 { } WorkbookCellDisplay :: (wb: *Workbook, index: s32, row: s32, col: s32, out: *s8, cap: s32) { + if wb.native != null && index >= 0 && index < wb.sheet_count { + NativeDisplay(wb, index, row, col, out, cap) + return + } cell: *Cell = null v: Val if index < 0 || index >= wb.sheet_count { diff --git a/src/gnumeric.zi b/src/gnumeric.zi new file mode 100644 index 0000000..b776b9d --- /dev/null +++ b/src/gnumeric.zi @@ -0,0 +1,373 @@ +// Gnumeric's native document engine owns imported .gnumeric workbooks. +// Its public C ABI is loaded on demand; the editor and headless driver stay +// Ziran. Keeping the native document retains styles, names, arrays, charts, +// print settings and shared expressions through edits, saves and undo. +NativeArray :: struct { data: **void; count: u32; } +NativePosition :: struct { col: s32; row: s32; } + +#scope_file +native_dl :: #system_library "dl"; +NativeOpenLibrary :: (name: *s8, flags: s32) -> *void #foreign native_dl "dlopen"; +NativeSymbol :: (library: *void, name: *s8) -> *void #foreign native_dl "dlsym"; +native_library: *void; +native_context: *void; +native_tried: bool; +native_ready: bool; +NativeFn_pre_init :: #type (s32, **s8) -> *void #c_call; +native_pre_init: NativeFn_pre_init; +NativeFn_initialize :: #type () #c_call; +native_initialize: NativeFn_initialize; +NativeFn_new_context :: #type () -> *void #c_call; +native_new_context: NativeFn_new_context; +NativeFn_plugins_init :: #type (*void) #c_call; +native_plugins_init: NativeFn_plugins_init; +NativeFn_plugins :: #type () -> *void #c_call; +native_plugins: NativeFn_plugins; +NativeFn_activate :: #type (*void, **void) #c_call; +native_activate: NativeFn_activate; +NativeFn_error_free :: #type (*void) #c_call; +native_error_free: NativeFn_error_free; +NativeFn_new_io :: #type (*void) -> *void #c_call; +native_new_io: NativeFn_new_io; +NativeFn_io_failed :: #type (*void) -> s32 #c_call; +native_io_failed: NativeFn_io_failed; +NativeFn_release :: #type (*void) #c_call; +native_release: NativeFn_release; +NativeFn_error_release :: #type (*void) #c_call; +native_error_release: NativeFn_error_release; +NativeFn_free :: #type (*void) #c_call; +native_free: NativeFn_free; +NativeFn_get_name :: #type (*void, *s8, **s8, *void) #c_call; +native_get_name: NativeFn_get_name; +NativeFn_array_release :: #type (*void) #c_call; +native_array_release: NativeFn_array_release; +NativeFn_input_memory :: #type (*u8, s64, s32) -> *void #c_call; +native_input_memory: NativeFn_input_memory; +NativeFn_read :: #type (*void, *s8, *void, *void, *s8) -> *void #c_call; +native_read: NativeFn_read; +NativeFn_book :: #type (*void) -> *void #c_call; +native_book: NativeFn_book; +NativeFn_sheet_count :: #type (*void) -> s32 #c_call; +native_sheet_count: NativeFn_sheet_count; +NativeFn_sheet :: #type (*void, s32) -> *void #c_call; +native_sheet: NativeFn_sheet; +NativeFn_positions :: #type (*void, s32) -> *NativeArray #c_call; +native_positions: NativeFn_positions; +NativeFn_cell :: #type (*void, s32, s32) -> *void #c_call; +native_cell: NativeFn_cell; +NativeFn_fetch :: #type (*void, s32, s32) -> *void #c_call; +native_fetch: NativeFn_fetch; +NativeFn_source :: #type (*void) -> *s8 #c_call; +native_source: NativeFn_source; +NativeFn_display :: #type (*void) -> *s8 #c_call; +native_display: NativeFn_display; +NativeFn_value :: #type (*void) -> *void #c_call; +native_value: NativeFn_value; +NativeFn_value_type :: #type (*void) -> s32 #c_call; +native_value_type: NativeFn_value_type; +NativeFn_number :: #type (*void) -> float64 #c_call; +native_number: NativeFn_number; +NativeFn_value_text :: #type (*void) -> *s8 #c_call; +native_value_text: NativeFn_value_text; +NativeFn_recalculate :: #type (*void) #c_call; +native_recalculate: NativeFn_recalculate; +NativeFn_set_text :: #type (*void, *s8, *void) #c_call; +native_set_text: NativeFn_set_text; +NativeFn_remove :: #type (*void, *void, s32, s32) #c_call; +native_remove: NativeFn_remove; +NativeFn_array_cell :: #type (*void) -> s32 #c_call; +native_array_cell: NativeFn_array_cell; +NativeFn_insert_rows :: #type (*void, s32, s32, *void, *void) -> s32 #c_call; +native_insert_rows: NativeFn_insert_rows; +NativeFn_delete_rows :: #type (*void, s32, s32, *void, *void) -> s32 #c_call; +native_delete_rows: NativeFn_delete_rows; +NativeFn_insert_cols :: #type (*void, s32, s32, *void, *void) -> s32 #c_call; +native_insert_cols: NativeFn_insert_cols; +NativeFn_delete_cols :: #type (*void, s32, s32, *void, *void) -> s32 #c_call; +native_delete_cols: NativeFn_delete_cols; +NativeFn_canonical_path :: #type (*s8, *s8) -> *s8 #c_call; +native_canonical_path: NativeFn_canonical_path; +NativeFn_filename_uri :: #type (*s8, *s8, *void) -> *s8 #c_call; +native_filename_uri: NativeFn_filename_uri; +NativeFn_document_uri :: #type (*void) -> *s8 #c_call; +native_document_uri: NativeFn_document_uri; +NativeFn_opener :: #type (*s8) -> *void #c_call; +native_opener: NativeFn_opener; +NativeFn_saver :: #type (*s8) -> *void #c_call; +native_saver: NativeFn_saver; +NativeFn_output_file :: #type (*s8, **void) -> *void #c_call; +native_output_file: NativeFn_output_file; +NativeFn_output_memory :: #type () -> *void #c_call; +native_output_memory: NativeFn_output_memory; +NativeFn_output_size :: #type (*void) -> s64 #c_call; +native_output_size: NativeFn_output_size; +NativeFn_output_bytes :: #type (*void) -> *u8 #c_call; +native_output_bytes: NativeFn_output_bytes; +NativeFn_output_closed :: #type (*void) -> s32 #c_call; +native_output_closed: NativeFn_output_closed; +NativeFn_output_close :: #type (*void) -> s32 #c_call; +native_output_close: NativeFn_output_close; +NativeFn_write :: #type (*void, *void, *void, *void) #c_call; +native_write: NativeFn_write; +NativeFn_current_sheet :: #type (*void) -> *void #c_call; +native_current_sheet: NativeFn_current_sheet; +NativeFn_focus_sheet :: #type (*void, *void) #c_call; +native_focus_sheet: NativeFn_focus_sheet; + +NativeResolve :: (slot: *void, name: string) -> bool { + symbol: *void = NativeSymbol(native_library, CText(name)) + if symbol == null { return false } + MemoryCopy(slot, cast(*void)*symbol, size_of(*void)) + return true +} + +#scope_export +NativeReady :: () -> bool { + if native_tried { return native_ready } + native_tried = true + native_library = NativeOpenLibrary(CText("libspreadsheet.so"), 1) + if native_library == null { return false } + ok: bool = true + ok = ok && NativeResolve(cast(*void)*native_pre_init, "gnm_pre_parse_init") + ok = ok && NativeResolve(cast(*void)*native_initialize, "gnm_init") + ok = ok && NativeResolve(cast(*void)*native_new_context, "gnm_cmd_context_stderr_new") + ok = ok && NativeResolve(cast(*void)*native_plugins_init, "gnm_plugins_init") + ok = ok && NativeResolve(cast(*void)*native_plugins, "go_plugins_get_available_plugins") + ok = ok && NativeResolve(cast(*void)*native_activate, "go_plugin_db_activate_plugin_list") + ok = ok && NativeResolve(cast(*void)*native_error_free, "go_error_info_free") + ok = ok && NativeResolve(cast(*void)*native_new_io, "go_io_context_new") + ok = ok && NativeResolve(cast(*void)*native_io_failed, "go_io_error_occurred") + ok = ok && NativeResolve(cast(*void)*native_release, "g_object_unref") + ok = ok && NativeResolve(cast(*void)*native_free, "g_free") + ok = ok && NativeResolve(cast(*void)*native_get_name, "g_object_get") + ok = ok && NativeResolve(cast(*void)*native_array_release, "g_ptr_array_unref") + ok = ok && NativeResolve(cast(*void)*native_input_memory, "gsf_input_memory_new") + ok = ok && NativeResolve(cast(*void)*native_read, "workbook_view_new_from_input") + ok = ok && NativeResolve(cast(*void)*native_book, "wb_view_get_workbook") + ok = ok && NativeResolve(cast(*void)*native_sheet_count, "workbook_sheet_count") + ok = ok && NativeResolve(cast(*void)*native_sheet, "workbook_sheet_by_index") + ok = ok && NativeResolve(cast(*void)*native_positions, "sheet_cell_positions") + ok = ok && NativeResolve(cast(*void)*native_cell, "sheet_cell_get") + ok = ok && NativeResolve(cast(*void)*native_fetch, "sheet_cell_fetch") + ok = ok && NativeResolve(cast(*void)*native_source, "gnm_cell_get_entered_text") + ok = ok && NativeResolve(cast(*void)*native_display, "gnm_cell_get_rendered_text") + ok = ok && NativeResolve(cast(*void)*native_value, "gnm_cell_get_value") + ok = ok && NativeResolve(cast(*void)*native_value_type, "value_type_of") + ok = ok && NativeResolve(cast(*void)*native_number, "value_get_as_float") + ok = ok && NativeResolve(cast(*void)*native_value_text, "value_get_as_string") + ok = ok && NativeResolve(cast(*void)*native_recalculate, "workbook_recalc_all") + ok = ok && NativeResolve(cast(*void)*native_set_text, "sheet_cell_set_text") + ok = ok && NativeResolve(cast(*void)*native_remove, "sheet_cell_remove") + ok = ok && NativeResolve(cast(*void)*native_array_cell, "gnm_cell_is_nonsingleton_array") + ok = ok && NativeResolve(cast(*void)*native_insert_rows, "sheet_insert_rows") + ok = ok && NativeResolve(cast(*void)*native_delete_rows, "sheet_delete_rows") + ok = ok && NativeResolve(cast(*void)*native_insert_cols, "sheet_insert_cols") + ok = ok && NativeResolve(cast(*void)*native_delete_cols, "sheet_delete_cols") + ok = ok && NativeResolve(cast(*void)*native_saver, "go_file_saver_for_id") + ok = ok && NativeResolve(cast(*void)*native_output_file, "gsf_output_stdio_new") + ok = ok && NativeResolve(cast(*void)*native_output_memory, "gsf_output_memory_new") + ok = ok && NativeResolve(cast(*void)*native_output_size, "gsf_output_size") + ok = ok && NativeResolve(cast(*void)*native_output_bytes, "gsf_output_memory_get_bytes") + ok = ok && NativeResolve(cast(*void)*native_output_closed, "gsf_output_is_closed") + ok = ok && NativeResolve(cast(*void)*native_output_close, "gsf_output_close") + ok = ok && NativeResolve(cast(*void)*native_write, "workbook_view_save_to_output") + ok = ok && NativeResolve(cast(*void)*native_current_sheet, "wb_view_cur_sheet") + ok = ok && NativeResolve(cast(*void)*native_focus_sheet, "wb_view_sheet_focus") + ok = ok && NativeResolve(cast(*void)*native_error_release, "g_error_free") + ok = ok && NativeResolve(cast(*void)*native_opener, "go_file_opener_for_id") + ok = ok && NativeResolve(cast(*void)*native_canonical_path, "g_canonicalize_filename") + ok = ok && NativeResolve(cast(*void)*native_filename_uri, "g_filename_to_uri") + ok = ok && NativeResolve(cast(*void)*native_document_uri, "go_doc_get_uri") + if !ok { return false } + argv: [2]*s8 + argv[0] = CText("workbook") + unused native_pre_init(1, *argv[0]) + native_initialize() + native_context = native_new_context() + native_plugins_init(native_context) + error: *void + native_activate(native_plugins(), *error) + // Optional plugin activation failures do not disable the core reader. + if error != null { native_error_free(error) } + native_ready = true + return true +} + +NativeRead :: (bytes: *u8, count: s64, uri: *s8 = null) -> *void { + if !NativeReady() { return null } + input: *void = native_input_memory(bytes, count, 0) + if input == null { return null } + io: *void = native_new_io(native_context) + opener: *void = native_opener(CText("Gnumeric_XmlIO:sax")) + view: *void + if opener != null { view = native_read(input, uri, opener, io, null) } + failed: bool = native_io_failed(io) != 0 + native_release(io) + native_release(input) + if failed && view != null { native_release(view); view = null } + return view +} + +// Supply the source URI so Gnumeric can resolve relative workbook links. +NativeReadDocument :: (bytes: *u8, count: s64, path: *s8) -> *void { + if !NativeReady() { return null } + absolute: *s8 = native_canonical_path(path, null) + if absolute == null { return null } + uri: *s8 = native_filename_uri(absolute, null, null) + native_free(cast(*void)absolute) + if uri == null { return null } + view: *void = NativeRead(bytes, count, uri) + native_free(cast(*void)uri) + return view +} + +NativeClose :: (view: *void) { if view != null { native_release(view) } } + +NativeWriteOutput :: (view: *void, output: *void, format: *s8) -> bool { + saver: *void = native_saver(format) + if saver == null { return false } + io: *void = native_new_io(native_context) + native_write(view, saver, output, io) + ok: bool = native_io_failed(io) == 0 + if native_output_closed(output) == 0 { + if native_output_close(output) == 0 { ok = false } + } + native_release(io) + return ok +} + +NativeSave :: (view: *void, path: *s8, csv: bool) -> s32 { + error: *void + // CSV is also written to pipes such as /dev/stdout. The native file + // output requires a seekable file; its memory output has no such limit. + output: *void = ifx csv then native_output_memory() else native_output_file(path, *error) + if output == null { + if error != null { native_error_release(error) } + return 0 + } + previous: *void = native_current_sheet(view) + if csv { native_focus_sheet(view, native_sheet(native_book(view), 0)) } + ok: bool = NativeWriteOutput(view, output, + ifx csv then CText("Gnumeric_stf:stf_csv") else CText("Gnumeric_XmlIO:sax")) + if csv { + native_focus_sheet(view, previous) + if ok { + count: s64 = native_output_size(output) + bytes: *s8 = cast(*s8)MemoryAllocate(cast(u64)count + 1) + if bytes == null { ok = false } + else { + MemoryCopy(cast(*void)bytes, cast(*void)native_output_bytes(output), cast(u64)count) + bytes[count] = 0 + ok = WriteFileText(path, bytes) + MemoryFree(cast(*void)bytes) + } + } + } + native_release(output) + return ifx ok then 1 else 0 +} + +NativeClone :: (view: *void) -> *void { + output: *void = native_output_memory() + if output == null { return null } + copy: *void + if NativeWriteOutput(view, output, CText("Gnumeric_XmlIO:sax")) { + copy = NativeRead(native_output_bytes(output), native_output_size(output), native_document_uri(native_book(view))) + } + native_release(output) + return copy +} + +NativeRefresh :: (wb: *Workbook) -> s32 { + // All model text is owned by Workbook; native pointers never outlive a + // call. Rebuilding also picks up dependencies changed by an edit. + for i: 0..wb.sheet_count - 1 { SheetFree(*wb.sheets[i]) } + wb.sheet_count = 0 + book: *void = native_book(wb.native) + native_recalculate(book) + count: s32 = native_sheet_count(book) + index: s32 = 0 + while index < count { + source: *void = native_sheet(book, index) + name: *s8 + native_get_name(source, CText("name"), *name, null) + sheet: *Sheet = WorkbookAddSheet(wb, name) + native_free(cast(*void)name) + if sheet == null { return 0 } + positions: *NativeArray = native_positions(source, 0) + if positions != null { + at: u32 = 0 + while at < positions.count { + position: *NativePosition = cast(*NativePosition)positions.data[at] + node: *void = native_cell(source, position.col, position.row) + cell: *Cell = CellObtain(sheet, position.row, position.col) + if cell != null && node != null { + cell.text = native_source(node) + value: *void = native_value(node) + kind: s32 = native_value_type(value) + cell.kind = ifx cell.text != null && cell.text[0] == 61 then CELL_FORMULA else CELL_LITERAL + cell.computed = 1 + if kind == 20 || kind == 40 { + cell.cached_kind = ifx kind == 20 then VAL_BOOL else VAL_FLOAT + cell.cached_number = native_number(value) + } else if kind == 50 { + cell.cached_kind = VAL_ERROR + message: *s8 = native_value_text(value) + cell.cached_err = ErrFromText(message) + native_free(cast(*void)message) + } else if kind == 60 { + cell.cached_kind = VAL_STRING + cell.cached_text = native_value_text(value) + } + } + at += 1 + } + native_array_release(cast(*void)positions) + } + SheetExtent(sheet) + index += 1 + } + return 1 +} + +NativeSet :: (wb: *Workbook, index: s32, row: s32, col: s32, text: *s8) -> s32 { + sheet: *void = native_sheet(native_book(wb.native), index) + if sheet == null { return 0 } + cell: *void = native_cell(sheet, col, row) + // Match Gnumeric: an array cannot be changed one constituent cell at a time. + if cell != null && native_array_cell(cell) != 0 { return 0 } + if text == null || text[0] == 0 { + if cell != null { native_remove(sheet, cell, 0, 1) } + } else { + cell = native_fetch(sheet, col, row) + if cell == null { return 0 } + native_set_text(cell, text, null) + } + return NativeRefresh(wb) +} + +NativeShift :: (wb: *Workbook, index: s32, at: s32, rows: bool, insert: bool) -> s32 { + sheet: *void = native_sheet(native_book(wb.native), index) + result: s32 + if rows { + if insert { result = native_insert_rows(sheet, at, 1, null, native_context) } + else { result = native_delete_rows(sheet, at, 1, null, native_context) } + } else { + if insert { result = native_insert_cols(sheet, at, 1, null, native_context) } + else { result = native_delete_cols(sheet, at, 1, null, native_context) } + } + if result != 0 { return 0 } + return NativeRefresh(wb) +} + +NativeDisplay :: (wb: *Workbook, index: s32, row: s32, col: s32, out: *s8, cap: s32) { + out[0] = 0 + sheet: *void = native_sheet(native_book(wb.native), index) + cell: *void = native_cell(sheet, col, row) + if cell == null { return } + text: *s8 = native_display(cell) + if text != null { + FormatText(out, cast(u64)cap, CText("%s"), text) + native_free(cast(*void)text) + } +} diff --git a/tests/desktop_test.zi b/tests/desktop_test.zi index faf6609..aa7cbae 100644 --- a/tests/desktop_test.zi +++ b/tests/desktop_test.zi @@ -266,15 +266,20 @@ StartApp :: (directory: string) { LaunchApp(directory, directory) } -LaunchApp :: (directory: string, data: string) { +LaunchApp :: (directory: string, data: string, document: string = "") { SetText(data_directory[:], directory) SetText(saved_path[:], data) AppendText(saved_path[:], "/workbook.gnumeric") SetText(log_path[:], directory) AppendText(log_path[:], "/app.log") UnsetEnvironment("KRYON_CAPTURE_PATH") - command: [1]string = .{DesktopAppPath()} - app_pid = Spawn(command[:], TextUntilNul(log_path[:])) + command: [2]string = .{DesktopAppPath(), document} + count: s32 = 1 + if document.count > 0 { + count = 2 + SetText(saved_path[:], document) + } + app_pid = Spawn(command[0:count], TextUntilNul(log_path[:])) Check(app_pid > 0, "the app could not be started") cleanup_pid = app_pid FindWindow() @@ -582,8 +587,10 @@ DriveAutosave :: (directory: string) -> s32 { ExpectSavedSheetCell :: (sheet: s32, row: s32, column: s32, expected: string, message: string) { saved: *Engine.Workbook = Engine.WorkbookNew() - Check(Engine.WorkbookLoadFile(saved, cast(*s8)*saved_path[0]) != 0, - "cannot read the saved workbook") + if Engine.WorkbookLoadFile(saved, cast(*s8)*saved_path[0]) == 0 { + ShowLog() + Fail("cannot read the saved workbook") + } source: *s8 = Engine.WorkbookCellText(saved, sheet, row, column) actual: string = "" if source != null { actual = TextFromCString(cast(*u8)source) } @@ -599,14 +606,7 @@ ExpectSavedSheetCell :: (sheet: s32, row: s32, column: s32, expected: string, me } ExpectSavedCell :: (row: s32, column: s32, expected: string) { - saved: *Engine.Workbook = Engine.WorkbookNew() - Check(Engine.WorkbookLoadFile(saved, cast(*s8)*saved_path[0]) != 0, - "cannot read the menu test's saved workbook") - source: *s8 = Engine.WorkbookCellText(saved, 0, row, column) - actual: string = "" - if source != null { actual = TextFromCString(cast(*u8)source) } - Check(actual == expected, "the cell menu changed the wrong cell") - Engine.WorkbookFree(saved) + ExpectSavedSheetCell(0, row, column, expected, "saved cell differs") } HeaderWorkbook :: #string END @@ -614,11 +614,11 @@ HeaderWorkbook :: #string END END; RowMenuWorkbook :: #string END -Rows1222=B2*2212 +RowsRows1222=B2*2212 END; LargeHeaderWorkbook :: #string END -Large18899 +LargeLarge18899 END; ReadOwnedWindowScreenshot :: (path: string) { @@ -649,10 +649,10 @@ DriveHeaders :: (directory: string) -> s32 { Check(CsvCellText(0,0,1)=="" && CsvCellText(0,1,1)=="" && CsvCellText(0,20,1)=="","delete clears the entire column") Check(CsvCellText(0,0,0)=="11" && CsvCellText(0,20,2)=="212","column delete preserves neighboring columns") Press(GridLeft-30,GridTop+14); Key("Delete"); Save() - result=Run(evaluate[:],bytes[:]); Check(result.code==0 && ParseCsv(0,TextView(bytes[:result.length])),"cannot read cleared row") - // CSV export begins at the first nonempty row, now row 2. - Check(CsvCellText(0,0,0)=="" && CsvCellText(0,0,2)=="22","row number selects the whole row") - Check(CsvCellText(0,19,2)=="212","row delete preserves other rows") + // Native CSV trims leading empty rows and columns. Check the saved + // coordinates directly so export bounds do not change this selection test. + ExpectSavedCell(0,0,""); ExpectSavedCell(0,2,"") + ExpectSavedCell(1,2,"22"); ExpectSavedCell(20,2,"212") Check(StopApp()==0,"header test app exits cleanly") } @@ -763,7 +763,8 @@ DriveFormulas :: (directory: string) -> s32 { Check(HasTint(GridLeft + ColumnWidth - 2, GridTop + RowHeight + 2, 6, RowHeight - 4, false), "the formula's second reference is not outlined in its color") Key("Return") - ExpectSavedCell(4, 0, "=SUM(A1:A3)+B2") + // Gnumeric serializes function names in their canonical lowercase. + ExpectSavedCell(4, 0, "=sum(A1:A3)+B2") Say("formulas: clicks and drags write references, and a new click replaces the last") // Another sheet's cell gets that sheet's name; Enter returns to the edited sheet. @@ -919,11 +920,13 @@ DriveUndo :: (directory: string) -> s32 { TypeText("+10") ExpectSavedSheetCell(0, 2, 0, "=A2*2+10", "typing in a formula is saved") Key("ctrl+z") - ExpectSavedSheetCell(0, 2, 0, "=A2*2+", "Ctrl+Z in an edit takes back the last word") + // Incomplete formulas are literal strings; Gnumeric exposes the leading + // apostrophe that makes them safe to edit without parsing as a formula. + ExpectSavedSheetCell(0, 2, 0, "'=A2*2+", "Ctrl+Z in an edit takes back the last word") Key("ctrl+z") ExpectSavedSheetCell(0, 2, 0, "=A2*2", "Ctrl+Z in an edit takes back the word before") Key("ctrl+y") - ExpectSavedSheetCell(0, 2, 0, "=A2*2+", "Ctrl+Y in an edit puts a word back") + ExpectSavedSheetCell(0, 2, 0, "'=A2*2+", "Ctrl+Y in an edit puts a word back") TypeText("7") Key("Return") ExpectSavedSheetCell(0, 2, 0, "=A2*2+7", "the edit keeps typing after undo") @@ -970,7 +973,7 @@ DriveUndo :: (directory: string) -> s32 { Key("ctrl+z") ExpectSavedSheetCell(0, 5, 0, "=A1", "Ctrl+Z in a formula brings back the reference picked before") Key("ctrl+z") - ExpectSavedSheetCell(0, 5, 0, "=", "Ctrl+Z in a formula takes back the first pick") + ExpectSavedSheetCell(0, 5, 0, "'=", "Ctrl+Z in a formula takes back the first pick") Key("Escape") ExpectSavedSheetCell(0, 5, 0, "", "Escape after undo leaves the cell as it was") @@ -1114,6 +1117,43 @@ CheckFrame :: (work: string) { Say("frame: layout, selection, and cell text rendered") } +// An explicit document must receive keyboard edits and autosaves itself, +// even when a profile directory is set. A broken import must stay untouched. +DriveDocument :: (directory: string) -> s32 { + Check(Environment(PrivateMarker) == "1", "document test needs a private display") + SetEnvironment("WORKBOOK_DIR", directory) + document: [4096]u8 + SetText(document[:], directory) + AppendText(document[:], "/Time Sheet.gnumeric") + source: [32768]u8 + count: s32 = ReadWholeFile("tests/document.gnumeric", source[:]) + Check(count > 0, "cannot read synthetic Gnumeric fixture") + Check(WriteWholeFile(TextUntilNul(document[:]), TextView(source[0:count])), "cannot write document fixture") + LaunchApp(directory, directory, TextUntilNul(document[:])) + ClickCell(1, 4) + TypeText("keyboard works") + Key("Return") + Save() + ExpectSavedSheetCell(0, 1, 4, "keyboard works", "typing edits the opened document") + ExpectSavedSheetCell(0, 2, 3, "=(C3-B3)*24", "saving retains shared formulas") + Check(StopApp() == 0, "document app did not exit cleanly") + SetText(document[:], directory) + AppendText(document[:], "/broken.gnumeric") + broken: string = " s32 { AppendText(undo[:], "/undo") Check(MakeDirectory(TextUntilNul(undo[:])), "cannot create the undo directory") RunSession(self, "--drive-undo", TextUntilNul(undo[:])) + document: [4096]u8 + SetText(document[:], work) + AppendText(document[:], "/document") + Check(MakeDirectory(TextUntilNul(document[:])), "cannot create document test directory") + RunSession(self, "--drive-document", TextUntilNul(document[:])) } headers: [4096]u8; SetText(headers[:],work); AppendText(headers[:],"/headers") Check(MakeDirectory(TextUntilNul(headers[:])),"cannot create header test directory") @@ -1241,6 +1286,9 @@ RunAll :: (self: string, menus_only: bool, headers_only: bool = false) -> s32 { #program_export main :: (argc: s32, argv: **s8) -> s32 { + if argc == 3 && TextFromCString(cast(*u8)argv[1]) == "--drive-document" { + return DriveDocument(TextFromCString(cast(*u8)argv[2])) + } if argc == 3 && TextFromCString(cast(*u8)argv[1]) == "--drive-headers" { return DriveHeaders(TextFromCString(cast(*u8)argv[2])) } if argc == 3 && TextFromCString(cast(*u8)argv[1]) == "--drive" { return Drive(TextFromCString(cast(*u8)argv[2])) diff --git a/tests/document.gnumeric b/tests/document.gnumeric new file mode 100644 index 0000000..69f7ba7 --- /dev/null +++ b/tests/document.gnumeric @@ -0,0 +1,41 @@ + + + + TimeNotes + + + Time300100000 + Duration$D$2+$D$3A1 + + Sans + + + + + + Date + 46027 + 09:15 + 10:15 + =(C2-B2)*24 + 46028 + 09:15 + 10:45 + + =SUM(D2:D3) + =Duration + =TRANSPOSE({1,2}) + 42 + + A6:B6 + + Notes11 + + =literal & text + 000123 + TRUE + Überprüfung + + + + diff --git a/tests/gnumeric_test.zi b/tests/gnumeric_test.zi new file mode 100644 index 0000000..baed773 --- /dev/null +++ b/tests/gnumeric_test.zi @@ -0,0 +1,112 @@ +// Imported documents use Gnumeric for interpretation and round trips. The +// fixture is synthetic; no owner workbooks belong in the repository. +#load "test_support.zi"; +Engine :: #import "engine"; + +ExpectSource :: (book: *Engine.Workbook, sheet: s32, row: s32, col: s32, text: string) { + Check(Engine.TextCompareLiteral(Engine.WorkbookCellText(book, sheet, row, col), text) == 0, + "imported cell source differs") +} +ExpectDisplay :: (book: *Engine.Workbook, sheet: s32, row: s32, col: s32, text: string) { + output: [256]s8 + Engine.WorkbookCellDisplay(book, sheet, row, col, *output[0], 256) + if Engine.TextCompareLiteral(*output[0], text) != 0 { + SayWith("Expected: ", text) + SayWith("Actual: ", TextFromCString(cast(*u8)*output[0])) + Fail("Gnumeric display differs") + } +} + +#program_export +main :: () -> s32 { + book: *Engine.Workbook = Engine.WorkbookNew() + Check(Engine.WorkbookLoadFile(book, Engine.CText("tests/document.gnumeric")) != 0, "cannot import Gnumeric document") + Check(book.native != null && Engine.WorkbookSheetCount(book) == 2, "native document not retained") + ExpectSource(book, 0, 2, 3, "=(C3-B3)*24") + ExpectSource(book, 0, 100000, 300, "42") + ExpectDisplay(book, 0, 1, 0, "2026-01-05") + ExpectDisplay(book, 0, 2, 3, "1.50") + ExpectDisplay(book, 0, 3, 3, "2.50") + ExpectDisplay(book, 0, 4, 3, "2.50") + ExpectDisplay(book, 1, 0, 0, "=literal & text") + ExpectDisplay(book, 1, 0, 1, "000123") + ExpectDisplay(book, 1, 1, 0, "TRUE") + ExpectDisplay(book, 0, 7, 0, "1") + ExpectDisplay(book, 0, 8, 0, "2") + Check(Engine.WorkbookSetCell(book, 0, 8, 0, Engine.CText("99")) == 0, "part of an array was overwritten") + copy: *Engine.Workbook = Engine.WorkbookClone(book) + Check(copy != null, "native undo snapshot failed") + Check(Engine.WorkbookSetCell(book, 0, 2, 2, Engine.CText("11:15")) != 0, "native edit failed") + ExpectDisplay(book, 0, 2, 3, "2.00") + ExpectDisplay(book, 0, 4, 3, "3.00") + ExpectDisplay(copy, 0, 2, 3, "1.50") + Check(Engine.WorkbookInsertRow(book, 0, 0) != 0, "native row insertion failed") + ExpectDisplay(book, 0, 2, 0, "2026-01-05") + ExpectDisplay(book, 0, 5, 3, "3.00") + Check(Engine.WorkbookDeleteRow(book, 0, 0) != 0, "native row deletion failed") + ExpectDisplay(book, 0, 1, 0, "2026-01-05") + template: [4096]u8 + SetText(template[:], "/tmp/workbook-gnumeric-XXXXXX") + work: string = MakeTemporaryDirectory(template[:]) + Check(work.count > 0, "cannot create test output directory") + SetText(cleanup_directory[:], work) + path: [4096]u8 + SetText(path[:], work) + AppendText(path[:], "/saved.gnumeric") + Check(Engine.WorkbookWriteGnumeric(book, cast(*s8)*path[0]) != 0, "native save failed") + saved: *Engine.Workbook = Engine.WorkbookNew() + Check(Engine.WorkbookLoadFile(saved, cast(*s8)*path[0]) != 0, "native round trip failed") + ExpectDisplay(saved, 0, 1, 0, "2026-01-05") + ExpectDisplay(saved, 0, 2, 3, "2.00") + ExpectDisplay(saved, 0, 4, 3, "3.00") + ExpectSource(saved, 0, 100000, 300, "42") + ExpectDisplay(saved, 1, 0, 1, "000123") + ExpectDisplay(saved, 0, 8, 0, "2") + // A native document is not a NUL-terminated UTF-8 string. UTF-16 XML + // contains embedded zero bytes and must reach Gnumeric intact. + xml: string = "Wide42" + wide: [4096]u8 + wide[0] = 255; wide[1] = 254 + for at: 0..cast(s32)xml.count - 1 { wide[2 + at * 2] = xml[at]; wide[3 + at * 2] = 0 } + SetText(path[:], work); AppendText(path[:], "/encoded.gnumeric") + Check(WriteWholeFile(TextUntilNul(path[:]), TextView(wide[0:2 + cast(s32)xml.count * 2])), "cannot write UTF-16 fixture") + encoded: *Engine.Workbook = Engine.WorkbookNew() + Check(Engine.WorkbookLoadFile(encoded, cast(*s8)*path[0]) != 0, "UTF-16 document was truncated") + ExpectDisplay(encoded, 0, 0, 0, "42") + Engine.WorkbookFree(encoded) + // The independent writer also declares enough grid space when a new + // workbook reaches beyond the original 256-column/65,536-row default. + fresh: *Engine.Workbook = Engine.WorkbookNew() + Engine.WorkbookAddSheet(fresh, Engine.CText("Large")) + Check(Engine.WorkbookSetCell(fresh, 0, 100000, 300, Engine.CText("42")) != 0, "cannot create a large-coordinate cell") + SetText(path[:], work); AppendText(path[:], "/large.gnumeric") + Check(Engine.WorkbookWriteGnumeric(fresh, cast(*s8)*path[0]) != 0, "cannot write large dimensions") + imported: *Engine.Workbook = Engine.WorkbookNew() + Check(Engine.WorkbookLoadFile(imported, cast(*s8)*path[0]) != 0, "cannot re-read large dimensions") + ExpectSource(imported, 0, 100000, 300, "42") + Engine.WorkbookFree(imported) + Engine.WorkbookFree(fresh) + // CSV's first field can begin with '<'; it must not be mistaken for XML. + SetText(path[:], work); AppendText(path[:], "/literal.csv") + Check(WriteWholeFile(TextUntilNul(path[:]), "