crisol-core 1.3.0

Crisol core: an egui-free data model, themes, metrics, localization, commands, state, and storage.
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
//! The append-only command journal and macros recorded from it.
//!
//! Every dispatched command can be appended with its arguments and a timestamp. A
//! recorded range becomes a named macro; replaying the same `(command, args)` sequence
//! is deterministic, so a recorded session doubles as a regression test.
//!
//! ```
//! use crisol_core::state::journal;
//! ```

#[cfg(feature = "threads")]
use std::path::Path;

use serde_json::Value;

use crate::commands::{Command, CommandId, CommandRegistry};

/// One recorded command.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::JournalEntry;
/// ```
pub struct JournalEntry {
    /// Monotonic sequence number, starting at 1.
    pub sequence: u64,
    /// Seconds on the application clock (or Unix time).
    pub timestamp: f64,
    /// The command that ran.
    pub command: CommandId,
    /// Arguments, if the command has any.
    pub args: Option<Value>,
    /// A human label for the journal view.
    pub label: Option<String>,
}

impl JournalEntry {
    /// The command id and its arguments.
    pub fn command(&self) -> &CommandId {
        &self.command
    }

    /// The argument value.
    pub fn args(&self) -> Option<&Value> {
        self.args.as_ref()
    }
}

/// A versioned, append-only journal.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::CommandJournal;
/// ```
pub struct CommandJournal {
    /// File format version. Currently 1.
    pub version: u32,
    /// The entries, oldest first.
    pub entries: Vec<JournalEntry>,
    next_sequence: u64,
}

impl Default for CommandJournal {
    fn default() -> Self {
        Self::new()
    }
}

impl CommandJournal {
    /// The current file version.
    pub const VERSION: u32 = 1;

    /// An empty journal.
    pub fn new() -> Self {
        Self {
            version: Self::VERSION,
            entries: Vec::new(),
            next_sequence: 1,
        }
    }

    /// Export the journal as a Python replay script.
    pub fn export_python(&self) -> String {
        let mut script = String::from("# Generated by crisol: replay this journal headlessly.\n");
        for entry in &self.entries {
            let id = entry.command.as_str().replace('\\', "\\\\").replace('"', "\\\"");
            match &entry.args {
                Some(args) => {
                    script.push_str(&format!("run(\"{id}\", {args})\n"));
                }
                None => script.push_str(&format!("run(\"{id}\")\n")),
            }
        }
        script
    }

    /// Export the journal as a Rust replay array.
    pub fn export_rust(&self) -> String {
        let mut out = String::from("// Generated by crisol: replay this journal.\n");
        out.push_str("let commands = [\n");
        for entry in &self.entries {
            out.push_str(&format!("    \"{}\",\n", entry.command.as_str()));
        }
        out.push_str("];\n");
        out
    }

    /// Append a command with no arguments.
    pub fn append(&mut self, command: impl Into<CommandId>) -> &JournalEntry {
        self.append_at(0.0, command, None, None)
    }

    /// Append a command with arguments.
    pub fn append_with(
        &mut self,
        command: impl Into<CommandId>,
        args: Value,
        label: impl Into<String>,
    ) -> &JournalEntry {
        self.append_at(0.0, command, Some(args), Some(label.into()))
    }

    /// Append a command with an explicit timestamp.
    pub fn append_at(
        &mut self,
        timestamp: f64,
        command: impl Into<CommandId>,
        args: Option<Value>,
        label: Option<String>,
    ) -> &JournalEntry {
        let sequence = self.next_sequence;
        self.next_sequence += 1;
        self.entries.push(JournalEntry {
            sequence,
            timestamp,
            command: command.into(),
            args,
            label,
        });
        // Just pushed; the journal never removes entries outside `clear`.
        #[allow(clippy::indexing_slicing)]
        &self.entries[self.entries.len() - 1]
    }

    /// The entries.
    pub fn entries(&self) -> &[JournalEntry] {
        &self.entries
    }

    /// Number of entries.
    pub fn len(&self) -> usize {
        self.entries.len()
    }

    /// Whether the journal is empty.
    pub fn is_empty(&self) -> bool {
        self.entries.is_empty()
    }

    /// The newest entry.
    pub fn last(&self) -> Option<&JournalEntry> {
        self.entries.last()
    }

    /// Entries with a sequence greater than `sequence`.
    pub fn since(&self, sequence: u64) -> &[JournalEntry] {
        let start = self.entries.partition_point(|entry| entry.sequence <= sequence);
        self.entries.get(start..).unwrap_or_default()
    }

    /// Remove every entry and reset the sequence.
    pub fn clear(&mut self) {
        self.entries.clear();
        self.next_sequence = 1;
    }

    /// Serialize the journal as pretty JSON.
    ///
    /// # Errors
    /// When serialization fails (it does not for these types).
    pub fn to_json(&self) -> Result<String, JournalError> {
        serde_json::to_string_pretty(self).map_err(|error| JournalError::Json(error.to_string()))
    }

    /// Parse a journal, rejecting a newer version.
    ///
    /// # Errors
    /// When the JSON is malformed or the version is newer than [`Self::VERSION`].
    pub fn from_json(json: &str) -> Result<Self, JournalError> {
        let journal: Self = serde_json::from_str(json).map_err(|error| JournalError::Json(error.to_string()))?;
        if journal.version > Self::VERSION {
            return Err(JournalError::UnsupportedVersion(journal.version));
        }
        Ok(journal)
    }

    /// Write the journal atomically.
    ///
    /// # Errors
    /// When serialization or the write fails.
    #[cfg(feature = "threads")]
    pub fn save(&self, path: impl AsRef<Path>) -> Result<(), JournalError> {
        let json = self.to_json()?;
        crate::storage::atomic_write(path.as_ref(), json.as_bytes())
            .map_err(|error| JournalError::Io(error.to_string()))
    }

    /// Read a journal from disk.
    ///
    /// # Errors
    /// When the file cannot be read or parsed.
    #[cfg(feature = "threads")]
    pub fn load(path: impl AsRef<Path>) -> Result<Self, JournalError> {
        let text = std::fs::read_to_string(path).map_err(|error| JournalError::Io(error.to_string()))?;
        Self::from_json(&text)
    }
}

/// A named sequence of journal entries.
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::Macro;
/// ```
pub struct Macro {
    /// Display name.
    pub name: String,
    /// The registry id a macro is registered under.
    pub command: CommandId,
    /// The steps, in order.
    pub steps: Vec<JournalEntry>,
}

impl Macro {
    /// Replay the steps through `run`. The function receives each step's command and
    /// arguments in the recorded order; no window or clock is involved.
    pub fn replay(&self, mut run: impl FnMut(&JournalEntry)) {
        for step in &self.steps {
            run(step);
        }
    }

    /// A registry id from a macro name, such as `macro.align-and-fit`.
    pub fn command_id(name: &str) -> CommandId {
        let slug: String = name
            .chars()
            .map(|character| {
                if character.is_ascii_alphanumeric() {
                    character.to_ascii_lowercase()
                } else {
                    '-'
                }
            })
            .collect();
        let slug = slug.trim_matches('-');
        CommandId::new(format!("macro.{}", if slug.is_empty() { "untitled" } else { slug }))
    }
}

/// The named macros, versioned for the workspace file.
#[derive(Clone, Debug, Default, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::MacroLibrary;
/// ```
pub struct MacroLibrary {
    /// File format version.
    pub version: u32,
    /// The macros.
    pub macros: Vec<Macro>,
}

impl MacroLibrary {
    /// The current file version.
    pub const VERSION: u32 = 1;

    /// An empty library.
    pub fn new() -> Self {
        Self {
            version: Self::VERSION,
            macros: Vec::new(),
        }
    }

    /// Record the entries after `after_sequence` as a new macro and return it.
    pub fn record_from(&mut self, journal: &CommandJournal, after_sequence: u64, name: impl Into<String>) -> &Macro {
        let name = name.into();
        let steps = journal.since(after_sequence).to_vec();
        let command = Macro::command_id(&name);
        self.macros.push(Macro { name, command, steps });
        // Just pushed.
        #[allow(clippy::indexing_slicing)]
        &self.macros[self.macros.len() - 1]
    }

    /// Add an existing macro.
    pub fn add(&mut self, macro_: Macro) {
        self.macros.push(macro_);
    }

    /// The macros.
    pub fn iter(&self) -> impl Iterator<Item = &Macro> {
        self.macros.iter()
    }

    /// A macro by name.
    pub fn get(&self, name: &str) -> Option<&Macro> {
        self.macros.iter().find(|macro_| macro_.name == name)
    }

    /// A macro by its command id.
    pub fn by_command(&self, command: &CommandId) -> Option<&Macro> {
        self.macros.iter().find(|macro_| &macro_.command == command)
    }

    /// Register every macro as a command in `registry`.
    pub fn register(&self, registry: &mut CommandRegistry) {
        for macro_ in &self.macros {
            registry.register(
                Command::new(macro_.command.clone(), format!("Run macro: {}", macro_.name))
                    .category("Macros")
                    .description(format!("{} recorded steps", macro_.steps.len())),
            );
        }
    }
}

/// Why a journal file could not be read or written.
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
/// # Example
///
/// ```
/// use crisol_core::state::JournalError;
/// ```
pub enum JournalError {
    /// The JSON is malformed.
    #[error("invalid journal JSON: {0}")]
    Json(String),
    /// The file version is newer than this crate understands.
    #[error("unsupported journal version {0}")]
    UnsupportedVersion(u32),
    /// The file could not be read or written.
    #[error("{0}")]
    Io(String),
}

#[cfg(all(test, feature = "threads"))]
mod tests {
    use super::*;

    #[test]
    fn entries_are_append_only_and_sequenced() {
        let mut journal = CommandJournal::new();
        journal.append_at(1.0, "file.new", None, Some("New".to_owned()));
        journal.append_with("file.save", Value::from(1), "Save");
        assert_eq!(journal.len(), 2);
        assert_eq!(journal.last().map(|entry| entry.sequence), Some(2));
        assert_eq!(journal.since(1).len(), 1);
        assert_eq!(journal.since(0).len(), 2);
        assert!(journal.last().and_then(JournalEntry::args).is_some());
    }

    #[test]
    fn a_macro_replays_the_recorded_commands() {
        let mut journal = CommandJournal::new();
        journal.append("file.new");
        journal.append("edit.type");
        let mut library = MacroLibrary::new();
        let macro_ = library.record_from(&journal, 1, "New and type").clone();
        assert_eq!(macro_.steps.len(), 1);
        let mut replayed = Vec::new();
        macro_.replay(|step| replayed.push(step.command.to_string()));
        assert_eq!(replayed, ["edit.type"]);
        assert_eq!(macro_.command.to_string(), "macro.new-and-type");
    }

    #[test]
    fn registered_macros_are_commands() {
        let mut journal = CommandJournal::new();
        journal.append("file.new");
        let mut library = MacroLibrary::new();
        library.record_from(&journal, 0, "New");
        let mut registry = CommandRegistry::new();
        library.register(&mut registry);
        assert!(registry.get(&Macro::command_id("New")).is_some());
    }

    #[test]
    fn the_journal_round_trips_and_rejects_a_newer_version() {
        let mut journal = CommandJournal::new();
        journal.append_with("file.save", Value::from("a.rs"), "Save");
        let json = journal.to_json().expect("serialize");
        let back = CommandJournal::from_json(&json).expect("parse");
        assert_eq!(back, journal);
        let newer = json.replace("\"version\": 1", "\"version\": 9");
        assert!(matches!(
            CommandJournal::from_json(&newer),
            Err(JournalError::UnsupportedVersion(9))
        ));
    }

    #[test]
    fn macros_round_trip_through_json() {
        let mut journal = CommandJournal::new();
        journal.append("file.new");
        let mut library = MacroLibrary::new();
        library.record_from(&journal, 0, "New");
        let json = serde_json::to_string(&library).expect("serialize");
        let back: MacroLibrary = serde_json::from_str(&json).expect("deserialize");
        assert_eq!(back, library);
    }
}

#[cfg(test)]
mod export_tests {
    use super::*;

    #[test]
    fn the_journal_exports_python_and_rust() {
        let mut journal = CommandJournal::new();
        journal.append("file.save");
        journal.append("edit.paste");
        let python = journal.export_python();
        let rust = journal.export_rust();
        assert!(python.contains("run(\"file.save\")"));
        assert!(rust.contains("\"edit.paste\""));
    }
}