slipcase-open 0.2.1

Open the content file of a Slipcase container in its own application, and write edits back into the container
Documentation
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Watching the content directory, and what the events in it mean.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)
//
//! **The watch is on the directory and never on the file**, which concept 6
//! calls one of the three things that make write-back detection hard. A serious
//! editor saves by writing a temporary sibling and renaming it over the target,
//! so a watcher registered on the content file loses its handle on the first
//! save and never fires again. `notify` will watch a directory on all three
//! platforms, but only if it is asked to.
//!
//! ## The sibling signal
//!
//! Concept 6.1: the content directory holds one file, put there by this tool,
//! so anything else appearing in it was created by the target application — a
//! lock file, an autosave, a backup, a save in progress. Nothing here needs to
//! know which, or what any of them are called, which is why there is no table
//! of `~$name.docx` and `.~lock.name#` conventions to maintain and no
//! application it fails to know about.
//!
//! Siblings present means the application is working in there, which process
//! exit does not tell you. Siblings gone means it has cleaned up and has
//! probably finished. It stays a heuristic in both directions: most
//! read-oriented applications write no sibling at all, so an empty directory
//! means nothing, and an application that leaves a backup behind for good never
//! produces the cleaned-up signal. Both degrade to silence, which is the
//! intended fallback and is why the session model does not rest on this.

use std::path::Path;
use std::sync::mpsc::{self, Receiver};
use std::time::Duration;

use notify::{RecommendedWatcher, RecursiveMode, Watcher as _};

/// What happened in a content directory.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Change {
    /// The content file itself was written, replaced, or removed. The
    /// write-back trigger.
    Content,
    /// Something the target application made appeared beside it.
    SiblingAppeared,
    /// Something it had made went away.
    SiblingWentAway,
}

/// What an event in the content directory means, given the content file's name.
///
/// Pure, so the rule is testable without a filesystem or a race. Paths are
/// compared by their final component: `notify` reports absolute paths, and a
/// rename within the directory arrives as paths that differ only there.
///
/// A rename over the content file produces events naming both the temporary
/// sibling and the content file, and both are worth reporting — the first says
/// the application is working, the second is the save.
#[must_use]
pub fn classify(content_name: &str, paths: &[&Path], kind: EventKind) -> Vec<Change> {
    paths
        .iter()
        .map(|p| {
            let is_content = p.file_name().is_some_and(|n| n == content_name);
            match (is_content, kind) {
                (true, _) => Change::Content,
                (false, EventKind::Gone) => Change::SiblingWentAway,
                (false, _) => Change::SiblingAppeared,
            }
        })
        .collect()
}

/// The shape of an event, reduced to what the rule above needs.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EventKind {
    /// Created, written, or renamed into place.
    Touched,
    /// Removed, or renamed away.
    Gone,
}

impl EventKind {
    /// Reduce one of `notify`'s events, or discard it.
    ///
    /// **Reading a file is not changing it.** A plain read of the watched
    /// content file emits `Access(Open(Any))` on Linux — measured on
    /// 2026-08-30 — and treating that as a save makes every reader of the
    /// content file a source of spurious write-backs. Anything that reads it
    /// counts: the write-back itself opens the content file, and so does
    /// `recover::state`, which is called once per session by `sessions`.
    /// Running `sessions` in a loop beside an open session produced a repack
    /// per poll before this arm existed.
    ///
    /// The repacks are invisible from outside, which is why this is a rule and
    /// a test rather than something anyone would notice: each one writes the
    /// same bytes, so the container stays right and only the work is wrong.
    ///
    /// The exception is a close after writing, which is the one access event
    /// that means a save finished. Linux reports it and the other platforms do
    /// not, so it is a signal to take where it is offered rather than one to
    /// depend on.
    ///
    /// `Any` and `Other` stay a touch. An unrecognised event in this directory
    /// is still something happening in it, and the cost of treating one as a
    /// save is a repack that writes what is already there.
    fn of(kind: notify::EventKind) -> Option<Self> {
        use notify::event::{AccessKind, AccessMode, ModifyKind, RenameMode};
        match kind {
            // A removal, and the half of a rename that names where the file
            // was. The other half names where it went, which is a touch.
            notify::EventKind::Remove(_)
            | notify::EventKind::Modify(ModifyKind::Name(RenameMode::From)) => Some(Self::Gone),
            notify::EventKind::Access(AccessKind::Close(AccessMode::Write)) => Some(Self::Touched),
            notify::EventKind::Access(_) => None,
            _ => Some(Self::Touched),
        }
    }
}

/// A watch on one content directory.
///
/// Holds the platform watcher, which stops when this is dropped.
pub struct Watch {
    /// `Option` so [`Drop`] can drop the watcher and *then* wait for the
    /// platform to finish stopping it.
    watcher: Option<RecommendedWatcher>,
    changes: Receiver<Change>,
    /// Where Windows reports that a watch has finished stopping.
    ///
    /// `notify`'s own constructor throws this receiver away, which is why the
    /// stop is unobservable through the ordinary API and why this builds the
    /// watcher the long way round. [`Drop`] says what it is for.
    #[cfg(windows)]
    stopped: Receiver<notify::windows::MetaEvent>,
}

/// How long [`Watch::drop`] will wait for a stop to finish.
///
/// A stop that has gone wrong should not become a hang of its own, which is
/// the defect this is here to avoid rather than to relocate. A stop that is
/// working takes microseconds, so a wait this long is only ever paid by one
/// that is not.
#[cfg(windows)]
const STOP_WAIT: Duration = Duration::from_secs(5);

impl Watch {
    /// Watch `dir` for changes to `content_name` and to anything beside it.
    ///
    /// Non-recursive: the content directory has no subdirectories of this
    /// tool's making, and an application that creates one has still created a
    /// sibling, which is the signal either way.
    ///
    /// # Errors
    ///
    /// Where the platform watcher cannot be created or cannot watch `dir`.
    pub fn on(dir: &Path, content_name: &str) -> notify::Result<Self> {
        let (tx, changes) = mpsc::channel();
        let content_name = content_name.to_string();
        let handler = move |event: notify::Result<notify::Event>| {
            let Ok(event) = event else {
                // A dropped or errored event is not a reason to tear down the
                // watch. Concept 6.2 exists because detection is unreliable,
                // and the session close is the backstop for everything this
                // misses.
                return;
            };
            let Some(kind) = EventKind::of(event.kind) else {
                return;
            };
            let paths: Vec<&Path> = event.paths.iter().map(AsRef::as_ref).collect();
            for change in classify(&content_name, &paths, kind) {
                // A closed receiver means the session is gone and there is
                // nobody to tell.
                if tx.send(change).is_err() {
                    return;
                }
            }
        };

        // On Windows the watcher is built through `create` rather than
        // `recommended_watcher`, for the one thing `recommended_watcher` throws
        // away: the channel the backend reports `SingleWatchComplete` on.
        // Without it a stop cannot be waited for, and `Drop` has to be able to
        // wait. Everywhere else the ordinary constructor is right.
        #[cfg(windows)]
        let (mut watcher, stopped) = {
            let (meta_tx, stopped) = mpsc::channel();
            let handler: std::sync::Arc<std::sync::Mutex<dyn notify::EventHandler>> =
                std::sync::Arc::new(std::sync::Mutex::new(handler));
            let watcher = notify::windows::ReadDirectoryChangesWatcher::create(handler, meta_tx)?;
            (watcher, stopped)
        };
        #[cfg(not(windows))]
        let mut watcher = notify::recommended_watcher(handler)?;

        watcher.watch(dir, RecursiveMode::NonRecursive)?;
        Ok(Self {
            watcher: Some(watcher),
            changes,
            #[cfg(windows)]
            stopped,
        })
    }

    /// Every change that has arrived, without waiting.
    pub fn drain(&self) -> impl Iterator<Item = Change> + '_ {
        self.changes.try_iter()
    }

    /// Wait up to `within` for the next change.
    #[must_use]
    pub fn next_change(&self, within: Duration) -> Option<Change> {
        self.changes.recv_timeout(within).ok()
    }
}

/// Whether the target application has anything of its own in the content
/// directory.
///
/// Asked of the directory rather than tracked from events, because events can
/// be missed and the answer has to be right at the moment somebody is deciding
/// whether to close a session (concept 6.2).
///
/// # Errors
///
/// Where the directory cannot be read.
pub fn siblings_present(dir: &Path, content_name: &str) -> std::io::Result<bool> {
    for entry in std::fs::read_dir(dir)? {
        if entry?.file_name() != *content_name {
            return Ok(true);
        }
    }
    Ok(false)
}

/// **The stop is waited for, and this is the fix for a measured hang.**
///
/// `notify`'s watcher drop is fire-and-forget: it posts `Action::Stop`, wakes
/// its server thread and returns, leaving that thread inside `stop_watch`.
/// Whatever removes the watched directory next therefore races a watch that is
/// still stopping, and on Windows that pair deadlocks — `stop_watch` waits
/// `INFINITE` for a semaphore its own completion routine does not post when it
/// re-arms `ReadDirectoryChangesW`, and the re-armed read does not return while
/// a `remove_dir_all` is walking the same directory.
///
/// Measured 2026-09-07 before this existed: a diagnostic that drops a watch and
/// then removes the directory wedged 9 runs in 20, one instance parked with
/// zero CPU for over ten minutes; `Opened::close`, which removes first and
/// drops after, wedged past a 300-second timeout with the same two stacks.
/// `docs/windows-save-test-hang.md` has both, and the ordering alone was never
/// the cure: the 9-in-20 case already dropped the watch first.
///
/// So the watcher goes, and then this waits for the backend to say the watch
/// has actually stopped, which is the guarantee the caller needs before
/// removing anything. [`STOP_WAIT`] bounds the wait so that a stop which never
/// finishes is a delay rather than a second hang.
impl Drop for Watch {
    fn drop(&mut self) {
        drop(self.watcher.take());

        #[cfg(windows)]
        {
            // The same channel carries `WatcherAwakened`, so this reads until
            // the completion it wants, the sender goes, or the clock runs out.
            let deadline = std::time::Instant::now() + STOP_WAIT;
            loop {
                let left = deadline.saturating_duration_since(std::time::Instant::now());
                if left.is_zero() {
                    break;
                }
                match self.stopped.recv_timeout(left) {
                    Ok(notify::windows::MetaEvent::SingleWatchComplete) | Err(_) => break,
                    Ok(_) => {}
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::{classify, siblings_present, Change, EventKind, Watch};
    use std::path::{Path, PathBuf};
    use std::time::Duration;

    fn at(names: &[&str]) -> Vec<PathBuf> {
        names
            .iter()
            .map(|n| Path::new("/s/content").join(n))
            .collect()
    }

    fn refs(paths: &[PathBuf]) -> Vec<&Path> {
        paths.iter().map(AsRef::as_ref).collect()
    }

    #[test]
    fn writing_the_content_file_is_the_write_back_trigger() {
        let p = at(&["report.pdf"]);
        assert_eq!(
            classify("report.pdf", &refs(&p), EventKind::Touched),
            [Change::Content]
        );
    }

    #[test]
    fn anything_else_appearing_is_the_application_working() {
        // No table of lock file conventions. The directory held one file, this
        // tool put it there, so whatever this is came from the editor.
        for name in [
            "~$report.docx",
            ".~lock.report.pdf#",
            "report.pdf.tmp",
            "4919",
        ] {
            let p = at(&[name]);
            assert_eq!(
                classify("report.pdf", &refs(&p), EventKind::Touched),
                [Change::SiblingAppeared],
                "{name}"
            );
        }
    }

    #[test]
    fn a_sibling_going_away_is_the_application_finishing() {
        let p = at(&["~$report.docx"]);
        assert_eq!(
            classify("report.pdf", &refs(&p), EventKind::Gone),
            [Change::SiblingWentAway]
        );
    }

    #[test]
    fn the_content_file_going_away_is_still_the_content_file() {
        // A rename over it arrives as the content file being replaced, and an
        // application that deletes and rewrites is doing a save in two steps.
        // Either way the container should be asked to catch up.
        let p = at(&["report.pdf"]);
        assert_eq!(
            classify("report.pdf", &refs(&p), EventKind::Gone),
            [Change::Content]
        );
    }

    #[test]
    fn a_rename_naming_both_paths_reports_both() {
        // The atomic save: a temporary sibling renamed over the target. The
        // sibling says the application is working and the content file is the
        // save, and dropping either would lose one of the two things the watch
        // is for.
        let p = at(&["report.pdf.tmp", "report.pdf"]);
        assert_eq!(
            classify("report.pdf", &refs(&p), EventKind::Touched),
            [Change::SiblingAppeared, Change::Content]
        );
    }

    #[test]
    fn a_content_file_named_like_a_lock_file_is_still_the_content_file() {
        // SPEC 2.3 permits any plain filename. Matching by name and not by
        // shape is what keeps this true.
        let p = at(&["~$report.docx"]);
        assert_eq!(
            classify("~$report.docx", &refs(&p), EventKind::Touched),
            [Change::Content]
        );
    }

    #[test]
    fn siblings_are_asked_of_the_directory_rather_than_remembered() {
        let tmp = tempfile::tempdir().unwrap();
        std::fs::write(tmp.path().join("report.pdf"), b"x").unwrap();
        assert!(!siblings_present(tmp.path(), "report.pdf").unwrap());

        std::fs::write(tmp.path().join("~$report.pdf"), b"").unwrap();
        assert!(siblings_present(tmp.path(), "report.pdf").unwrap());

        std::fs::remove_file(tmp.path().join("~$report.pdf")).unwrap();
        assert!(!siblings_present(tmp.path(), "report.pdf").unwrap());
    }

    #[test]
    fn reading_the_content_file_is_not_a_change_to_it() {
        // Write-back opens the content file to read it, which inotify reports
        // as an access on the watched file. Treating that as a save makes the
        // write-back its own trigger: measured on 2026-08-30, one edit produced
        // three repacks and would have produced more had the session stayed
        // open.
        //
        // **The read has to be told apart from the setup, and only after the
        // watch is quiet.** FSEvents is path-based and replays: registering a
        // watch delivers the events that just happened to the directory,
        // including the tempdir appearing and the `write` below, at the
        // platform's own latency rather than before this returns. Measured on
        // an Apple silicon runner 2026-09-07, the third run in a loop: the
        // setup arrived as `[SiblingAppeared, Content, Content]` inside the
        // window and read as the read. inotify and ReadDirectoryChangesW
        // deliver only what follows registration and never showed it. So the
        // watch is drained until it goes quiet, which absorbs the replay on
        // every platform, and only what the read then produces is measured —
        // which is nothing: probed five times on that platform, a settled read
        // produced no `Content`, because a read is `Access` and `EventKind::of`
        // discards it. The earlier version had no settle and asserted against
        // the whole window, so it was measuring the notifier.
        let tmp = tempfile::tempdir().unwrap();
        let content_path = tmp.path().join("report.pdf");
        std::fs::write(&content_path, b"first").unwrap();

        let watch = Watch::on(tmp.path(), "report.pdf").unwrap();

        // Quiet is nothing for 400ms, capped so a notifier that never falls
        // silent cannot hang the suite. The replay is what is being waited out.
        let cap = std::time::Instant::now() + Duration::from_secs(5);
        while watch.next_change(Duration::from_millis(400)).is_some()
            && std::time::Instant::now() < cap
        {}

        let _ = std::fs::read(&content_path).unwrap();

        let deadline = std::time::Instant::now() + Duration::from_secs(2);
        let mut seen = Vec::new();
        while std::time::Instant::now() < deadline {
            if let Some(c) = watch.next_change(Duration::from_millis(100)) {
                seen.push(c);
            }
        }
        assert!(
            !seen.contains(&Change::Content),
            "reading the content file was reported as a change: {seen:?}"
        );
    }

    #[test]
    fn a_real_atomic_save_reaches_the_watch() {
        // The one test that goes through the platform. It saves the way a
        // serious editor does — write a temporary sibling, rename over the
        // target — which is the case a watch registered on the file would miss
        // entirely.
        let tmp = tempfile::tempdir().unwrap();
        let content_path = tmp.path().join("report.pdf");
        std::fs::write(&content_path, b"first").unwrap();

        let watch = Watch::on(tmp.path(), "report.pdf").unwrap();

        let scratch = tmp.path().join("report.pdf.tmp");
        std::fs::write(&scratch, b"second").unwrap();
        std::fs::rename(&scratch, &content_path).unwrap();

        // Generously, because this is at the platform's pace and not ours.
        let mut seen = Vec::new();
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        while std::time::Instant::now() < deadline && !seen.contains(&Change::Content) {
            if let Some(c) = watch.next_change(Duration::from_millis(250)) {
                seen.push(c);
            }
        }
        assert!(
            seen.contains(&Change::Content),
            "the save never arrived: {seen:?}"
        );
        assert_eq!(std::fs::read(&content_path).unwrap(), b"second");
    }
}