sprawling-wire 0.0.12

The process boundary of a sprawling city: the frames its clients speak, and the server that answers them.
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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at https://mozilla.org/MPL/2.0/.
// Copyright (c) 2026 2youg1 and the sprawling contributors

//! What one person settled about their own copy of the city: the
//! language they read, how the pages look, and the chords they rebound.
//!
//! **These are the person's layer, not the city's.** They live in
//! `~/.sprawling/config.toml` beside the components that are already
//! tied to this machine, they change nothing a run can observe, and
//! they are answered whole by [`Query::Preferences`](crate::Query) and
//! changed one named fact at a time by
//! [`Command::PutPreferences`](crate::Command).
//!
//! **Every value set a selector offers is declared once, here.** A
//! browser holding its own list of the words it would accept would keep
//! an option the city stopped offering pickable until somebody noticed;
//! the client reads these enums out of the generated schema, so an
//! option it can draw is an option this build can load.
//!
//! One named change per fact rather than one whole-record write: two
//! screens that each settle one thing must not be able to overwrite
//! each other's field on the way past.

use std::collections::BTreeMap;

use serde::{Deserialize, Serialize};

mod core;
pub use core::{CorePlacement, CorePreferences, CorePriority};

mod body;
pub use body::{BODY_PX_MIN, BodyPx};

mod tag;
pub use tag::{SessionTags, TAG_MAX, Tag};

/// Which language a person reads the interface in.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Lang {
    En,
    Zh,
}

/// Which palette the pages are drawn in. `System` is the absence of an
/// opinion, resolved where the page is drawn rather than in the
/// stylesheet: the light palette is declared once, and a second
/// declaration of it inside a `prefers-color-scheme` block would be a
/// second authority for the same rungs.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Lighting {
    System,
    Dark,
    Light,
}

/// Where one of the two typefaces comes from.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Face {
    /// The family this build ships.
    Geist,
    /// Whatever this machine calls its interface font.
    System,
    /// The stack the person wrote out.
    Custom,
}

/// Which face reading text is drawn in: the messages of a conversation,
/// documents and reports. Controls, labels, figures and code keep the
/// interface's faces whichever this says
/// (`crates/wire/spec/Preference.lean` D52).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum ReadingFace {
    /// The face the interface is drawn in, whichever [`Face`] that is.
    Interface,
    /// Libron, the serif face this build ships for reading.
    Libron,
}

/// How much air the spacing steps carry. Two named postures rather than
/// a coefficient, because the coefficient is the stylesheet's to
/// choose.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Density {
    Comfortable,
    Compact,
}

/// Whether colour carries meaning on these pages, or only contrast
/// does.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Chroma {
    Full,
    Off,
}

/// Whether the pages animate. `System` is the absence of an opinion,
/// which is what the stylesheet's `prefers-reduced-motion` block reads.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Motion {
    System,
    On,
    Off,
}

/// Whether the edge layer's small surfaces are drawn as glass. `On`
/// still yields to a machine that asks for less transparency, which
/// only some engines report: that gap is why the switch exists.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Glass {
    On,
    Off,
}

/// How much of the world layer the page draws: none of it, whole panels
/// beside the conversation, or all of it as the workspace with the
/// conversation as a band along its foot. Three layouts rather than
/// three points on one slider, so three names.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum Tier {
    Zen,
    Blend,
    Panorama,
}

/// How the pages look.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Appearance {
    pub lighting: Lighting,
    pub sans: Face,
    pub mono: Face,
    /// The families this person wrote out, used when the matching
    /// [`Face`] is [`Face::Custom`] and empty otherwise.
    pub sans_stack: String,
    /// See `sans_stack`.
    pub mono_stack: String,
    /// Absent means the person stated no opinion and reading text is
    /// drawn in the interface's face.
    #[serde(default)]
    pub reading: Option<ReadingFace>,
    /// The size of a line of body text in pixels, at least
    /// [`BODY_PX_MIN`]. Absent means the person
    /// stated no size and the stylesheet's own is drawn — which is a
    /// different statement from any number this build could pick for
    /// them.
    pub body_px: Option<BodyPx>,
    pub density: Density,
    pub chroma: Chroma,
    pub motion: Motion,
    /// Absent means the person stated no opinion and the page draws
    /// its own posture.
    #[serde(default)]
    pub glass: Option<Glass>,
    /// The world layer's opacity in the blend tier, in percent. Absent
    /// means the stylesheet's own is drawn. The domain the slider
    /// offers is the page's to state, because the page alone draws it;
    /// a value outside it is read back as absent there.
    #[serde(default)]
    pub blend_percent: Option<u32>,
}

/// One chord the person rebound: the action, and the chord as the
/// keymap spells it.
///
/// An action left at the chord this build ships has no entry, so the
/// list says what was changed rather than what the keymap holds.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct Chord {
    pub action: String,
    pub spelled: String,
}

/// Everything one person settled about their own copy of the city.
///
/// Whole rather than a dozen readings, because that is the record the
/// file holds and because a screen that changes two of these at once
/// must not be able to write one and drop the other.
///
/// **This is the grammar of `[ui]` in the person's own file as well as
/// the shape of the answer.** The file is read through this type and
/// written by serialising it, so a key the file may hold and a field
/// the answer states are one declaration. A section that states only
/// some of them is read with the rest at the postures
/// [`PreferencesAnswer::default`] gives, and a key no field claims is
/// refused where it is written rather than ignored into a setting that
/// never takes effect.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct PreferencesAnswer {
    /// The language this person reads the interface in, and nothing
    /// when they have never said.
    ///
    /// Absent rather than a language this build picked for them: the
    /// browser's own tag is the only evidence anybody has before the
    /// first choice, and a stated `en` here would overrule it on every
    /// machine whose owner simply never opened the setting.
    pub lang: Option<Lang>,
    /// Performance settings read from `[core]`, never stored in `[ui]`.
    pub core: CorePreferences,
    /// Whether this person has walked through the welcome once. The
    /// city decides whether setting up is *needed*; this only decides
    /// whether somebody who skipped it is asked again.
    pub welcomed: bool,
    /// Whether the panel beside a conversation is open.
    pub panel: bool,
    /// The tier this person last chose, and nothing when they never
    /// chose one: the tier a first visit opens in is the page's posture,
    /// and a stated tier here would overrule it on every machine whose
    /// owner never pressed the key.
    pub tier: Option<Tier>,
    pub appearance: Appearance,
    /// Which proxy rule an endpoint attached from now on starts with.
    /// An endpoint already attached keeps the rule the city recorded
    /// for it.
    pub proxying: kernel::Proxying,
    /// The chords this person rebound, action order.
    pub chords: Vec<Chord>,
    /// The tags this person gave sessions, in session order
    /// (`crates/wire/spec/Preference.lean` §8-84).
    pub tags: Vec<SessionTags>,
    /// The person's colours laid over the built-in theme
    /// (`crates/wire/spec/Preference.lean` D29).
    pub theme: ThemeOverride,
}

/// Colours laid over the theme the page ships with. The empty value is
/// the built-in theme.
///
/// The values are CSS, and the city does not parse them: the page owns
/// both the theme and the stylesheet that reads it, and checks the keys
/// against the `@theme` block and the legibility of the result.
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, deny_unknown_fields)]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub struct ThemeOverride {
    /// A CSS variable of the `@theme` block in `client/src/theme.css`,
    /// mapped to the CSS colour that replaces it.
    pub tokens: BTreeMap<String, String>,
    /// A whole stylesheet the person wrote, laid after the tokens.
    pub css: Option<String>,
}

/// What a person who has settled nothing is answered.
///
/// The postures this build draws before anybody chooses, stated once
/// for the file's reader and the answer's reader together. `panel` is
/// the one that is not its type's own default: the panel beside a
/// conversation is open until somebody closes it, so an unwritten file
/// has to say `true` where `welcomed` says `false`.
impl Default for PreferencesAnswer {
    fn default() -> Self {
        PreferencesAnswer {
            lang: None,
            core: CorePreferences::default(),
            welcomed: false,
            panel: true,
            tier: None,
            appearance: Appearance::default(),
            proxying: kernel::Proxying::ExceptLocal,
            chords: Vec::new(),
            tags: Vec::new(),
            theme: ThemeOverride::default(),
        }
    }
}

impl Default for Appearance {
    fn default() -> Self {
        Appearance {
            lighting: Lighting::System,
            sans: Face::Geist,
            mono: Face::Geist,
            sans_stack: String::new(),
            mono_stack: String::new(),
            reading: None,
            body_px: None,
            density: Density::Comfortable,
            chroma: Chroma::Full,
            motion: Motion::System,
            glass: None,
            blend_percent: None,
        }
    }
}

impl PreferencesAnswer {
    /// Lands one named change on this record.
    ///
    /// Here rather than at the file: what a patch means is the patch's
    /// own rule, and a second application of it — in the store, in a
    /// test, in whatever keeps these next — would be a second answer
    /// to what `Chord("")` does.
    pub fn apply(&mut self, patch: PreferencePatch) {
        match patch {
            PreferencePatch::Lang(lang) => self.lang = Some(lang),
            PreferencePatch::Welcomed(welcomed) => self.welcomed = welcomed,
            PreferencePatch::Panel(panel) => self.panel = panel,
            PreferencePatch::Tier(tier) => self.tier = Some(tier),
            PreferencePatch::Appearance(appearance) => self.appearance = appearance,
            PreferencePatch::Proxying(proxying) => self.proxying = proxying,
            // The writer stores these separately from `[ui]`.
            PreferencePatch::CorePriority(priority) => self.core.priority = priority,
            PreferencePatch::CorePlacement(placement) => self.core.placement = placement,
            PreferencePatch::RunMemory(memory) => self.core.memory_bytes = memory,
            PreferencePatch::Tags(next) => tag::retagged(&mut self.tags, next),
            PreferencePatch::Theme(theme) => self.theme = theme,
            PreferencePatch::Chord(chord) => {
                self.chords.retain(|held| held.action != chord.action);
                // An empty spelling returns the action to the chord this
                // build ships, which `Chord` keeps no entry for.
                if !chord.spelled.is_empty() {
                    self.chords.push(chord);
                    // Action order, so two machines that rebound the
                    // same chords in a different order hold the same
                    // file.
                    self.chords.sort_by(|one, two| one.action.cmp(&two.action));
                }
            }
        }
    }
}

/// One named change to [`PreferencesAnswer`].
///
/// A closed set of named changes rather than a whole record, so two
/// screens settling different facts cannot overwrite each other, and so
/// a frame that names a fact this build does not keep is refused at the
/// boundary rather than merged.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
pub enum PreferencePatch {
    Lang(Lang),
    Welcomed(bool),
    Panel(bool),
    Tier(Tier),
    Appearance(Appearance),
    Proxying(kernel::Proxying),
    /// Rebind one action, or return it to the chord this build ships by
    /// sending an empty `spelled`.
    Chord(Chord),
    /// Whether the core's threads stand above normal. Lands in the
    /// file's `[core]` section, not in `[ui]` (`crates/wire/spec/Command/Step.lean` §8-61).
    CorePriority(CorePriority),
    CorePlacement(CorePlacement),
    RunMemory(Option<std::num::NonZeroU64>),
    /// Replace one session's tags with these; an empty set removes them
    /// (`crates/wire/spec/Preference.lean` §8-84).
    Tags(SessionTags),
    /// Replace the colour override; the empty value returns to the
    /// built-in theme (`crates/wire/spec/Preference.lean` D29).
    Theme(ThemeOverride),
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, reason = "test code")]
mod tests {
    use super::*;

    /// A patch names one fact. The test that matters is that the tag is
    /// the fact's name, because that tag is what the person's file and
    /// the client's call site are both written against.
    #[test]
    fn a_patch_travels_under_the_name_of_the_fact_it_changes() {
        let text = serde_json::to_string(&PreferencePatch::Lang(Lang::Zh)).unwrap();
        assert_eq!(text, r#"{"lang":"zh"}"#);
        let back: PreferencePatch = serde_json::from_str(&text).unwrap();
        assert_eq!(back, PreferencePatch::Lang(Lang::Zh));
    }

    /// No silent repair: a word no build offers is not turned into the
    /// posture the client ships with.
    #[test]
    fn a_word_no_build_offers_is_refused_rather_than_repaired() {
        assert!(serde_json::from_str::<Lighting>("\"sepia\"").is_err());
        assert!(serde_json::from_str::<PreferencePatch>(r#"{"lang":"fr"}"#).is_err());
    }

    /// Rebinding one action twice leaves one entry, and returning it
    /// to the shipped chord leaves none: the list states what was
    /// changed, so an action that appears twice would make the keymap
    /// depend on which entry it read last.
    #[test]
    fn an_action_is_bound_once_and_unbinding_it_removes_the_entry() {
        let mut held = PreferencesAnswer::default();
        let bind = |spelled: &str| {
            PreferencePatch::Chord(Chord {
                action: "go.city".to_owned(),
                spelled: spelled.to_owned(),
            })
        };
        held.apply(bind("accel+2"));
        held.apply(bind("accel+3"));
        assert_eq!(held.chords.len(), 1);
        assert_eq!(
            held.chords.first().map(|held| held.spelled.as_str()),
            Some("accel+3")
        );
        held.apply(bind(""));
        assert!(held.chords.is_empty());
    }

    /// A section that states one fact is read with the rest at the
    /// postures this build draws, and the panel is the one whose
    /// absence does not mean `false`.
    #[test]
    fn a_section_that_states_one_fact_leaves_the_others_at_their_posture() {
        let held: PreferencesAnswer = serde_json::from_str(r#"{"welcomed":true}"#).unwrap();
        assert!(held.welcomed);
        assert!(held.panel);
        assert_eq!(held.lang, None);
        assert_eq!(held.appearance, Appearance::default());
    }

    /// A section written before the page's glass, blend opacity and
    /// tier reached the city still reads, with the three absent: every
    /// person's file predates them.
    #[test]
    fn an_appearance_written_before_glass_and_blend_still_reads() {
        let held: PreferencesAnswer = serde_json::from_str(
            r#"{"appearance":{"lighting":"dark","sans":"geist","mono":"geist","sans_stack":"","mono_stack":"","body_px":null,"density":"compact","chroma":"full","motion":"system"}}"#,
        )
        .unwrap();
        assert_eq!(
            (
                held.tier,
                held.appearance.glass,
                held.appearance.blend_percent
            ),
            (None, None, None)
        );
        let mut chosen = held;
        chosen.apply(PreferencePatch::Tier(Tier::Panorama));
        assert_eq!(chosen.tier, Some(Tier::Panorama));
    }

    /// The body size has a floor and no ceiling (`crates/wire/spec/Preference.lean`
    /// D51): a size under the floor is refused where it is read, so the
    /// person's file and a frame meet the rule the page's box states,
    /// and any size above it reads back as the number it was.
    #[test]
    fn a_body_size_under_the_floor_is_refused_and_any_size_above_it_reads() {
        let appearance = |px: u32| {
            serde_json::json!({ "appearance": {
                "lighting": "dark", "sans": "geist", "mono": "geist",
                "sans_stack": "", "mono_stack": "", "body_px": px,
                "density": "compact", "chroma": "full", "motion": "system",
            }})
        };
        assert!(serde_json::from_value::<PreferencesAnswer>(appearance(11)).is_err());
        for px in [12, 24, 96] {
            let held: PreferencesAnswer = serde_json::from_value(appearance(px)).unwrap();
            assert_eq!(
                serde_json::to_value(&held)
                    .unwrap()
                    .pointer("/appearance/body_px"),
                Some(&serde_json::json!(px))
            );
        }
    }

    /// The reading face is the person's to state and absent until they
    /// do (`crates/wire/spec/Preference.lean` D52): a section that names
    /// it reads back the face it named, and one written before the
    /// field existed reads back as never stated.
    #[test]
    fn the_reading_face_reads_back_as_stated_and_absent_as_never_said() {
        let appearance = |reading: Option<&str>| {
            let mut stated = serde_json::json!({
                "lighting": "dark", "sans": "geist", "mono": "geist",
                "sans_stack": "", "mono_stack": "", "body_px": null,
                "density": "compact", "chroma": "full", "motion": "system",
            });
            if let (Some(face), Some(fields)) = (reading, stated.as_object_mut()) {
                fields.insert("reading".to_owned(), serde_json::json!(face));
            }
            serde_json::json!({ "appearance": stated })
        };
        let read_back = |reading: Option<&str>| {
            let held: PreferencesAnswer = serde_json::from_value(appearance(reading)).unwrap();
            serde_json::to_value(&held)
                .unwrap()
                .pointer("/appearance/reading")
                .cloned()
        };
        assert_eq!(
            [
                read_back(Some("libron")),
                read_back(Some("interface")),
                read_back(None)
            ],
            [
                Some(serde_json::json!("libron")),
                Some(serde_json::json!("interface")),
                Some(serde_json::Value::Null),
            ]
        );
        assert!(serde_json::from_value::<PreferencesAnswer>(appearance(Some("georgia"))).is_err());
    }

    /// A key this build does not read is refused where it is written.
    /// Ignoring it produces the one state nobody can diagnose: the
    /// setting is in the file, and nothing happens.
    #[test]
    fn a_key_no_field_claims_is_refused() {
        assert!(serde_json::from_str::<PreferencesAnswer>(r#"{"welcomd":true}"#).is_err());
    }
}