write 0.4.0

A fullscreen, distraction-free, write-only Markdown editor that fades text away to silence the writer's inner editor.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
use std::collections::VecDeque;
use std::fs::{self, File, OpenOptions, TryLockError};
use std::io::{BufWriter, Write};
use std::path::PathBuf;
use std::time::{Duration, Instant};

use chrono::Local;
use eframe::egui;

mod render;

use render::{
    Glyph, PRIMARY, PRIMARY_DARKER, build_job, glyph_factor, shake_offset,
    start_byte_of_second_to_last_word, word_count,
};

const SYNC_INTERVAL: Duration = Duration::from_secs(30);
const FONT_SIZE: f32 = 28.0;

/// Result of acquiring today's session file: the locked handle, the day-total word
/// count already on disk, and the file's byte length at open (the hard delete floor).
type SessionFile = (File, usize, u64);

pub struct WriteApp {
    document: String,         // file mirror; retained for 1c word count
    visible: VecDeque<Glyph>, // render buffer; pruned each frame as glyphs fully fade
    writer: BufWriter<File>,  // append-only handle to the session .md
    visibility_head: f64,     // glyphs born before this fade out at once (visual clear)
    shake_start: f64,         // time of the last backspace-clear; drives the wiggle feedback
    enter_run: u8,            // 0 = none, 1 = one Enter written, 2+ = cleared / no-op
    boot_size: u64,           // file length at open; hard deletion floor (protects prior sessions)
    delete_floor: u64, // monotonic, non-decreasing byte floor; backspace never truncates below it
    menu_open: bool,
    fullscreen: bool,         // live window state; toggled from the Esc menu (W)
    darker: bool,             // session-only render state; toggled from the Esc menu (D)
    entered_fullscreen: bool, // one-shot: launch-time deferred fullscreen, applied once focused
    seed_words: usize,        // day-total words already on disk at open time
    last_sync: Instant,
}

/// Open today's append-only session file (`~/Documents/write/YYYY-MM-DD.md`),
/// creating it if needed, and take an exclusive advisory lock. Invocations on the
/// same day share one file; the lock ensures only one `write` process appends to
/// it at a time. Returns `Ok(None)` when another process already holds today's
/// lock — the caller should exit quietly.
pub fn open_session_file() -> Result<Option<SessionFile>, Box<dyn std::error::Error + Send + Sync>>
{
    let path = today_file_path()?;
    let file = OpenOptions::new().create(true).append(true).open(&path)?;
    // Advisory flock tied to this fd; released automatically when the process exits.
    match file.try_lock() {
        Ok(()) => {
            let existing = fs::read_to_string(&path).unwrap_or_default();
            // Count words BEFORE writing the header so its tokens aren't counted as the writer's.
            let seed = word_count(&existing);

            // Idempotent blank-line separation: cap at exactly two trailing newlines so
            // repeated launches don't grow blank-line runs. Empty file starts cleanly.
            let prefix = if existing.is_empty() || existing.ends_with("\n\n") {
                ""
            } else if existing.ends_with('\n') {
                "\n"
            } else {
                "\n\n"
            };
            let header = format!(
                "{prefix}## {}\n\n",
                Local::now().format("%Y-%m-%d %-I:%M:%S%P %Z")
            );

            // Write the header through the raw fd (append mode) BEFORE capturing boot_size,
            // so the existing delete-floor mechanism protects it and the TUI never shows it.
            let mut file = file;
            file.write_all(header.as_bytes())?;
            let boot_size = file.metadata()?.len();
            Ok(Some((file, seed, boot_size)))
        }
        Err(TryLockError::WouldBlock) => Ok(None),
        Err(TryLockError::Error(e)) => Err(Box::new(e)),
    }
}

/// Resolve today's session-file path (`~/Documents/write/YYYY-MM-DD.md`),
/// creating the `write/` directory if needed. Does not open or lock the file.
pub fn today_file_path() -> Result<PathBuf, Box<dyn std::error::Error + Send + Sync>> {
    let mut dir: PathBuf = dirs::document_dir()
        .or_else(dirs::home_dir)
        .ok_or("no Documents or home directory")?;
    dir.push("write");
    fs::create_dir_all(&dir)?;
    dir.push(format!("{}.md", Local::now().format("%Y-%m-%d")));
    Ok(dir)
}

/// Open today's session file in the writer's editor and wait for it to close.
/// Pre-creates the file so the editor opens an existing path. Resolves the editor
/// via `$VISUAL` → `$EDITOR` → `vi`, shell-splitting on whitespace so values like
/// `"code -w"` work. Propagates a non-zero editor exit code as our exit code.
pub fn run_edit() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let path = today_file_path()?;
    // Touch so the editor opens an existing file (no advisory lock here).
    drop(OpenOptions::new().create(true).append(true).open(&path)?);

    let editor = std::env::var("VISUAL")
        .or_else(|_| std::env::var("EDITOR"))
        .unwrap_or_else(|_| "vi".to_string());

    let mut parts = editor.split_whitespace();
    let program = parts.next().ok_or("empty editor command")?;
    let status = std::process::Command::new(program)
        .args(parts)
        .arg(&path)
        .status()?; // inherits stdio by default

    if !status.success() {
        std::process::exit(status.code().unwrap_or(1));
    }
    Ok(())
}

/// Dump today's session file to stdout verbatim (including `## <datetime>` headers and
/// blank-line separators). A missing file is treated as an empty day: print nothing, exit 0.
/// Takes no advisory lock and creates nothing.
pub fn run_show() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
    let path = today_file_path()?;
    match fs::read(&path) {
        Ok(bytes) => {
            use std::io::Write as _;
            std::io::stdout().write_all(&bytes)?;
            Ok(())
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(e) => Err(Box::new(e)),
    }
}

impl WriteApp {
    pub fn new(
        _cc: &eframe::CreationContext<'_>,
        file: File,
        seed_words: usize,
        boot_size: u64,
    ) -> Self {
        Self {
            document: String::new(),
            visible: VecDeque::new(),
            writer: BufWriter::new(file),
            visibility_head: 0.0,
            shake_start: f64::NEG_INFINITY,
            enter_run: 0,
            boot_size,
            delete_floor: boot_size,
            menu_open: false,
            fullscreen: false,
            darker: false,
            entered_fullscreen: false,
            seed_words,
            last_sync: Instant::now(),
        }
    }

    // Append raw text to the file mirror, the file, and the visible render buffer.
    fn append(&mut self, s: &str, now: f64) {
        let mut end = self.document.len();
        for ch in s.chars() {
            end += ch.len_utf8();
            self.visible.push_back(Glyph {
                ch,
                birth: now,
                end_offset: end,
            });
        }
        self.document.push_str(s);
        if let Err(e) = self.writer.write_all(s.as_bytes()) {
            eprintln!("write: failed to append to file: {e}");
        }
        let candidate = self.boot_size + start_byte_of_second_to_last_word(&self.document) as u64;
        self.delete_floor = self.delete_floor.max(candidate); // max() keeps it monotonic
    }

    // Bounded deletion: truncate the day file by one whole char, but never below
    // `delete_floor` (the monotonic "two words ago" floor). A blocked backspace
    // triggers a horizontal wiggle (via `shake_start`) as "no" feedback; a successful
    // deletion does not.
    fn backspace(&mut self, now: f64) {
        let current_end = self.boot_size + self.document.len() as u64;
        if self.document.is_empty() || current_end <= self.delete_floor {
            self.shake_start = now; // floor reached → wiggle feedback
            return;
        }
        let ch = self.document.chars().next_back().unwrap();
        if current_end - (ch.len_utf8() as u64) < self.delete_floor {
            self.shake_start = now; // would cross the floor → wiggle feedback
            return;
        }
        self.document.pop(); // UTF-8 safe: pops a whole char
        if let Err(e) = self.writer.flush() {
            eprintln!("write: flush before truncate failed: {e}");
            return; // do NOT set_len with bytes still buffered
        }
        let new_end = self.boot_size + self.document.len() as u64;
        if let Err(e) = self.writer.get_ref().set_len(new_end) {
            eprintln!("write: truncate failed: {e}");
        }
        let doc_len = self.document.len();
        while let Some(g) = self.visible.back() {
            if g.end_offset > doc_len {
                self.visible.pop_back();
            } else {
                break;
            }
        }
        self.enter_run = 0;
    }

    fn fsync(&mut self) {
        if let Err(e) = self.writer.flush() {
            eprintln!("write: flush failed: {e}");
        }
        if let Err(e) = self.writer.get_ref().sync_data() {
            eprintln!("write: sync_data failed: {e}");
        }
    }
}

impl eframe::App for WriteApp {
    fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let ctx = ui.ctx().clone(); // cheap Arc clone; avoids borrow conflict with ui.painter()

        // Suppress Tab focus navigation.
        ctx.input_mut(|i| {
            let _ = i.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
        });

        let now = ctx.input(|i| i.time);

        // Enter fullscreen only once the window has focus, to dodge the launch-time
        // activation race that otherwise bounces the Space back to the desktop. Keep
        // repainting until then so we actually observe the focus transition.
        if !self.entered_fullscreen {
            if ctx.input(|i| i.focused) {
                ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(true));
                self.entered_fullscreen = true;
                self.fullscreen = true;
            } else {
                ctx.request_repaint();
            }
        }

        // Copy events out, keep the input closure short.
        let events = ctx.input(|i| i.events.clone());
        // Closing the menu is deferred to after this batch so the trailing Text
        // event a key emits (e.g. W's "w") is still swallowed by the menu gate
        // and doesn't leak into the document.
        let mut close_menu = false;
        for event in events {
            if self.menu_open {
                if let egui::Event::Key {
                    key, pressed: true, ..
                } = event
                {
                    match key {
                        egui::Key::Q => ctx.send_viewport_cmd(egui::ViewportCommand::Close),
                        egui::Key::W => {
                            self.fullscreen = !self.fullscreen;
                            ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(
                                self.fullscreen,
                            ));
                            close_menu = true; // resume writing in the new window state
                        }
                        egui::Key::D => {
                            self.darker = !self.darker;
                            close_menu = true; // resume writing in the new brightness
                        }
                        egui::Key::Escape => close_menu = true, // resume writing
                        _ => {}
                    }
                }
                continue; // ignore Text and everything else while the menu is open
            }
            match event {
                egui::Event::Text(t) => {
                    self.append(&t, now); // Text already handles shift/dead/accents
                    self.enter_run = 0;
                }
                egui::Event::Key {
                    key,
                    modifiers,
                    pressed: true,
                    ..
                } => {
                    if modifiers.command {
                        // ignore Cmd/Ctrl combos (paste, undo, ...)
                        continue;
                    }
                    match key {
                        egui::Key::Enter => {
                            match self.enter_run {
                                0 => {
                                    self.append("\n\n", now);
                                    self.enter_run = 1;
                                }
                                1 => {
                                    // Second consecutive Enter: clear the screen (no newlines).
                                    self.visibility_head = now;
                                    self.enter_run = 2;
                                }
                                _ => {} // already cleared → no-op
                            }
                        }
                        egui::Key::Backspace => {
                            self.backspace(now);
                        }
                        egui::Key::Escape => {
                            self.menu_open = true;
                            self.fsync(); // durable flush on menu open
                        }
                        _ => {} // arrows, Delete, Tab, Home, End, PageUp/Down → no-op
                    }
                }
                _ => {} // Event::Paste, Event::Ime, pointer, etc. → ignored
            }
        }
        if close_menu {
            self.menu_open = false;
        }

        // Periodic durability: flush + sync_data ~every 30s.
        if self.last_sync.elapsed() >= SYNC_INTERVAL {
            self.fsync();
            self.last_sync = Instant::now();
        }

        // Prune fully-faded glyphs from the front (oldest first; glyphs are in birth order).
        // Uses the combined factor so clear-faded glyphs drain too.
        while let Some(front) = self.visible.front() {
            if glyph_factor(front.birth, now, self.visibility_head) <= 0.0 {
                self.visible.pop_front();
            } else {
                break;
            }
        }

        // Render: full-rect black background + a center-anchored, centered fading galley.
        let rect = ctx.content_rect();
        let margin = 40.0_f32;
        let max_col = 760.0_f32;
        let col_width = (rect.width() - 2.0 * margin).clamp(0.0, max_col);
        let primary = if self.darker { PRIMARY_DARKER } else { PRIMARY };
        let floor_byte = (self.delete_floor - self.boot_size) as usize;
        let job = build_job(
            self.visible.make_contiguous(),
            now,
            self.visibility_head,
            egui::FontId::proportional(FONT_SIZE),
            primary,
            col_width,
            floor_byte,
        );
        let painter = ui.painter();
        painter.rect_filled(rect, 0.0, egui::Color32::BLACK);
        let galley = painter.layout_job(job);
        let dx = shake_offset(now - self.shake_start);
        let x = rect.left() + (rect.width() - col_width) * 0.5 + dx;
        let x_height = 0.5 * FONT_SIZE; // egui 0.34 has no x-height metric; 0.5em is close enough
        let center_y = rect.center().y;
        let y = center_y + x_height - galley.size().y; // newest line one x-height below center; older lines scroll up

        // Insertion-point marker: a passive, non-blinking block at the galley tail. Computed
        // here because painter.galley(...) below moves `galley`.
        let cursor_rect = (!self.visible.is_empty()).then(|| {
            let tail = galley.pos_from_cursor(galley.end()); // galley-local, zero-width
            let top_left = egui::pos2(x, y) + tail.min.to_vec2();
            let h = tail.height().max(FONT_SIZE); // never degenerate
            egui::Rect::from_min_size(top_left, egui::vec2(0.5 * FONT_SIZE, h))
        });

        painter.galley(egui::pos2(x, y), galley, primary); // existing line — galley moved here

        // Cursor fades with the newest visible glyph and inherits darker mode via `primary`.
        if let Some(cursor_rect) = cursor_rect
            && let Some(g) = self.visible.back()
        {
            let factor = glyph_factor(g.birth, now, self.visibility_head);
            let cursor_color = primary.gamma_multiply(factor);
            painter.rect_filled(cursor_rect, 0.0, cursor_color);
        }

        let words = self.seed_words + word_count(&self.document);
        if words >= 2 {
            let pos = egui::pos2(rect.right() - margin, rect.top() + margin);
            painter.text(
                pos,
                egui::Align2::RIGHT_TOP,
                format!("{words} words"),
                egui::FontId::proportional(0.5 * FONT_SIZE), // smaller than body
                egui::Color32::from_gray(110),               // dim gray so the HUD recedes
            );
        }

        if self.menu_open {
            let words = self.seed_words + word_count(&self.document);
            egui::Window::new("menu")
                .title_bar(false)
                .resizable(false)
                .collapsible(false)
                .anchor(egui::Align2::CENTER_CENTER, egui::Vec2::ZERO)
                .show(&ctx, |ui| {
                    ui.vertical_centered(|ui| {
                        ui.label(egui::RichText::new(format!("{words} words")).size(24.0));
                        ui.add_space(8.0);
                        let win_hint = if self.fullscreen {
                            "W — windowed"
                        } else {
                            "W — fullscreen"
                        };
                        let dark_hint = if self.darker {
                            "D — normal"
                        } else {
                            "D — darker"
                        };
                        ui.label(format!(
                            "Q — quit     Esc — resume     {win_hint}     {dark_hint}"
                        ));
                    });
                });
        }

        if self.visible.is_empty() {
            // Idle: nothing to animate. Wake only to run the periodic fsync.
            ctx.request_repaint_after(SYNC_INTERVAL.saturating_sub(self.last_sync.elapsed()));
        } else {
            // Text still visible/fading: animate.
            ctx.request_repaint();
        }
    }

    fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
        [0.0, 0.0, 0.0, 1.0]
    }

    fn on_exit(&mut self) {
        self.fsync(); // final flush + sync on clean exit
    }
}