Open dropped documents and use their filenames as window titles

This commit is contained in:
waozi committed 2026-10-20 10:42:55 -03:00
1 parent da4fdf02bb
commit d5559b7615
7 files changed
+296 -47

No files matched your search

+4 -2
View File
@@ -33,7 +33,7 @@ $(APP): $(SOURCES)
define program
@$(ZIRAN) build --project --target=c --entry $(1):main -o $(3)-c $(2)
@$(CC) $(NATIVE_FLAGS) -I$(shell $(ZIRAN) pkg path ziran)/include -I$(3)-c \
$(3)-c/*.c -lm -o $(3)
$(3)-c/*.c -lm $(if $(filter desktop_test,$(1)),-lX11) -o $(3)
endef
# The engine driver, and the test programs, which are Ziran too.
@@ -93,6 +93,8 @@ install: build
@ln -sf workbook $(PREFIX)/bin/geld
@sed 's|^Exec=geld$$|Exec=$(PREFIX)/bin/geld|' packaging/geld.desktop \
> $(PREFIX)/share/applications/geld.desktop
@if command -v update-desktop-database >/dev/null 2>&1; then \
update-desktop-database $(PREFIX)/share/applications; fi
# A Debian package of the same files.
DEB_NAME := workbook_$(VERSION)_amd64
@@ -107,7 +109,7 @@ Maintainer: Waozi <[email protected]>
Installed-Size: INSTALLED_SIZE
Depends: libc6, libsdl2-2.0-0, libcairo2, gnumeric
Homepage: https://github.com/kryonlabs/workbook
Description: Spreadsheet editor compatible with Gnumeric
Description: Spreadsheet editor
Workbook is a native spreadsheet editor written in Ziran with Kryon. It reads
and writes Gnumeric and CSV files and evaluates Gnumeric formulas; the cell
command does the same without a window. Installed profile commands such as
+12 -32
View File
@@ -1,42 +1,22 @@
# workbook
Native spreadsheet editor written in [Ziran](https://github.com/ziranlang/ziran)
with [Kryon](https://github.com/kryonlabs/kryon), compatible with Gnumeric file
formats and expressions. Everything in the repository is Ziran (`.zi`) apart
from the Makefile and configuration. `src/app.zi` is the desktop application and
`src/engine.zi` is the spreadsheet engine (grid model, formula evaluator,
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.
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 editor can open a file directly:
with [Kryon](https://github.com/kryonlabs/kryon). Open a document from your file
manager, drop it onto Workbook, or pass its path 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.
The window title shows the document's filename. Edits save back to that file;
when you drop another document, Workbook saves the current edit before opening
it. Launching without a file uses the profile described below.
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`.
Everything in the repository is Ziran (`.zi`) apart from the Makefile and
configuration. `src/app.zi` is the desktop application, `src/engine.zi` is the
spreadsheet engine, and `src/cell.zi` is the headless driver. Imported documents
use the installed `gnumeric` library for loading, calculation and saving.
New workbooks and CSV use the independent Ziran engine. Document format,
dependencies and rendering limitations are covered in
[format notes](docs/GNUMERIC_PARITY.md).
## build & run
+2 -2
View File
@@ -1,8 +1,8 @@
[Desktop Entry]
Type=Application
Name=Workbook
Comment=Spreadsheet editor compatible with Gnumeric
Comment=Spreadsheet editor
Exec=workbook %f
Terminal=false
Categories=Office;
Categories=Office;Spreadsheet;
MimeType=application/x-gnumeric;
+72 -7
View File
@@ -2,6 +2,7 @@
// cell grid of the spreadsheet engine.
using UI :: #import "Widgets";
Engine :: #import "engine";
Desktop :: #import "kryon/Desktop";
Json :: #import "json_scan";
SystemStyle :: #import "kss/SystemStyle";
SystemThemeLinux :: #import "SystemThemeLinux";
@@ -185,8 +186,8 @@ theme_name: [128]u8;
theme_frames: s32 = 0;
theme_installed: bool = false;
data_path: [1024]u8;
data_directory: [1024]u8;
data_path: [4096]u8;
data_directory: [4096]u8;
status: [256]u8;
#scope_export
@@ -197,6 +198,11 @@ Frame :: (session: Session, viewport: Rectangle) -> s32 {
if workbook == null {
LoadWorkbook()
SelectCell(0, 0)
UpdateDocumentTitle()
}
dropped: [4096]u8
while Desktop.DesktopTakeDroppedFile(dropped[:]) {
OpenDocument(TextUntilNul(dropped[:]))
}
key: s32 = KeyboardTake(session)
control: bool = (KeyboardModifiers(session) & KeyModifierControl) != 0
@@ -333,6 +339,60 @@ LoadWorkbook :: () {
dirty = false
}
UpdateDocumentTitle :: () {
unused Desktop.DesktopSetTitle(FileName(TextUntilNul(data_path[:])))
}
// Finish and save the current document before replacing it. A failed import
// leaves the current workbook, its path, selection, and undo history intact.
OpenDocument :: (path: string) {
if !DocumentPath(path) { return }
if edit_focused { CommitCell() }
if dirty && !load_failed {
SaveWorkbook(false)
if dirty { return }
}
next: *Engine.Workbook = Engine.WorkbookNew()
if Engine.WorkbookLoadFile(next, cast(*s8)CPath(path)) == 0 {
Engine.WorkbookFree(next)
SetText(status[:], "Could not open ")
AppendText(status[:], FileName(path))
return
}
if edit_focused { EndEdit() }
FinishEditStep()
while undo_count > 0 {
undo_count -= 1
Engine.WorkbookFree(undo_steps[undo_count].book)
}
while redo_count > 0 {
redo_count -= 1
Engine.WorkbookFree(redo_steps[redo_count].book)
}
Engine.WorkbookFree(workbook)
workbook = next
SetText(data_path[:], path)
data_directory[0] = 0
base := cast(s32)path.count - cast(s32)FileName(path).count
if base > 0 { SetText(data_directory[:], path[0:base]) }
sheet_index = 0
edit_sheet = 0
scroll_row = 0
scroll_column = 0
grid_menu_open = false
drag_mode = DragNone
edit_refocus = false
edit_claim = false
copied_sheet = -1
copied_length = 0
dirty = false
load_failed = false
save_retry_at = 0
status[0] = 0
SelectCell(0, 0)
UpdateDocumentTitle()
}
MonotonicMilliseconds :: () -> s64 {
now: TimeSpec
ClockTime(1, *now)
@@ -342,7 +402,7 @@ MonotonicMilliseconds :: () -> s64 {
// Creates every missing parent, including a fresh XDG data directory.
EnsureDataDirectory :: () -> bool {
path: string = TextUntilNul(data_directory[:])
prefix: [1024]u8
prefix: [4096]u8
at: s32 = 1
while at <= cast(s32)path.count {
if at == cast(s32)path.count || path[at] == #char "/" {
@@ -368,7 +428,7 @@ SaveWorkbook :: (finish_edit: bool) {
saved: bool = false
// Replace the previous file only after its replacement has been written
// and synced. A failed write leaves the last saved workbook intact.
temporary: [1100]u8
temporary: [4160]u8
SetText(temporary[:], path)
AppendText(temporary[:], ".tmp-XXXXXX")
if EnsureDataDirectory() {
@@ -1852,13 +1912,18 @@ OpenFileArgument :: (out: []u8) -> bool {
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 }
if !DocumentPath(name) { return false }
if name.count >= out.count { return false }
SetText(out, name)
return true
}
DocumentPath :: (name: string) -> bool {
if name.count < 9 || name.count >= 4096 { return false }
suffix: string = name[cast(s32)name.count - 9:cast(s32)name.count]
return Engine.TextCompareFoldLiteral(cast(*s8)CPath(suffix), ".gnumeric") == 0
}
// 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 {
+59 -3
View File
@@ -8,6 +8,7 @@
#load "test_support.zi";
#load "csv_table.zi";
#load "screenshot.zi";
#load "file_drop.zi";
RawCurrentDirectory :: (output: *u8, size: u64) -> *u8 #foreign libc "getcwd";
RawChangeDirectory :: (path: *u8) -> s32 #foreign libc "chdir";
@@ -15,7 +16,6 @@ RawChangeDirectory :: (path: *u8) -> s32 #foreign libc "chdir";
AppPath :: "build/workbook-desktop";
CellPath :: "build/cell";
FixturePath :: "tests/fixtures/operators.gnumeric";
WindowName :: "Kryon Ziran";
PrivateMarker :: "WORKBOOK_TEST_PRIVATE_DISPLAY";
// Grid geometry from src/app.zi, in window pixels.
@@ -291,7 +291,8 @@ FindWindow :: () {
attempts: s32 = 0
while attempts < 100 {
output: [1024]u8
search: [4]string = .{"xdotool", "search", "--name", WindowName}
pid: [32]u8
search: [5]string = .{"xdotool", "search", "--onlyvisible", "--pid", NumberText(pid[:], app_pid)}
result: CaptureResult = Run(search[:], output[:])
if result.code == 0 && result.length > 0 {
end: s32 = 0
@@ -1117,6 +1118,20 @@ CheckFrame :: (work: string) {
Say("frame: layout, selection, and cell text rendered")
}
ExpectTitle :: (expected: string) {
output: [4096]u8
command: [3]string = .{"xdotool", "getwindowname", WindowId()}
result := Run(command[:], output[:])
title: [4096]u8
SetText(title[:], expected)
AppendText(title[:], "\n")
if result.code != 0 || TextView(output[0:result.length]) != TextUntilNul(title[:]) {
SayWith("expected title: ", expected)
SayWith("actual title: ", TextView(output[0:result.length]))
Fail("the window title does not match the document")
}
}
// 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 {
@@ -1130,12 +1145,46 @@ DriveDocument :: (directory: string) -> s32 {
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[:]))
ExpectTitle("Time Sheet.gnumeric")
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")
// A real Xdnd URI-list drop opens the next document and finishes the
// current edit without Enter. Spaces, punctuation and UTF-8 are decoded
// by the desktop host, just as for a file-manager drag.
ClickCell(1, 4)
TypeText("saved before drop")
dropped: [4096]u8
SetText(dropped[:], directory)
AppendText(dropped[:], "/Budget #1 % café.gnumeric")
Check(WriteWholeFile(TextUntilNul(dropped[:]), TextView(source[0:count])), "cannot write drop fixture")
DropDocument(TextUntilNul(dropped[:]))
ExpectTitle("Budget #1 % café.gnumeric")
ExpectSavedSheetCell(0, 1, 4, "saved before drop", "drop preserves the preceding edit")
SetText(saved_path[:], TextUntilNul(dropped[:]))
// Undo from the previous document must never be applied to this one.
Key("ctrl+z")
ClickCell(1, 4)
TypeText("edited dropped document")
Key("Return")
ExpectSavedSheetCell(0, 1, 4, "edited dropped document", "the dropped document receives keyboard edits")
// A failed drop retains the current document and its undo history.
invalid: [4096]u8
SetText(invalid[:], directory)
AppendText(invalid[:], "/invalid drop.gnumeric")
Check(WriteWholeFile(TextUntilNul(invalid[:]), "<gnm:Workbook"), "cannot write invalid drop fixture")
DropDocument(TextUntilNul(invalid[:]))
ExpectTitle("Budget #1 % café.gnumeric")
Key("ctrl+z")
ExpectSavedSheetCell(0, 1, 4, "", "a failed drop preserves undo for the open document")
ClickCell(1, 4)
TypeText("still editable")
Key("Return")
ExpectSavedSheetCell(0, 1, 4, "still editable", "a failed drop keeps editing the current file")
// A valid drop also recovers a window whose original import failed.
Check(StopApp() == 0, "document app did not exit cleanly")
SetText(document[:], directory)
AppendText(document[:], "/broken.gnumeric")
@@ -1146,11 +1195,18 @@ DriveDocument :: (directory: string) -> s32 {
TypeText("must not replace the document")
Key("Return")
Save()
DropDocument(TextUntilNul(dropped[:]))
ExpectTitle("Budget #1 % café.gnumeric")
SetText(saved_path[:], TextUntilNul(dropped[:]))
ClickCell(1, 4)
TypeText("recovered")
Key("Return")
ExpectSavedSheetCell(0, 1, 4, "recovered", "a valid drop recovers a failed initial import")
Check(StopApp() == 0, "failed-import app did not exit cleanly")
count = ReadWholeFile(TextUntilNul(document[:]), source[:])
Check(count == cast(s32)broken.count && TextView(source[0:count]) == broken,
"a failed import was overwritten")
Say("document: file arguments, keyboard input, autosave and failed-import protection passed")
Say("document: file arguments, titles, real file drops, keyboard edits and failed-import protection passed")
return 0
}
+146
View File
@@ -0,0 +1,146 @@
// A file-manager source for the Xdnd protocol. Runs only inside the desktop
// test's private display and targets the child window found by its PID.
x11 :: #system_library "X11";
DropDisplayOpen :: (name: *u8) -> *void #foreign x11 "XOpenDisplay";
DropDisplayClose :: (display: *void) -> s32 #foreign x11 "XCloseDisplay";
DropRoot :: (display: *void) -> u64 #foreign x11 "XDefaultRootWindow";
DropWindowNew :: (display: *void, parent: u64, x: s32, y: s32, width: u32,
height: u32, border: u32, border_pixel: u64, background: u64) -> u64 #foreign x11 "XCreateSimpleWindow";
DropWindowFree :: (display: *void, window: u64) -> s32 #foreign x11 "XDestroyWindow";
DropAtom :: (display: *void, name: *u8, only_existing: s32) -> u64 #foreign x11 "XInternAtom";
DropSelectionOwner :: (display: *void, selection: u64, window: u64, time: u64) -> s32 #foreign x11 "XSetSelectionOwner";
DropSend :: (display: *void, window: u64, propagate: s32, mask: s64, event: *void) -> s32 #foreign x11 "XSendEvent";
DropFlush :: (display: *void) -> s32 #foreign x11 "XFlush";
DropPending :: (display: *void) -> s32 #foreign x11 "XPending";
DropNext :: (display: *void, event: *void) -> s32 #foreign x11 "XNextEvent";
DropProperty :: (display: *void, window: u64, property: u64, kind: u64,
format: s32, mode: s32, data: *u8, length: s32) -> s32 #foreign x11 "XChangeProperty";
DropClient :: struct {
kind: s32
serial: u64
sent: s32
display: *void
window: u64
message: u64
format: s32
data: [5]u64
padding: [96]u8
}
DropRequest :: struct {
kind: s32
serial: u64
sent: s32
display: *void
owner: u64
requestor: u64
selection: u64
target: u64
property: u64
time: u64
}
DropNotify :: struct {
kind: s32
serial: u64
sent: s32
display: *void
requestor: u64
selection: u64
target: u64
property: u64
time: u64
padding: [120]u8
}
DropName :: (display: *void, name: string) -> u64 {
bytes: [128]u8
Check(CopyCString(name, bytes[:]), "drop atom too long")
return DropAtom(display, *bytes[0], 0)
}
DropMessage :: (display: *void, target: u64, source: u64, name: string,
second: u64, third: u64, fourth: u64, fifth: u64) {
event: DropClient
event.kind = 33 // ClientMessage
event.display = display
event.window = target
event.message = DropName(display, name)
event.format = 32
event.data = .{source, second, third, fourth, fifth}
Check(DropSend(display, target, 0, cast(s64)0, cast(*void)*event) != 0, "cannot send drop message")
DropFlush(display)
}
DropDocument :: (path: string) {
Check(Environment(PrivateMarker) == "1", "file drops require the private display")
display := DropDisplayOpen(null)
Check(display != null, "cannot open the private drop display")
defer { DropDisplayClose(display) }
source := DropWindowNew(display, DropRoot(display), 0, 0, 1, 1, 0, cast(u64)0, cast(u64)0)
defer { DropWindowFree(display, source) }
target: u64 = cast(u64)0
for byte: WindowId() { target = target * cast(u64)10 + cast(u64)(byte - 48) }
selection := DropName(display, "XdndSelection")
uri_type := DropName(display, "text/uri-list")
action := DropName(display, "XdndActionCopy")
status_atom := DropName(display, "XdndStatus")
finished_atom := DropName(display, "XdndFinished")
DropSelectionOwner(display, selection, source, cast(u64)0)
uri: [16384]u8
SetText(uri[:], "file://")
hex: string = "0123456789ABCDEF"
for byte: path {
encoded: [3]u8
if (byte >= 65 && byte <= 90) || (byte >= 97 && byte <= 122) ||
(byte >= 48 && byte <= 57) || byte == 47 || byte == 45 || byte == 46 || byte == 95 || byte == 126 {
encoded[0] = byte
AppendText(uri[:], TextView(encoded[0:1]))
} else {
encoded[0] = 37
encoded[1] = hex[cast(s32)byte / 16]
encoded[2] = hex[cast(s32)byte % 16]
AppendText(uri[:], TextView(encoded[:]))
}
}
AppendText(uri[:], "\r\n")
DropMessage(display, target, source, "XdndEnter", cast(u64)0x05000000, uri_type, cast(u64)0, cast(u64)0)
DropMessage(display, target, source, "XdndPosition", cast(u64)0, cast(u64)0, cast(u64)0, action)
dropped: bool = false
served: bool = false
finished: bool = false
for attempt: 0..999 {
while DropPending(display) > 0 {
event: DropClient
DropNext(display, cast(*void)*event)
if event.kind == 33 && event.message == status_atom && !dropped {
Check((event.data[1] & cast(u64)1) != cast(u64)0, "the app refused file drops")
DropMessage(display, target, source, "XdndDrop", cast(u64)0, cast(u64)0, cast(u64)0, cast(u64)0)
dropped = true
}
if event.kind == 30 { // SelectionRequest
request := cast(*DropRequest)*event
Check(request.selection == selection && request.target == uri_type, "unexpected drop selection")
property := request.property
if property == cast(u64)0 { property = request.target }
DropProperty(display, request.requestor, property, uri_type, 8, 0,
*uri[0], cast(s32)TextUntilNul(uri[:]).count)
reply: DropNotify
reply.kind = 31
reply.display = display
reply.requestor = request.requestor
reply.selection = request.selection
reply.target = request.target
reply.property = property
reply.time = request.time
Check(DropSend(display, reply.requestor, 0, cast(s64)0, cast(*void)*reply) != 0, "cannot answer drop selection")
DropFlush(display)
served = true
}
if event.kind == 33 && event.message == finished_atom { finished = true }
}
if finished { break }
SleepMilliseconds(10)
}
Check(dropped && served && finished, "file drop did not complete through the native host")
SleepMilliseconds(500)
}
+1 -1
View File
@@ -33,5 +33,5 @@ backend = "desktop"
[tool.kryon.install]
profile = "desktop"
name = "Workbook"
comment = "Spreadsheet editor compatible with Gnumeric"
comment = "Spreadsheet editor"
categories = "Office;Spreadsheet;"