RediWM is a Wayland compositor written in Zig (OpenGL ES) that includes everything in one process
Editor: keep unsaved tabs as drafts, and let the tab strip shrink and scroll
oxydizer76bda301ef4a
diff --git a/src/editor/AGENTS.md b/src/editor/AGENTS.mdindex d525a92..3e85beb 100644--- a/src/editor/AGENTS.md+++ b/src/editor/AGENTS.md@@ -29,3 +29,37 @@`text.items` reader (segmenter, find, IME, clipboard) would need to learn it.* A selected line break is not in the segment layout, so `paintLine` draws thehighlight out to the margin itself (wrapped mode only, as Pango did).++## Drafts++* **Unsaved text survives closing, crashes and reboots.** `drafts.zig` owns+ the files (`$XDG_STATE_HOME/rediwm/editor-drafts/`: `session.json`, one+ `<name>.txt` per modified tab, `lock`; all 0600 in a 0700 directory, each+ replaced through a synced temporary name, strays swept after every write).+ `app_drafts.zig` decides what and when. A tab is kept when it is modified and+ not an empty untitled one; clean tabs are not restored. A restored tab has+ `doc.saved = null` and the file's `stamp` from before, so saving it still+ trips `FileChanged` if the file moved on.+* **Writes follow `app_drafts.signature`** (tabs, revisions, modified, paths,+ selected tab; not the cursor), debounced 1 s after the last change and at+ most 5 s into continuous typing, on a thread over copied text. No timer runs+ unless a change is unwritten: a tab switch with nothing to keep arms none.+ State that should trigger a write belongs in the signature. A failed write is+ retried after the usual delay, never in a loop.+* **Drafts are for a session that ends some other way.** Closing the window+ or a tab asks to save as usual (Discard deletes the draft). A SIGTERM/SIGHUP/+ SIGINT (they write through the eventfd the writer uses to wake the loop), a+ dying compositor or a crash leaves the drafts, and `deinit` writes last.+ Tabs over `text_limit` (8 MiB; 64 MiB together) are not kept.+* Tests that start the editor need a scratch `XDG_STATE_HOME`, or they restore+ and overwrite the real drafts.++## Tab strip++* Tabs share the strip left of the new-tab button, `tab_max` (176) down to+ `tab_min` (112) wide; beyond that it scrolls by pixels (`tab_scroll`), by+ wheel over the strip. `revealTab` brings the selected tab into view only when+ the selection, the tab count or the width changed, so typing never snaps a+ strip the user scrolled away. Go through `tabX`/`tabAt`/`tabCloseBox`; a tab+ at the edge is partly drawn (the strip is clipped), so hit tests must stay+ inside `tabRight()`. Names are ellipsized; the unsaved dot never is.diff --git a/src/editor/app.zig b/src/editor/app.zigindex 8846efb..0fe2693 100644--- a/src/editor/app.zig+++ b/src/editor/app.zig@@ -23,10 +23,15 @@ const app_paint = @import("app_paint.zig");const app_search = @import("app_search.zig");const app_edit = @import("app_edit.zig");const app_controls = @import("app_controls.zig");+const app_drafts = @import("app_drafts.zig");+const drafts = @import("drafts.zig");const a = std.heap.c_allocator;pub const top: f64 = 40;pub const status_h: f64 = 26;-pub const tab_w: f64 = 176;+/// A tab is this wide while there is room; tabs share the strip down to+/// `tab_min`, and beyond that the strip scrolls.+pub const tab_max: f64 = 176;+pub const tab_min: f64 = 112;const Status = struct {revision: usize = std.math.maxInt(usize),cursor: usize = 0,@@ -48,6 +53,10 @@ pub const Tab = struct {measure: view.Measure = .{},/// The status bar's line and column, recomputed only when the cursor or text moves.status: Status = .{},+ /// The draft file this tab's unsaved text lives in, and the revision of the+ /// text it holds; null while the tab has none (see `drafts.zig`).+ draft_name: ?u64 = null,+ draft_rev: ?usize = null,pub fn deinit(t: *Tab) void {t.doc.deinit();if (t.path) |path| a.free(path);@@ -61,7 +70,9 @@ pub const App = struct {tabs: std.ArrayList(*Tab) = .empty,selected: usize = 0,next_id: usize = 1,- first_tab: usize = 0,+ /// How far the tab strip is scrolled, in pixels.+ tab_scroll: f64 = 0,+ strip_seen: app_controls.Strip = .{},w: i32 = 900,h: i32 = 620,scale: i32 = 1,@@ -113,6 +124,8 @@ pub const App = struct {preedit: std.ArrayList(u8) = .empty,layouts: view.Layouts = .{},rows: std.ArrayList(view.Row) = .empty,+ /// Where unsaved text is kept between sessions; null when it cannot be.+ keeper: ?*drafts.Keeper = null,pub fn init(io: std.Io) !App {var self: App = .{ .io = io };@@ -120,6 +133,7 @@ pub const App = struct {return self;}pub fn deinit(self: *App) void {+ self.deinitDrafts();if (self.operation) |job| job.deinit();for (self.tabs.items) |t| t.deinit();self.tabs.deinit(a);@@ -172,9 +186,7 @@ pub const App = struct {self.title[value.len] = 0;self.title_changed = true;}- const visible: usize = @intFromFloat(@max(1, @floor((self.tabRight() - 2) / tab_w)));- if (self.selected < self.first_tab) self.first_tab = self.selected;- if (self.selected >= self.first_tab + visible) self.first_tab = self.selected - visible + 1;+ self.revealTab();}pub const CaretState = app_paint.CaretState;@@ -191,6 +203,12 @@ pub const App = struct {pub const paintMenu = app_paint.paintMenu;pub const paintButton = app_paint.paintButton;pub const paintIcon = app_controls.paintIcon;+ pub const tabWidth = app_controls.tabWidth;+ pub const tabX = app_controls.tabX;+ pub const tabAt = app_controls.tabAt;+ pub const tabScrollMax = app_controls.tabScrollMax;+ pub const scrollTabs = app_controls.scrollTabs;+ pub const revealTab = app_controls.revealTab;pub const tabCloseBox = app_controls.tabCloseBox;pub const newButtonBox = app_controls.newButtonBox;pub const menuButtonBox = app_controls.menuButtonBox;@@ -214,6 +232,14 @@ pub const App = struct {pub const finishClose = app_files.finishClose;pub const act = app_files.act;+ pub const openDrafts = app_drafts.openDrafts;+ pub const stepDrafts = app_drafts.stepDrafts;+ pub const draftTimeout = app_drafts.draftTimeout;+ pub const draftWake = app_drafts.draftWake;+ pub const drainDrafts = app_drafts.drainDrafts;+ pub const signaled = app_drafts.signaled;+ pub const deinitDrafts = app_drafts.deinitDrafts;+pub const resize = app_view.resize;pub const viewTop = app_view.viewTop;pub const viewHeight = app_view.viewHeight;diff --git a/src/editor/app_controls.zig b/src/editor/app_controls.zigindex 996ce7d..9022d6f 100644--- a/src/editor/app_controls.zig+++ b/src/editor/app_controls.zig@@ -1,4 +1,5 @@//! Shared geometry for the tab controls and their hover feedback.+const std = @import("std");const c = @import("../files/c.zig").api;const ui = @import("ui").cairo;const theme = @import("ui").theme;@@ -8,8 +9,59 @@ const app = @import("app.zig");const App = app.App;const SearchControl = @import("app_search.zig").Control;-pub fn tabCloseBox(_: *const App, index: usize) Rect {- return .{ .x = @as(f64, @floatFromInt(index)) * app.tab_w + app.tab_w - 36, .y = 2, .w = 34, .h = 34 };+/// The strip is the width left of the new-tab button. Tabs share it, none+/// wider than `tab_max` or narrower than `tab_min`; a strip holding more than+/// fit at `tab_min` scrolls by pixels, so the tab cut off at its edge shows+/// that there is more.+pub fn tabWidth(self: *const App) f64 {+ const count: f64 = @floatFromInt(@max(1, self.tabs.items.len));+ return std.math.clamp(self.tabRight() / count, app.tab_min, app.tab_max);+}++/// Where tab `index` starts on screen.+pub fn tabX(self: *const App, index: usize) f64 {+ return @as(f64, @floatFromInt(index)) * self.tabWidth() - self.tab_scroll;+}++/// The tab under an x position of the strip.+pub fn tabAt(self: *const App, x: f64) ?usize {+ if (x < 0 or x >= self.tabRight()) return null;+ const index: usize = @intFromFloat((x + self.tab_scroll) / self.tabWidth());+ return if (index < self.tabs.items.len) index else null;+}++pub fn tabScrollMax(self: *const App) f64 {+ const count: f64 = @floatFromInt(self.tabs.items.len);+ return @max(0, count * self.tabWidth() - self.tabRight());+}++pub fn scrollTabs(self: *App, delta: f64) void {+ const before = self.tab_scroll;+ self.tab_scroll = std.math.clamp(before + delta, 0, self.tabScrollMax());+ if (self.tab_scroll != before) self.dirty = true;+}++/// What decides whether the selected tab needs bringing into view.+pub const Strip = struct { selected: usize = std.math.maxInt(usize), count: usize = 0, right: f64 = 0 };++/// Scrolls the selected tab into view when it, the number of tabs or the+/// width changed, and keeps the scroll in range. Other changes (typing)+/// leave a strip the user scrolled away alone.+pub fn revealTab(self: *App) void {+ const seen: Strip = .{ .selected = self.selected, .count = self.tabs.items.len, .right = self.tabRight() };+ if (!std.meta.eql(seen, self.strip_seen)) {+ self.strip_seen = seen;+ const width = self.tabWidth();+ const left = @as(f64, @floatFromInt(self.selected)) * width;+ if (left < self.tab_scroll) {+ self.tab_scroll = left;+ } else if (left + width > self.tab_scroll + seen.right) self.tab_scroll = left + width - seen.right;+ }+ self.tab_scroll = std.math.clamp(self.tab_scroll, 0, self.tabScrollMax());+}++pub fn tabCloseBox(self: *const App, index: usize) Rect {+ return .{ .x = self.tabX(index) + self.tabWidth() - 36, .y = 2, .w = 34, .h = 34 };}pub fn newButtonBox(self: *const App) Rect {@@ -37,11 +89,7 @@ pub fn hoverTarget(self: *App) Hover {if (self.find_open) if (self.searchHit(self.px, self.py)) |hit| return .{ .search = hit };if (self.newButtonBox().contains(self.px, self.py)) return .new;if (!self.has_titlebar and self.menuButtonBox().contains(self.px, self.py)) return .menu;- for (self.first_tab..self.tabs.items.len) |i| {- const index = i - self.first_tab;- if (@as(f64, @floatFromInt(index + 1)) * app.tab_w > self.tabRight()) break;- if (self.tabCloseBox(index).contains(self.px, self.py)) return .{ .close = i };- }+ if (self.tabAt(self.px)) |i| if (self.tabCloseBox(i).contains(self.px, self.py)) return .{ .close = i };return .none;}diff --git a/src/editor/app_drafts.zig b/src/editor/app_drafts.zignew file mode 100644index 0000000..74fa09a--- /dev/null+++ b/src/editor/app_drafts.zig@@ -0,0 +1,263 @@+//! Keeping unsaved tabs as drafts: which tabs, when they are written, and+//! bringing them back with the next editor. The files are `drafts.zig`'s.++const std = @import("std");+const c = @import("../files/c.zig").api;+const key_repeat = @import("ui").key_repeat;+const drafts = @import("drafts.zig");+const Document = @import("document.zig").Document;+const app_mod = @import("app.zig");+const App = app_mod.App;+const Tab = app_mod.Tab;+const a = std.heap.c_allocator;++/// A tab with work worth keeping: changed, and not an empty new document.+fn wants(t: *const Tab) bool {+ return t.doc.modified() and (t.path != null or t.doc.text.items.len > 0);+}+fn fits(t: *const Tab, total: usize) bool {+ return t.doc.text.items.len <= drafts.text_limit and total + t.doc.text.items.len <= drafts.total_limit;+}+fn anyWanted(self: *App) bool {+ for (self.tabs.items) |t| if (wants(t)) return true;+ return false;+}++/// Everything a write would change, in one number: the tabs, what they hold+/// and which one is selected. Cursor moves are not in it; they only ride along+/// with the next write.+fn signature(self: *App) u64 {+ var hash = std.hash.Wyhash.init(0);+ hash.update(std.mem.asBytes(&self.selected));+ for (self.tabs.items) |t| {+ hash.update(std.mem.asBytes(&t.id));+ hash.update(std.mem.asBytes(&t.doc.revision));+ hash.update(&.{ @intFromBool(t.doc.modified()), 0 });+ if (t.path) |path| hash.update(path);+ hash.update(&.{0});+ }+ return hash.final();+}++/// Copies what a write needs, so the tabs can change meanwhile.+fn snapshot(self: *App, k: *drafts.Keeper) !drafts.Snapshot {+ var items: std.ArrayList(drafts.Item) = .empty;+ errdefer {+ for (items.items) |item| item.deinit();+ items.deinit(a);+ }+ var total: usize = 0;+ var selected: usize = 0;+ for (self.tabs.items, 0..) |t, i| {+ if (!wants(t) or !fits(t, total)) continue;+ total += t.doc.text.items.len;+ const path = if (t.path) |p| try a.dupe(u8, p) else null;+ errdefer if (path) |p| a.free(p);+ const text = if (t.draft_rev == t.doc.revision) null else try a.dupe(u8, t.doc.text.items);+ errdefer if (text) |x| a.free(x);+ try items.append(a, .{+ .entry = .{ .name = t.draft_name orelse k.next, .path = path, .stamp = t.stamp, .cursor = t.doc.cursor, .anchor = t.doc.anchor, .top = t.doc.top, .bom = t.doc.bom },+ .tab_id = t.id,+ .revision = t.doc.revision,+ .text = text,+ });+ if (t.draft_name == null) {+ t.draft_name = k.next;+ k.next += 1;+ }+ if (i == self.selected) selected = items.items.len - 1;+ }+ return .{ .selected = selected, .next = k.next, .items = try items.toOwnedSlice(a) };+}++/// A written snapshot is what the disk holds now. Tabs that left it lost their files.+fn commit(self: *App, k: *drafts.Keeper, snap: drafts.Snapshot, sig: u64) void {+ for (self.tabs.items) |t| {+ const item = for (snap.items) |item| {+ if (item.tab_id == t.id) break item;+ } else null;+ if (item) |it| {+ if (it.text != null) t.draft_rev = it.revision;+ } else {+ t.draft_name = null;+ t.draft_rev = null;+ }+ }+ k.written = sig;+ k.on_disk = snap.items.len > 0;+}++/// A failed write is tried again after the usual quiet time, not in a loop.+fn backoff(k: *drafts.Keeper, now: i64) void {+ k.last = now;+ k.since = now;+}++fn finish(self: *App, k: *drafts.Keeper, job: *drafts.Job, now: i64) void {+ k.job = null;+ defer job.deinit();+ if (job.err) |err| {+ std.log.warn("rediwm-editor: cannot write drafts: {}", .{err});+ backoff(k, now);+ return;+ }+ commit(self, k, job.snapshot, job.signature);+}++fn startFlush(self: *App, k: *drafts.Keeper, now: i64) void {+ const snap = snapshot(self, k) catch return backoff(k, now);+ if (snap.items.len == 0 and !k.on_disk) {+ // Only tabs too large to keep: there is nothing to write or clear.+ snap.deinit();+ k.written = k.seen;+ k.since = null;+ return;+ }+ k.job = drafts.Job.start(&k.store, snap, k.seen, k.wake) catch {+ snap.deinit();+ return backoff(k, now);+ };+}++/// Writes what the tabs hold now, here and now, after any write in flight.+/// Closing the editor on purpose asks about unsaved tabs first, so what is+/// written here is a session that ended some other way.+fn writeNow(self: *App, k: *drafts.Keeper) bool {+ if (k.job) |job| {+ job.wait();+ finish(self, k, job, key_repeat.nowMs());+ }+ const sig = signature(self);+ if (sig == k.written) return true;+ const snap = snapshot(self, k) catch return false;+ defer snap.deinit();+ if (snap.items.len > 0 or k.on_disk) k.store.write(snap) catch |err| {+ std.log.warn("rediwm-editor: cannot write drafts: {}", .{err});+ return false;+ };+ commit(self, k, snap, sig);+ k.seen = sig;+ k.since = null;+ return true;+}++/// Takes the drafts directory and brings back the last session's tabs. Without+/// a home, or while another editor owns the directory, there are no drafts and+/// closing asks about unsaved work as it always did.+pub fn openDrafts(self: *App, env: std.process.Environ) void {+ start(self, env) catch |err| std.log.warn("rediwm-editor: unsaved text will not be kept: {}", .{err});+}+fn start(self: *App, env: std.process.Environ) !void {+ var store = try drafts.Store.open(self.io, try drafts.directory(env));+ errdefer store.deinit();+ const wake = c.eventfd(0, c.EFD_CLOEXEC | c.EFD_NONBLOCK);+ if (wake < 0) return error.EventFailed;+ errdefer _ = c.close(wake);+ const k = try a.create(drafts.Keeper);+ errdefer a.destroy(k);+ var loaded = store.load();+ defer loaded.deinit();+ k.* = .{ .store = store, .wake = wake, .next = loaded.next, .on_disk = loaded.tabs.items.len > 0 };+ restore(self, &loaded);+ k.seen = signature(self);+ k.written = k.seen;+ self.keeper = k;+ drafts.catchSignals(wake);+}++fn clampToChar(text: []const u8, pos: usize) usize {+ var at = @min(pos, text.len);+ while (at > 0 and at < text.len and text[at] & 0xc0 == 0x80) at -= 1;+ return at;+}++fn restore(self: *App, loaded: *drafts.Loaded) void {+ const blank = self.tabs.items.len == 1 and self.tabs.items[0].path == null and+ self.tabs.items[0].doc.text.items.len == 0 and !self.tabs.items[0].doc.modified();+ var selected: usize = 0;+ var count: usize = 0;+ for (loaded.tabs.items, 0..) |*r, i| {+ const t = a.create(Tab) catch continue;+ t.* = .{ .id = self.next_id, .doc = Document.adopt(r.text, r.bom) catch {+ a.destroy(t);+ continue;+ } };+ r.text = .empty;+ t.path = r.path;+ r.path = null;+ t.stamp = r.stamp;+ const text = t.doc.text.items;+ t.doc.cursor = clampToChar(text, r.cursor);+ t.doc.anchor = clampToChar(text, r.anchor);+ t.doc.top = t.doc.lineStart(clampToChar(text, r.top));+ // The history did not survive, so there is no state to undo back to.+ t.doc.saved = null;+ t.draft_name = r.name;+ t.draft_rev = t.doc.revision;+ self.tabs.append(a, t) catch {+ t.deinit();+ continue;+ };+ self.next_id += 1;+ if (i == loaded.selected) selected = self.tabs.items.len - 1;+ count += 1;+ }+ if (count == 0) return;+ if (blank) {+ self.tabs.orderedRemove(0).deinit();+ selected -|= 1;+ }+ self.selected = selected;+ self.changed();+}++/// Called after every event: notices changes, collects a finished write and+/// starts the next one once typing has paused.+pub fn stepDrafts(self: *App, now: i64) void {+ const k = self.keeper orelse return;+ if (k.job) |job| if (job.done.load(.acquire)) finish(self, k, job, now);+ const sig = signature(self);+ if (sig != k.seen) {+ k.seen = sig;+ k.last = now;+ }+ if (k.seen == k.written) {+ k.since = null;+ } else if (!k.on_disk and !anyWanted(self)) {+ // Nothing to keep and nothing to clear: no timer for a tab switch.+ k.written = k.seen;+ k.since = null;+ } else if (k.since == null) k.since = k.last;+ if (k.due(now)) |wait| if (wait == 0) startFlush(self, k, now);+}++/// Milliseconds until `stepDrafts` has something to do, for the poll timeout.+pub fn draftTimeout(self: *App, now: i64) ?i64 {+ const k = self.keeper orelse return null;+ return k.due(now);+}++pub fn draftWake(self: *App) c_int {+ return if (self.keeper) |k| k.wake else -1;+}++pub fn drainDrafts(self: *App) void {+ const k = self.keeper orelse return;+ var count: u64 = 0;+ _ = c.read(k.wake, &count, 8);+}++/// A signal that ends the session arrived.+pub fn signaled(self: *App) bool {+ return self.keeper != null and drafts.stopping.load(.acquire);+}++pub fn deinitDrafts(self: *App) void {+ const k = self.keeper orelse return;+ self.keeper = null;+ drafts.releaseSignals();+ _ = writeNow(self, k);+ k.store.deinit();+ _ = c.close(k.wake);+ a.destroy(k);+}diff --git a/src/editor/app_input.zig b/src/editor/app_input.zigindex 2a6c9c8..b696d60 100644--- a/src/editor/app_input.zig+++ b/src/editor/app_input.zig@@ -12,7 +12,6 @@ const app_mod = @import("app.zig");const App = app_mod.App;const top = app_mod.top;const status_h = app_mod.status_h;-const tab_w = app_mod.tab_w;const labels = app_mod.labels;/// The byte offset nearest a point given relative to the text origin.@@ -89,12 +88,10 @@ pub fn handleButton(self: *App, code: u32, pressed: bool) void {self.act(.new);return;}- if (self.px < 0 or self.px >= self.tabRight()) return;- const i = self.first_tab + @as(usize, @intFromFloat(@max(0, self.px) / tab_w));- if (i < self.tabs.items.len) {+ if (self.tabAt(self.px)) |i| {self.selected = i;self.changed();- if (self.tabCloseBox(i - self.first_tab).contains(self.px, self.py)) self.closeSelected();+ if (self.tabCloseBox(i).contains(self.px, self.py)) self.closeSelected();}} else if (self.find_open and self.py < self.viewTop()) {if (self.searchHit(self.px, self.py)) |control| self.searchActivate(control);diff --git a/src/editor/app_paint.zig b/src/editor/app_paint.zigindex 08c0878..a28ee71 100644--- a/src/editor/app_paint.zig+++ b/src/editor/app_paint.zig@@ -19,10 +19,10 @@ const app_mod = @import("app.zig");const App = app_mod.App;const top = app_mod.top;const status_h = app_mod.status_h;-const tab_w = app_mod.tab_w;const labels = app_mod.labels;const Tab = app_mod.Tab;const fill = app_mod.fill;+const drawEllipsis = @import("../files/app_draw.zig").drawEllipsis;pub const CaretState = struct {active: bool,@@ -164,25 +164,29 @@ pub fn render(self: *App, cr: *c.cairo_t) void {const t = theme.global;fill(cr, 0, 0, @floatFromInt(self.w), @floatFromInt(self.h), t.app_bg);fill(cr, 0, 0, @floatFromInt(self.w), 38, t.app_bar);- var i = self.first_tab;- while (i < self.tabs.items.len) : (i += 1) {- const x = @as(f64, @floatFromInt(i - self.first_tab)) * tab_w;- if (x + tab_w > self.tabRight()) break;- const tab = self.tabs.items[i];+ c.cairo_save(cr);+ c.cairo_rectangle(cr, 0, 0, self.tabRight(), 38);+ c.cairo_clip(cr);+ const width = self.tabWidth();+ for (self.tabs.items, 0..) |tab, i| {+ const x = self.tabX(i);+ if (x + width <= 0 or x >= self.tabRight()) continue;if (i == self.selected) {- fill(cr, x, 0, tab_w, 38, t.app_bg);- fill(cr, x + 8, 35, tab_w - 16, 2, theme.shellPalette().accent);- }- var buf: [512]u8 = undefined;- const label = std.fmt.bufPrint(&buf, "{s}{s}", .{ tab.name(), if (tab.doc.modified()) " •" else "" }) catch tr("Text file");- c.cairo_save(cr);- c.cairo_rectangle(cr, x + 12, 2, tab_w - 52, 32);- c.cairo_clip(cr);+ fill(cr, x, 0, width, 38, t.app_bg);+ fill(cr, x + 8, 35, width - 16, 2, theme.shellPalette().accent);+ } else if (i + 1 != self.selected and i + 1 < self.tabs.items.len) fill(cr, x + width - 1, 10, 1, 18, t.app_divider);+ // The name gives way to the close button; the unsaved mark never does.+ const name = if (std.unicode.utf8ValidateSlice(tab.name())) tab.name() else tr("Text file");+ const mark: f64 = if (tab.doc.modified()) 14 else 0;+ const room = width - 48 - mark;ui.setSource(cr, t.window_fg);- ui.drawText(cr, label, x + 12, 24, ui.textSize(), false);- c.cairo_restore(cr);- self.paintIcon(cr, self.tabCloseBox(i - self.first_tab), .close, tr("Close tab"), false);+ drawEllipsis(cr, name, x + 12, 24, room, ui.textSize(), false);+ if (mark > 0) {+ ui.drawText(cr, "•", x + 12 + @min(ui.measureText(cr, name, ui.textSize(), false), room) + 5, 24, ui.textSize(), false);+ }+ self.paintIcon(cr, self.tabCloseBox(i), .close, tr("Close tab"), false);}+ c.cairo_restore(cr);self.paintIcon(cr, self.newButtonBox(), .plus, tr("New tab"), false);if (!self.has_titlebar) self.paintIcon(cr, self.menuButtonBox(), .more, tr("Menu"), self.menu_open);if (self.find_open) self.paintSearch(cr);diff --git a/src/editor/app_view.zig b/src/editor/app_view.zigindex 184e902..cec4b48 100644--- a/src/editor/app_view.zig+++ b/src/editor/app_view.zig@@ -92,7 +92,7 @@ pub fn barTimeout(self: *const App, now: i64) ?u32 {pub fn handleScroll(self: *App, amount: f64) void {if (self.close_tab != null or self.menu_open) return;if (self.py >= 0 and self.py < top) {- if (amount > 0) self.first_tab = @min(self.tabs.items.len - 1, self.first_tab + 1) else self.first_tab -|= 1;+ self.scrollTabs(amount * 3);} else if (self.shift and !self.wrap) {self.current().scroll_x = @max(0, self.current().scroll_x + amount * 3);} else {diff --git a/src/editor/drafts.zig b/src/editor/drafts.zignew file mode 100644index 0000000..4f0cdf0--- /dev/null+++ b/src/editor/drafts.zig@@ -0,0 +1,344 @@+//! Unsaved text that outlives the window, a crash and a reboot, like the drafts+//! of GNOME Text Editor.+//!+//! `$XDG_STATE_HOME/rediwm/editor-drafts/` holds `session.json` (the tabs with+//! unsaved work, in order, with their file and cursor) and one `<name>.txt`+//! per such tab. Every file is replaced through a temporary name and synced, so+//! a crash leaves the old or the new one, never half of it. One editor owns the+//! directory (an exclusive `lock`); a second runs without drafts rather than+//! fight over it. Which tabs to keep and when to write is `app_drafts.zig`'s+//! business; nothing here knows about tabs or Wayland.+const std = @import("std");+const c = @import("../files/c.zig").api;+const op = @import("operation.zig");+const Document = @import("document.zig").Document;+const a = std.heap.c_allocator;++/// A tab holding more text than this is not kept as a draft: rewriting it on+/// every pause in typing would cost more than it protects. Closing the window+/// asks about such a tab as usual.+pub const text_limit: usize = 8 * 1024 * 1024;+/// The same for all drafts together.+pub const total_limit: usize = 64 * 1024 * 1024;+/// Quiet time after the last change before the drafts are written.+pub const delay_ms: i64 = 1000;+/// Longest a change waits while typing goes on.+pub const max_wait_ms: i64 = 5000;+const max_tabs = 256;+const manifest_name = "session.json";+const manifest_limit: usize = 4 * 1024 * 1024;++pub const Entry = struct {+ name: u64,+ path: ?[]const u8 = null,+ /// What the file looked like when the tab was loaded or last saved, so a+ /// save of the restored text still notices that the file changed since.+ stamp: ?op.Stamp = null,+ cursor: usize = 0,+ anchor: usize = 0,+ top: usize = 0,+ bom: bool = false,+};+const Manifest = struct {+ version: u32 = 1,+ selected: usize = 0,+ next: u64 = 1,+ tabs: []const Entry = &.{},+};++pub const Restored = struct {+ name: u64,+ path: ?[:0]u8,+ stamp: ?op.Stamp,+ cursor: usize,+ anchor: usize,+ top: usize,+ bom: bool,+ text: std.ArrayList(u8),+ pub fn deinit(r: *Restored) void {+ if (r.path) |path| a.free(path);+ r.text.deinit(a);+ }+};+pub const Loaded = struct {+ selected: usize = 0,+ next: u64 = 1,+ tabs: std.ArrayList(Restored) = .empty,+ pub fn deinit(l: *Loaded) void {+ for (l.tabs.items) |*t| t.deinit();+ l.tabs.deinit(a);+ }+};++/// One tab's draft as handed to the writer. Everything is owned, because the+/// tab goes on changing while a background thread writes.+pub const Item = struct {+ entry: Entry,+ tab_id: usize,+ revision: usize,+ /// Null when the file for `entry.name` already holds this revision.+ text: ?[]u8,+ pub fn deinit(item: Item) void {+ if (item.text) |text| a.free(text);+ if (item.entry.path) |path| a.free(@constCast(path));+ }+};+pub const Snapshot = struct {+ selected: usize,+ next: u64,+ items: []Item,+ pub fn deinit(s: Snapshot) void {+ for (s.items) |item| item.deinit();+ a.free(s.items);+ }+};++pub fn directory(env: std.process.Environ) ![:0]u8 {+ if (env.getPosix("XDG_STATE_HOME")) |base| {+ if (std.fs.path.isAbsolute(base)) return std.fmt.allocPrintSentinel(a, "{s}/rediwm/editor-drafts", .{base}, 0);+ }+ const home = env.getPosix("HOME") orelse return error.NoHome;+ return std.fmt.allocPrintSentinel(a, "{s}/.local/state/rediwm/editor-drafts", .{home}, 0);+}++pub const Store = struct {+ path: [:0]u8,+ dir: c_int,+ lock: c_int,++ /// Takes `path`, which it frees on failure too.+ pub fn open(io: std.Io, path: [:0]u8) !Store {+ errdefer a.free(path);+ try std.Io.Dir.cwd().createDirPath(io, path);+ const dir = c.open(path, c.O_RDONLY | c.O_DIRECTORY | c.O_CLOEXEC | c.O_NOFOLLOW);+ if (dir < 0) return error.OpenFailed;+ errdefer _ = c.close(dir);+ var st: c.struct_stat = undefined;+ if (c.fstat(dir, &st) != 0 or st.st_uid != c.getuid()) return error.NotOwned;+ _ = c.fchmod(dir, 0o700);+ const lock = c.openat(dir, "lock", c.O_RDWR | c.O_CREAT | c.O_CLOEXEC | c.O_NOFOLLOW, @as(c_uint, 0o600));+ if (lock < 0) return error.LockFailed;+ errdefer _ = c.close(lock);+ if (c.flock(lock, c.LOCK_EX | c.LOCK_NB) != 0) return error.Busy;+ return .{ .path = path, .dir = dir, .lock = lock };+ }+ pub fn deinit(s: *Store) void {+ _ = c.close(s.lock);+ _ = c.close(s.dir);+ a.free(s.path);+ }++ /// The drafts of the last session. Anything unreadable, over the limits or+ /// not valid text is left out rather than failing the rest.+ pub fn load(s: *const Store) Loaded {+ var out: Loaded = .{};+ const bytes = readAt(s.dir, manifest_name, manifest_limit) catch return out;+ defer a.free(bytes);+ const parsed = std.json.parseFromSlice(Manifest, a, bytes, .{ .ignore_unknown_fields = true }) catch return out;+ defer parsed.deinit();+ const manifest = parsed.value;+ if (manifest.version != 1) return out;+ out.next = @max(manifest.next, 1);+ for (manifest.tabs[0..@min(manifest.tabs.len, max_tabs)]) |entry| {+ out.next = @max(out.next, entry.name +| 1);+ var file: [32]u8 = undefined;+ const name = std.fmt.bufPrintSentinel(&file, "{d}.txt", .{entry.name}, 0) catch continue;+ const text = readAt(s.dir, name, text_limit) catch continue;+ Document.validate(text) catch {+ a.free(text);+ continue;+ };+ const usable = if (entry.path) |p| std.fs.path.isAbsolute(p) and std.mem.indexOfScalar(u8, p, 0) == null else false;+ const path = if (usable) a.dupeSentinel(u8, entry.path.?, 0) catch null else null;+ out.tabs.append(a, .{+ .name = entry.name,+ .path = path,+ .stamp = if (path != null) entry.stamp else null,+ .cursor = entry.cursor,+ .anchor = entry.anchor,+ .top = entry.top,+ .bom = entry.bom,+ .text = .fromOwnedSlice(text),+ }) catch {+ if (path) |p| a.free(p);+ a.free(text);+ continue;+ };+ }+ out.selected = if (manifest.selected < out.tabs.items.len) manifest.selected else 0;+ return out;+ }++ /// Writes the changed texts, then the session that refers to them, then+ /// removes the files nothing refers to any more.+ pub fn write(s: *const Store, snapshot: Snapshot) !void {+ for (snapshot.items) |item| if (item.text) |text| {+ var file: [32]u8 = undefined;+ try replace(s.dir, try std.fmt.bufPrintSentinel(&file, "{d}.txt", .{item.entry.name}, 0), text);+ };+ const entries = try a.alloc(Entry, snapshot.items.len);+ defer a.free(entries);+ for (snapshot.items, entries) |item, *entry| entry.* = item.entry;+ const json = try std.json.Stringify.valueAlloc(a, Manifest{ .selected = snapshot.selected, .next = snapshot.next, .tabs = entries }, .{});+ defer a.free(json);+ try replace(s.dir, manifest_name, json);+ _ = c.fsync(s.dir);+ s.sweep(snapshot.items);+ }+ fn sweep(s: *const Store, keep: []const Item) void {+ const fd = c.dup(s.dir);+ if (fd < 0) return;+ const stream = c.fdopendir(fd) orelse {+ _ = c.close(fd);+ return;+ };+ defer _ = c.closedir(stream);+ c.rewinddir(stream);+ while (c.readdir(stream)) |entry| {+ const name = std.mem.sliceTo(entry.*.d_name[0..], 0);+ const stale = blk: {+ if (std.mem.endsWith(u8, name, ".tmp")) break :blk true;+ const number = draftNumber(name) orelse break :blk false;+ for (keep) |item| if (item.entry.name == number) break :blk false;+ break :blk true;+ };+ if (stale) _ = c.unlinkat(s.dir, @ptrCast(&entry.*.d_name), 0);+ }+ }+};++/// `<digits>.txt` as a draft's file name.+fn draftNumber(name: []const u8) ?u64 {+ if (!std.mem.endsWith(u8, name, ".txt")) return null;+ return std.fmt.parseInt(u64, name[0 .. name.len - 4], 10) catch null;+}++fn replace(dir: c_int, name: [:0]const u8, bytes: []const u8) !void {+ var buffer: [64]u8 = undefined;+ const temp = try std.fmt.bufPrintSentinel(&buffer, "{s}.tmp", .{name}, 0);+ const fd = c.openat(dir, temp, c.O_WRONLY | c.O_CREAT | c.O_TRUNC | c.O_CLOEXEC | c.O_NOFOLLOW, @as(c_uint, 0o600));+ if (fd < 0) return error.WriteFailed;+ {+ defer _ = c.close(fd);+ errdefer _ = c.unlinkat(dir, temp, 0);+ try op.writeAll(fd, bytes);+ if (c.fsync(fd) != 0) return error.WriteFailed;+ }+ if (c.renameat(dir, temp, dir, name) != 0) {+ _ = c.unlinkat(dir, temp, 0);+ return error.WriteFailed;+ }+}++fn readAt(dir: c_int, name: [:0]const u8, limit: usize) ![]u8 {+ const fd = c.openat(dir, name, c.O_RDONLY | c.O_CLOEXEC | c.O_NOFOLLOW | c.O_NONBLOCK);+ if (fd < 0) return error.OpenFailed;+ defer _ = c.close(fd);+ var st: c.struct_stat = undefined;+ if (c.fstat(fd, &st) != 0 or st.st_mode & c.S_IFMT != c.S_IFREG or st.st_size < 0 or @as(u64, @intCast(st.st_size)) > limit) return error.Unreadable;+ const buffer = try a.alloc(u8, @intCast(st.st_size));+ errdefer a.free(buffer);+ var got: usize = 0;+ while (got < buffer.len) {+ const n = c.read(fd, buffer.ptr + got, buffer.len - got);+ if (n < 0 and std.posix.errno(n) == .INTR) continue;+ if (n <= 0) return error.Unreadable;+ got += @intCast(n);+ }+ return buffer;+}++/// Writes a snapshot on a thread of its own and wakes the event loop through+/// `wake` when done. Fsyncs can take tens of milliseconds on a slow disk.+pub const Job = struct {+ store: *const Store,+ snapshot: Snapshot,+ /// The state of the tabs the snapshot was taken from.+ signature: u64,+ wake: c_int,+ thread: ?std.Thread = null,+ done: std.atomic.Value(bool) = .init(false),+ err: ?anyerror = null,++ /// On failure the caller still owns `snapshot`.+ pub fn start(store: *const Store, snapshot: Snapshot, signature: u64, wake: c_int) !*Job {+ const job = try a.create(Job);+ errdefer a.destroy(job);+ job.* = .{ .store = store, .snapshot = snapshot, .signature = signature, .wake = wake };+ job.thread = try std.Thread.spawn(.{}, run, .{job});+ return job;+ }+ fn run(job: *Job) void {+ job.store.write(job.snapshot) catch |err| {+ job.err = err;+ };+ job.done.store(true, .release);+ notify(job.wake);+ }+ pub fn wait(job: *Job) void {+ if (job.thread) |thread| thread.join();+ job.thread = null;+ }+ pub fn deinit(job: *Job) void {+ job.wait();+ job.snapshot.deinit();+ a.destroy(job);+ }+};++fn notify(fd: c_int) void {+ const one: u64 = 1;+ _ = c.write(fd, &one, 8);+}++/// Set by SIGTERM/SIGHUP/SIGINT: the session is ending, write what is open.+pub var stopping = std.atomic.Value(bool).init(false);+var signal_wake: c_int = -1;+fn onSignal(_: c_int) callconv(.c) void {+ const errno = std.c._errno();+ const saved = errno.*;+ stopping.store(true, .release);+ notify(signal_wake);+ errno.* = saved;+}+/// Routes the signals that end a session to `wake`, so the event loop can+/// write the drafts before it exits instead of dying with the last seconds.+pub fn catchSignals(wake: c_int) void {+ signal_wake = wake;+ _ = c.signal(c.SIGTERM, onSignal);+ _ = c.signal(c.SIGHUP, onSignal);+ _ = c.signal(c.SIGINT, onSignal);+}++pub fn releaseSignals() void {+ _ = c.signal(c.SIGTERM, c.SIG_DFL);+ _ = c.signal(c.SIGHUP, c.SIG_DFL);+ _ = c.signal(c.SIGINT, c.SIG_DFL);+ signal_wake = -1;+}++/// What the app keeps between events: the store, the writer in flight and the+/// timing of the next write.+pub const Keeper = struct {+ store: Store,+ wake: c_int,+ job: ?*Job = null,+ /// The next draft file name.+ next: u64 = 1,+ /// The state of the tabs last looked at and last written (`app_drafts.signature`).+ seen: u64 = 0,+ written: u64 = 0,+ /// The first and the latest change not written yet.+ since: ?i64 = null,+ last: i64 = 0,+ /// Whether the session on disk holds any tab, which a write must clear.+ on_disk: bool = false,++ /// Milliseconds until the pending change is due, null with nothing to+ /// wait for. A write in flight wakes the loop itself.+ pub fn due(k: *const Keeper, now: i64) ?i64 {+ if (k.job != null) return null;+ const since = k.since orelse return null;+ return @max(0, @min(k.last + delay_ms, since + max_wait_ms) - now);+ }+};diff --git a/src/editor/drafts_tests.zig b/src/editor/drafts_tests.zignew file mode 100644index 0000000..33b5233--- /dev/null+++ b/src/editor/drafts_tests.zig@@ -0,0 +1,110 @@+const std = @import("std");+const c = @import("../files/c.zig").api;+const drafts = @import("drafts.zig");+const a = std.heap.c_allocator;++const Scratch = struct {+ root: [:0]u8,+ fn make() !Scratch {+ var template = "/tmp/rediwm-drafts-XXXXXX".*;+ _ = c.mkdtemp(&template) orelse return error.MkdtempFailed;+ return .{ .root = try a.dupeSentinel(u8, std.mem.sliceTo(&template, 0), 0) };+ }+ fn path(s: Scratch) ![:0]u8 {+ return std.fmt.allocPrintSentinel(a, "{s}/state/drafts", .{s.root}, 0);+ }+ fn remove(s: Scratch) void {+ std.Io.Dir.cwd().deleteTree(std.testing.io, s.root) catch {};+ a.free(s.root);+ }+};++fn item(name: u64, path: ?[]const u8, text: ?[]const u8) !drafts.Item {+ return .{+ .entry = .{ .name = name, .path = if (path) |p| try a.dupe(u8, p) else null, .cursor = 3, .anchor = 1, .top = 0 },+ .tab_id = name,+ .revision = 1,+ .text = if (text) |t| try a.dupe(u8, t) else null,+ };+}++test "drafts survive a write and load, and unreferenced files are swept" {+ const scratch = try Scratch.make();+ defer scratch.remove();+ var store = try drafts.Store.open(std.testing.io, try scratch.path());+ defer store.deinit();++ var items = try a.alloc(drafts.Item, 2);+ items[0] = try item(4, null, "typed, never saved\nsecond line é");+ items[1] = try item(7, "/home/user/notes.txt", "edited file");+ const first: drafts.Snapshot = .{ .selected = 1, .next = 8, .items = items };+ defer first.deinit();+ try store.write(first);+ // A stale draft and a half-written file from a crash are cleared by the next write.+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/state/drafts/99.txt", .{scratch.root}), .data = "stale" });+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = try std.fmt.allocPrint(a, "{s}/state/drafts/7.txt.tmp", .{scratch.root}), .data = "torn" });++ // Tab 4 is unchanged (no text to write); tab 7 gets new text.+ var again = try a.alloc(drafts.Item, 2);+ again[0] = try item(4, null, null);+ again[1] = try item(7, "/home/user/notes.txt", "edited file, again");+ const second: drafts.Snapshot = .{ .selected = 0, .next = 8, .items = again };+ defer second.deinit();+ try store.write(second);++ var loaded = store.load();+ defer loaded.deinit();+ try std.testing.expectEqual(@as(usize, 2), loaded.tabs.items.len);+ try std.testing.expectEqual(@as(u64, 8), loaded.next);+ try std.testing.expectEqual(@as(usize, 0), loaded.selected);+ try std.testing.expectEqualStrings("typed, never saved\nsecond line é", loaded.tabs.items[0].text.items);+ try std.testing.expect(loaded.tabs.items[0].path == null);+ try std.testing.expectEqualStrings("/home/user/notes.txt", loaded.tabs.items[1].path.?);+ try std.testing.expectEqualStrings("edited file, again", loaded.tabs.items[1].text.items);+ try std.testing.expectEqual(@as(usize, 3), loaded.tabs.items[0].cursor);++ var stale: c.struct_stat = undefined;+ const stale_path = try std.fmt.allocPrintSentinel(a, "{s}/state/drafts/99.txt", .{scratch.root}, 0);+ defer a.free(stale_path);+ try std.testing.expect(c.stat(stale_path, &stale) != 0);+ const torn_path = try std.fmt.allocPrintSentinel(a, "{s}/state/drafts/7.txt.tmp", .{scratch.root}, 0);+ defer a.free(torn_path);+ try std.testing.expect(c.stat(torn_path, &stale) != 0);+}++test "a draft that cannot be read or is not text is left out, not fatal" {+ const scratch = try Scratch.make();+ defer scratch.remove();+ var store = try drafts.Store.open(std.testing.io, try scratch.path());+ defer store.deinit();+ var items = try a.alloc(drafts.Item, 3);+ items[0] = try item(1, null, "good");+ items[1] = try item(2, null, "will be binary");+ items[2] = try item(3, null, "will vanish");+ const snapshot: drafts.Snapshot = .{ .selected = 2, .next = 4, .items = items };+ defer snapshot.deinit();+ try store.write(snapshot);+ const dir = try std.fmt.allocPrint(a, "{s}/state/drafts", .{scratch.root});+ defer a.free(dir);+ const binary = try std.fmt.allocPrint(a, "{s}/2.txt", .{dir});+ defer a.free(binary);+ try std.Io.Dir.cwd().writeFile(std.testing.io, .{ .sub_path = binary, .data = "bin\x00ary" });+ const vanished = try std.fmt.allocPrint(a, "{s}/3.txt", .{dir});+ defer a.free(vanished);+ try std.Io.Dir.cwd().deleteFile(std.testing.io, vanished);++ var loaded = store.load();+ defer loaded.deinit();+ try std.testing.expectEqual(@as(usize, 1), loaded.tabs.items.len);+ try std.testing.expectEqualStrings("good", loaded.tabs.items[0].text.items);+ // The selected tab was dropped: fall back to the first.+ try std.testing.expectEqual(@as(usize, 0), loaded.selected);+}++test "a second editor cannot take the drafts directory" {+ const scratch = try Scratch.make();+ defer scratch.remove();+ var store = try drafts.Store.open(std.testing.io, try scratch.path());+ defer store.deinit();+ try std.testing.expectError(error.Busy, drafts.Store.open(std.testing.io, try scratch.path()));+}diff --git a/src/editor/main.zig b/src/editor/main.zigindex 665589c..10aa604 100644--- a/src/editor/main.zig+++ b/src/editor/main.zig@@ -193,6 +193,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impoconst display = try wl.Display.connect(null);defer display.disconnect();var self = Client{ .display = display, .app = try app_mod.App.init(init.io) };+ self.app.openDrafts(init.minimal.environ);for (paths) |path| self.app.open(path);self.ime = .{ .app = &self.app };defer self.ime.deinit();@@ -272,6 +273,9 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impodefer a.free(pending_token);while (self.running) {self.app.sync();+ self.app.stepDrafts(key_repeat.nowMs());+ // The session is ending: leave without asking; `deinit` writes the drafts.+ if (self.app.signaled()) self.app.closed = true;if (self.app.closed) {self.close();break;@@ -320,10 +324,15 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impofds[0] = .{ .fd = display.getFd(), .events = @intCast(c.POLLIN | @as(c_int, if (flushed == .AGAIN) c.POLLOUT else 0)), .revents = 0 };fds[1] = .{ .fd = if (self.app.operation) |job| job.fd else -1, .events = c.POLLIN, .revents = 0 };fds[2] = .{ .fd = instance.fd, .events = c.POLLIN, .revents = 0 };- const fd_count = 3 + self.clipboard.addPoll(fds[3..]);+ fds[3] = .{ .fd = self.app.draftWake(), .events = c.POLLIN, .revents = 0 };+ const fd_count = 4 + self.clipboard.addPoll(fds[4..]);const poll_now = key_repeat.nowMs();var timeout: c_int = if (self.key_repeat.timeoutMs(poll_now)) |wait| @intCast(@min(wait, 60_000)) else -1;if (self.app.barTimeout(poll_now)) |wait| timeout = if (timeout < 0) @intCast(wait) else @min(timeout, @as(c_int, @intCast(wait)));+ if (self.app.draftTimeout(poll_now)) |wait| {+ const ms: c_int = @intCast(@min(wait, 60_000));+ timeout = if (timeout < 0) ms else @min(timeout, ms);+ }const result = c.poll(&fds, fd_count, self.app.caret.timeout(poll_now, self.clipboard.timeout(timeout)));if (result > 0 and (fds[0].revents & c.POLLIN != 0)) {if (display.readEvents() != .SUCCESS) return error.DisplayFailed;@@ -332,6 +341,7 @@ pub fn run(init: std.process.Init, paths: []const [:0]const u8, instance: *@impo}if ((fds[0].revents & (c.POLLERR | c.POLLHUP)) != 0) return error.DisplayFailed;if (display.dispatchPending() != .SUCCESS) return error.DisplayFailed;+ if (fds[3].revents & c.POLLIN != 0) self.app.drainDrafts();if (fds[2].revents & c.POLLIN != 0) {var request_buf: [16384]u8 = undefined;if (instance.receive(&request_buf)) |bytes| {diff --git a/src/editor_tests.zig b/src/editor_tests.zigindex 5ccfef5..65a632f 100644--- a/src/editor_tests.zig+++ b/src/editor_tests.zig@@ -3,6 +3,7 @@ test {_ = @import("editor/formats.zig");_ = @import("editor/document.zig");_ = @import("editor/document_search.zig");+ _ = @import("editor/drafts_tests.zig");_ = @import("editor/lines.zig");_ = @import("editor/view.zig");_ = @import("editor/operation.zig");diff --git a/tests/editor.py b/tests/editor.pyindex b66e3bd..1146612 100644--- a/tests/editor.py+++ b/tests/editor.py@@ -305,6 +305,109 @@ def run():wait_for(lambda: not windows("rediwm-editor"), "editor closes")print("binary rejection and clean window close", flush=True)+ # Unsaved text outlives a kill, a signal and closing the window.+ import json, signal+ drafts = tmp / "state/rediwm/editor-drafts"++ def kept():+ try:+ return json.loads((drafts / "session.json").read_text())["tabs"]+ except (OSError, ValueError):+ return None++ def gone(proc):+ wait_for(lambda: proc.poll() is not None and not windows("rediwm-editor"), "editor exits")++ notes = docs / "draft-notes.txt"+ notes.write_text("on disk\n")+ proc = start("rediwm-editor", notes)+ win = title("draft-notes.txt")+ ipc.focus_window(win["id"])+ key(107, ctrl=True)+ ipc.type_text("typed in file")+ key(49, ctrl=True) # new tab+ ipc.type_text("never saved note")+ title("* Untitled")+ wait_for(lambda: len(kept() or []) == 2, "drafts written after a pause in typing")+ assert oct((drafts / "session.json").stat().st_mode & 0o777) == "0o600"+ assert oct(drafts.stat().st_mode & 0o777) == "0o700"+ proc.send_signal(signal.SIGKILL)+ proc.wait()+ wait_for(lambda: not windows("rediwm-editor"), "killed editor unmaps")+ assert notes.read_text() == "on disk\n"++ proc = start("rediwm-editor")+ win = title("* Untitled")+ assert "(2/2)" in win["title"], win["title"]+ ipc.focus_window(win["id"])+ key(104, ctrl=True) # previous tab: the file, edited, still unsaved+ title("* draft-notes.txt")+ key(31, ctrl=True)+ wait_for(lambda: notes.read_bytes() == b"on disk\ntyped in file", "restored file draft saves over its file")+ title("draft-notes.txt")+ wait_for(lambda: len(kept() or []) == 1, "a saved tab leaves the drafts")+ assert len(list(drafts.glob("*.txt"))) == 1++ # Closing the window asks about what is unsaved, like closing a+ # tab; the drafts are for a session that ends some other way.+ ipc.action("close_window", {"id": editor()["id"]})+ time.sleep(.3)+ assert editor(), "window closed on unsaved work without asking"+ key(1) # cancel+ win = title("* Untitled")+ assert "(1/1)" in win["title"], win["title"]+ ipc.focus_window(win["id"])+ ipc.type_text(" and more")+ time.sleep(.3)+ proc.terminate() # SIGTERM before the pause: written on the way out+ gone(proc)+ assert any(b"never saved note and more" in p.read_bytes() for p in drafts.glob("*.txt")), "SIGTERM flushed the last typing"+ proc = start("rediwm-editor")+ win = title("* Untitled")+ ipc.focus_window(win["id"])++ # Discarding on purpose is the only way to lose it.+ key(17, ctrl=True)+ box = ipc.get_window_debug(editor()["id"])["client_box"]+ header = 46 if csd else 0+ click(editor(), (box["width"]-420)/2+200, (box["height"]-header-170)/2+130+header)+ gone(proc)+ assert kept() == [] and not list(drafts.glob("*.txt")), "discarded draft is removed"+ proc = start("rediwm-editor")+ title("Untitled")+ assert "(1/1)" in editor()["title"] and not editor()["title"].startswith("*")+ key(17, ctrl=True)+ gone(proc)+ print("unsaved text survives kill and signal, and closing asks, until discarded", flush=True)++ # Many tabs share the strip down to a minimum width, then it scrolls.+ proc = start("rediwm-editor")+ win = title("Untitled")+ ipc.focus_window(win["id"])+ for _ in range(11):+ key(49, ctrl=True)+ assert "(12/12)" in title("Untitled")["title"]+ box = ipc.get_window_debug(editor()["id"])["client_box"]+ header = 46 if csd else 0+ strip = box["width"] - (40 if csd else 80)+ assert strip / 12 < 112 < 12 * 112 - strip + 1, strip+ # Away from the close buttons, which sit at the right of each tab.+ click(editor(), strip - 60, header + 18)+ assert "(12/12)" in title("Untitled")["title"], "the newest tab is scrolled into view"+ reached = []+ for dy in (2000, -2000):+ ipc.move_cursor(round(box["x"] + 300), round(box["y"] + header + 18))+ ipc.scroll(0, dy)+ time.sleep(.2)+ click(editor(), 60, header + 18)+ reached.append(int(editor()["title"].rsplit("(", 1)[1].split("/")[0]))+ far = int((60 + 12 * 112 - strip) // 112) + 1+ assert sorted(reached) == [1, far], ("the wheel scrolls the strip to both ends", reached, far)+ for _ in range(12):+ key(17, ctrl=True)+ gone(proc)+ print("tabs share the strip, shrink to a minimum and scroll", flush=True)+# Beyond the old 16 MiB limit, and past the size where a save is# copied: opening must not lay the whole text out, End must reach# the real end, and the file written must be exact.