dais-core 0.2.0

Core types, command bus, and state machine for Dais
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
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
use std::collections::HashMap;
use std::path::{Path, PathBuf};

use serde::{Deserialize, Serialize};

use crate::state::TimerMode;

/// Top-level application configuration, loaded from TOML.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct Config {
    /// Window layout and monitor selection.
    pub display: DisplayConfig,
    /// Main presentation timer behavior.
    pub timer: TimerConfig,
    /// Laser pointer defaults.
    pub laser: LaserConfig,
    /// Spotlight overlay defaults.
    pub spotlight: SpotlightConfig,
    /// Freehand ink defaults.
    pub ink: InkConfig,
    /// Text box defaults.
    pub text_boxes: TextBoxConfig,
    /// Notes panel defaults.
    pub notes: NotesConfig,
    /// User keybindings, keyed by [`Action`](crate::keybindings::Action) config names.
    pub keybindings: HashMap<String, Vec<String>>,
    /// Clicker/remote profile configuration.
    pub clicker: ClickerConfig,
    /// Local HTTP remote-control API configuration.
    pub remote: RemoteConfig,
    /// Annotated export defaults.
    pub export: ExportConfig,
    /// Sidecar save format: `"dais"` or `"pdfpc"`.
    pub sidecar_format: String,
    /// Whether to persist per-slide timing data when saving sidecars.
    pub save_slide_timings: bool,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialConfig {
    display: Option<PartialDisplayConfig>,
    timer: Option<PartialTimerConfig>,
    laser: Option<PartialLaserConfig>,
    spotlight: Option<PartialSpotlightConfig>,
    ink: Option<PartialInkConfig>,
    text_boxes: Option<PartialTextBoxConfig>,
    notes: Option<PartialNotesConfig>,
    keybindings: Option<HashMap<String, Vec<String>>>,
    clicker: Option<PartialClickerConfig>,
    remote: Option<PartialRemoteConfig>,
    export: Option<PartialExportConfig>,
    sidecar_format: Option<String>,
    save_slide_timings: Option<bool>,
}

/// Display mode and monitor assignment.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct DisplayConfig {
    /// Display mode: "dual", "single", or "screen-share".
    pub mode: String,
    /// Single-monitor presentation surface: "hud" or "split".
    pub single_monitor_view: String,
    /// Audience monitor identifier or "auto".
    pub audience_monitor: String,
    /// Presenter monitor identifier or "auto".
    pub presenter_monitor: String,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialDisplayConfig {
    mode: Option<String>,
    single_monitor_view: Option<String>,
    audience_monitor: Option<String>,
    presenter_monitor: Option<String>,
}

/// Timer configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TimerConfig {
    /// "countdown" or "elapsed".
    pub mode: TimerMode,
    /// Timer duration in minutes. If omitted in elapsed mode, no limit is shown.
    pub duration_minutes: Option<u32>,
    /// Minutes remaining when warning color activates.
    pub warning_minutes: Option<u32>,
    /// Whether to show red when past duration.
    pub overrun_color: bool,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialTimerConfig {
    mode: Option<TimerMode>,
    duration_minutes: Option<OptionalU32Value>,
    warning_minutes: Option<OptionalU32Value>,
    overrun_color: Option<bool>,
}

#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(untagged)]
enum OptionalU32Value {
    Value(u32),
    Null(()),
}

impl OptionalU32Value {
    fn into_option(self) -> Option<u32> {
        match self {
            Self::Value(value) => Some(value),
            Self::Null(()) => None,
        }
    }
}

/// Laser pointer configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct LaserConfig {
    /// Default hex color string (e.g., "#FF0000") applied to all pointer styles unless overridden.
    pub color: String,
    /// Default size in logical pixels at 1x scale applied to all pointer styles unless overridden.
    pub size: f32,
    /// Style: "dot", "minimal", "crosshair", "arrow", "ring", "bullseye", or "highlight".
    pub style: String,
    /// Dot pointer appearance.
    pub dot: PointerStyleConfig,
    /// Minimal dot pointer appearance.
    pub minimal: PointerStyleConfig,
    /// Crosshair pointer appearance.
    pub crosshair: PointerStyleConfig,
    /// Arrow pointer appearance.
    pub arrow: PointerStyleConfig,
    /// Ring pointer appearance.
    pub ring: PointerStyleConfig,
    /// Bullseye pointer appearance.
    pub bullseye: PointerStyleConfig,
    /// Highlight pointer appearance.
    pub highlight: PointerStyleConfig,
}

/// Appearance configuration for one laser pointer style.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct PointerStyleConfig {
    /// Hex color string (e.g., "#FF0000" or "#FF000080").
    pub color: String,
    /// Size in logical pixels at 1x scale.
    pub size: f32,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialLaserConfig {
    color: Option<String>,
    size: Option<f32>,
    style: Option<String>,
    dot: Option<PartialPointerStyleConfig>,
    minimal: Option<PartialPointerStyleConfig>,
    crosshair: Option<PartialPointerStyleConfig>,
    arrow: Option<PartialPointerStyleConfig>,
    ring: Option<PartialPointerStyleConfig>,
    bullseye: Option<PartialPointerStyleConfig>,
    highlight: Option<PartialPointerStyleConfig>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialPointerStyleConfig {
    color: Option<String>,
    size: Option<f32>,
}

/// Spotlight configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct SpotlightConfig {
    /// Radius in logical pixels at 1x scale.
    pub radius: f32,
    /// Opacity of the dimmed area (0.0–1.0).
    pub dim_opacity: f32,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialSpotlightConfig {
    radius: Option<f32>,
    dim_opacity: Option<f32>,
}

/// Ink drawing configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct InkConfig {
    /// Pen color presets as hex strings (RGB or RGBA). `CycleInkColor` steps through these.
    /// Accepts a single string (`color = "#FF0000"`) or an array (`colors = ["#FF0000", "#0000FF"]`).
    pub colors: Vec<String>,
    /// Default pen stroke width in logical pixels.
    pub width: f32,
    /// Highlighter color presets as RGBA hex strings (alpha controls opacity).
    /// Defaults to semi-transparent yellow, green, cyan, and pink.
    pub highlighter_colors: Vec<String>,
    /// Default highlighter stroke width in logical pixels.
    pub highlighter_width: f32,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialInkConfig {
    /// New array form: `colors = ["#FF0000", "#0000FF"]`.
    colors: Option<Vec<String>>,
    /// Legacy single-color form: `color = "#FF0000"`. Ignored if `colors` is also set.
    color: Option<String>,
    width: Option<f32>,
    highlighter_colors: Option<Vec<String>>,
    highlighter_width: Option<f32>,
}

/// Default style for newly created text boxes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct TextBoxConfig {
    /// Text color as a hex string (RGB or RGBA).
    pub color: String,
    /// Background fill as a hex string (RGB or RGBA), or `"transparent"`.
    pub background: String,
    /// Typst setup inserted after Dais defaults and before newly created text box content.
    pub typst_prelude: String,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialTextBoxConfig {
    color: Option<String>,
    background: Option<String>,
    typst_prelude: Option<String>,
}

/// Clicker/remote hardware configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ClickerConfig {
    /// Name of the active clicker profile (e.g., "default", "logitech-spotlight").
    pub profile: String,
    /// Custom profile definitions mapping key names to action names.
    pub profiles: HashMap<String, HashMap<String, String>>,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialClickerConfig {
    profile: Option<String>,
    profiles: Option<HashMap<String, HashMap<String, String>>>,
}

/// Local HTTP remote-control API configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct RemoteConfig {
    /// Whether to start the remote API server with a presentation.
    pub enabled: bool,
    /// Bind host for the remote API. Defaults to loopback.
    pub host: String,
    /// Bind port for the remote API. `0` asks the OS to choose a free port.
    pub port: u16,
    /// Bearer token for remote API requests. Empty means generate one per launch.
    pub token: String,
    /// Allow unauthenticated requests from loopback clients when bound to loopback.
    pub allow_unauthenticated_loopback: bool,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialRemoteConfig {
    enabled: Option<bool>,
    host: Option<String>,
    port: Option<u16>,
    token: Option<String>,
    allow_unauthenticated_loopback: Option<bool>,
}

/// Notes panel configuration.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct NotesConfig {
    /// Font size in points.
    pub font_size: f32,
    /// Step size for font size increment/decrement.
    pub font_size_step: f32,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialNotesConfig {
    font_size: Option<f32>,
    font_size_step: Option<f32>,
}

/// Annotated export defaults.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(default)]
pub struct ExportConfig {
    /// Output format: "pdf", "svg", or "png".
    pub format: String,
    /// Layers to include: "all", "background", "ink", "text", or "overlays".
    pub layers: String,
    /// Export one page per logical slide using the final build page of each group.
    pub handout: bool,
    /// Whiteboard export behavior: "none", "append", or "only".
    pub whiteboard: String,
}

#[derive(Debug, Clone, Default, Deserialize)]
#[serde(default)]
struct PartialExportConfig {
    format: Option<String>,
    layers: Option<String>,
    handout: Option<bool>,
    whiteboard: Option<String>,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            display: DisplayConfig::default(),
            timer: TimerConfig::default(),
            laser: LaserConfig::default(),
            spotlight: SpotlightConfig::default(),
            ink: InkConfig::default(),
            text_boxes: TextBoxConfig::default(),
            notes: NotesConfig::default(),
            keybindings: HashMap::new(),
            clicker: ClickerConfig::default(),
            remote: RemoteConfig::default(),
            export: ExportConfig::default(),
            sidecar_format: "dais".to_string(),
            save_slide_timings: true,
        }
    }
}

impl Default for DisplayConfig {
    fn default() -> Self {
        Self {
            mode: "dual".to_string(),
            single_monitor_view: "hud".to_string(),
            audience_monitor: "auto".to_string(),
            presenter_monitor: "auto".to_string(),
        }
    }
}

impl Default for TimerConfig {
    fn default() -> Self {
        Self {
            mode: TimerMode::Elapsed,
            duration_minutes: None,
            warning_minutes: None,
            overrun_color: true,
        }
    }
}

impl Default for LaserConfig {
    fn default() -> Self {
        let pointer = PointerStyleConfig::default();
        Self {
            color: pointer.color.clone(),
            size: pointer.size,
            style: "dot".to_string(),
            dot: pointer.clone(),
            minimal: pointer.clone(),
            crosshair: pointer.clone(),
            arrow: pointer.clone(),
            ring: pointer.clone(),
            bullseye: pointer.clone(),
            highlight: pointer,
        }
    }
}

impl Default for PointerStyleConfig {
    fn default() -> Self {
        Self { color: "#FF0000".to_string(), size: 12.0 }
    }
}

impl Default for SpotlightConfig {
    fn default() -> Self {
        Self { radius: 80.0, dim_opacity: 0.6 }
    }
}

impl Default for InkConfig {
    fn default() -> Self {
        Self {
            colors: vec!["#FF0000".to_string()],
            width: 3.0,
            highlighter_colors: Vec::new(),
            highlighter_width: 10.0,
        }
    }
}

impl Default for TextBoxConfig {
    fn default() -> Self {
        Self {
            color: "#000000".to_string(),
            background: "transparent".to_string(),
            typst_prelude: String::new(),
        }
    }
}

impl Default for ClickerConfig {
    fn default() -> Self {
        Self { profile: "default".to_string(), profiles: HashMap::new() }
    }
}

impl Default for RemoteConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            host: "127.0.0.1".to_string(),
            port: 4317,
            token: String::new(),
            allow_unauthenticated_loopback: true,
        }
    }
}

/// Return the built-in default clicker profile mapping common USB presenter keys to actions.
pub fn default_clicker_profile() -> HashMap<String, String> {
    HashMap::from([
        ("PageDown".to_string(), "next_slide".to_string()),
        ("PageUp".to_string(), "previous_slide".to_string()),
        ("F5".to_string(), "toggle_presentation_mode".to_string()),
        ("b".to_string(), "toggle_blackout".to_string()),
        (".".to_string(), "toggle_blackout".to_string()),
    ])
}

impl Config {
    /// Resolve the active clicker profile into a key -> action map.
    pub fn active_clicker_profile(&self) -> HashMap<String, String> {
        if self.clicker.profile == "default" {
            return default_clicker_profile();
        }

        self.clicker.profiles.get(&self.clicker.profile).cloned().unwrap_or_else(|| {
            tracing::warn!(
                "Configured clicker profile '{}' not found; using default profile",
                self.clicker.profile
            );
            default_clicker_profile()
        })
    }

    /// Normalize the configured sidecar save format to a supported value.
    pub fn normalized_sidecar_format(&self) -> &str {
        if self.sidecar_format.eq_ignore_ascii_case("dais") { "dais" } else { "pdfpc" }
    }
}

impl Default for NotesConfig {
    fn default() -> Self {
        Self { font_size: 16.0, font_size_step: 2.0 }
    }
}

/// Resolve the platform-appropriate config file path.
pub fn config_path() -> Option<PathBuf> {
    directories::ProjectDirs::from("", "", "dais").map(|dirs| dirs.config_dir().join("config.toml"))
}

/// Resolve a project-local config path for a PDF.
pub fn project_config_path(pdf_path: &Path) -> Option<PathBuf> {
    pdf_path.parent().map(|dir| dir.join("dais.toml"))
}

impl Default for ExportConfig {
    fn default() -> Self {
        Self {
            format: "pdf".to_string(),
            layers: "all".to_string(),
            handout: false,
            whiteboard: "none".to_string(),
        }
    }
}

/// Options controlling how layered configuration is loaded.
#[derive(Debug, Clone, Copy, Default)]
pub struct ConfigLoadOptions {
    /// Skip the platform user config directory for USB-portable runs.
    pub portable: bool,
}

/// Load layered config for a document.
///
/// Precedence:
/// 1. Built-in defaults
/// 2. Machine-wide config (`config.toml` in the standard OS config dir)
/// 3. Project-local config (`dais.toml` next to the PDF)
/// 4. Explicit `--config` path, if provided
///
/// Missing or invalid config files are logged and ignored; this function always
/// returns a usable configuration by falling back to defaults.
pub fn load_config_for(pdf_path: &Path, explicit_config: Option<&Path>) -> Config {
    load_config_for_with_options(pdf_path, explicit_config, ConfigLoadOptions::default())
}

/// Load layered config for a document with additional mode options.
///
/// In portable mode, Dais skips the machine-wide config layer so a copied binary
/// and project folder behave consistently on machines that may already have
/// user-level Dais settings.
pub fn load_config_for_with_options(
    pdf_path: &Path,
    explicit_config: Option<&Path>,
    options: ConfigLoadOptions,
) -> Config {
    load_config_from_paths(pdf_path, config_path().as_deref(), explicit_config, options)
}

fn load_config_from_paths(
    pdf_path: &Path,
    machine_config: Option<&Path>,
    explicit_config: Option<&Path>,
    options: ConfigLoadOptions,
) -> Config {
    let mut config = Config::default();

    if options.portable {
        tracing::debug!("Portable mode enabled; skipping machine-wide config");
    } else if let Some(path) = machine_config {
        merge_config_file(&mut config, path);
    } else {
        tracing::warn!("Could not determine config directory, using defaults");
    }

    if let Some(path) = project_config_path(pdf_path) {
        merge_config_file(&mut config, &path);
    }

    if let Some(path) = explicit_config {
        merge_config_file(&mut config, path);
    }

    config
}

fn merge_config_file(config: &mut Config, path: &Path) {
    let Ok(contents) = std::fs::read_to_string(path) else {
        tracing::debug!("No config file at {}", path.display());
        return;
    };

    match toml::from_str::<PartialConfig>(&contents) {
        Ok(partial) => {
            tracing::info!("Loaded config layer from {}", path.display());
            apply_partial_config(config, partial);
        }
        Err(e) => {
            tracing::warn!("Failed to parse config at {}: {e}", path.display());
        }
    }
}

fn apply_partial_config(config: &mut Config, partial: PartialConfig) {
    if let Some(display) = partial.display {
        if let Some(mode) = display.mode {
            config.display.mode = mode;
        }
        if let Some(v) = display.single_monitor_view {
            config.display.single_monitor_view = v;
        }
        if let Some(audience_monitor) = display.audience_monitor {
            config.display.audience_monitor = audience_monitor;
        }
        if let Some(presenter_monitor) = display.presenter_monitor {
            config.display.presenter_monitor = presenter_monitor;
        }
    }

    if let Some(timer) = partial.timer {
        if let Some(mode) = timer.mode {
            config.timer.mode = mode;
        }
        if let Some(duration_minutes) = timer.duration_minutes {
            config.timer.duration_minutes = duration_minutes.into_option();
        }
        if let Some(warning_minutes) = timer.warning_minutes {
            config.timer.warning_minutes = warning_minutes.into_option();
        }
        if let Some(overrun_color) = timer.overrun_color {
            config.timer.overrun_color = overrun_color;
        }
    }

    if let Some(laser) = partial.laser {
        apply_laser_config(&mut config.laser, laser);
    }

    if let Some(spotlight) = partial.spotlight {
        if let Some(radius) = spotlight.radius {
            config.spotlight.radius = radius;
        }
        if let Some(dim_opacity) = spotlight.dim_opacity {
            config.spotlight.dim_opacity = dim_opacity;
        }
    }

    if let Some(ink) = partial.ink {
        if let Some(colors) = ink.colors {
            config.ink.colors = colors;
        } else if let Some(color) = ink.color {
            config.ink.colors = vec![color];
        }
        if let Some(width) = ink.width {
            config.ink.width = width;
        }
        if let Some(highlighter_colors) = ink.highlighter_colors {
            config.ink.highlighter_colors = highlighter_colors;
        }
        if let Some(highlighter_width) = ink.highlighter_width {
            config.ink.highlighter_width = highlighter_width;
        }
    }

    if let Some(text_boxes) = partial.text_boxes {
        if let Some(color) = text_boxes.color {
            config.text_boxes.color = color;
        }
        if let Some(background) = text_boxes.background {
            config.text_boxes.background = background;
        }
        if let Some(typst_prelude) = text_boxes.typst_prelude {
            config.text_boxes.typst_prelude = typst_prelude;
        }
    }

    if let Some(notes) = partial.notes {
        if let Some(font_size) = notes.font_size {
            config.notes.font_size = font_size;
        }
        if let Some(font_size_step) = notes.font_size_step {
            config.notes.font_size_step = font_size_step;
        }
    }

    if let Some(keybindings) = partial.keybindings {
        config.keybindings.extend(keybindings);
    }

    if let Some(clicker) = partial.clicker {
        if let Some(profile) = clicker.profile {
            config.clicker.profile = profile;
        }
        if let Some(profiles) = clicker.profiles {
            config.clicker.profiles.extend(profiles);
        }
    }

    if let Some(remote) = partial.remote {
        apply_remote_config(&mut config.remote, remote);
    }

    if let Some(export) = partial.export {
        apply_export_config(&mut config.export, export);
    }

    if let Some(sidecar_format) = partial.sidecar_format {
        config.sidecar_format = sidecar_format;
    }
    if let Some(save_slide_timings) = partial.save_slide_timings {
        config.save_slide_timings = save_slide_timings;
    }
}

fn apply_export_config(config: &mut ExportConfig, partial: PartialExportConfig) {
    if let Some(format) = partial.format {
        config.format = format;
    }
    if let Some(layers) = partial.layers {
        config.layers = layers;
    }
    if let Some(handout) = partial.handout {
        config.handout = handout;
    }
    if let Some(whiteboard) = partial.whiteboard {
        config.whiteboard = whiteboard;
    }
}

fn apply_remote_config(config: &mut RemoteConfig, partial: PartialRemoteConfig) {
    if let Some(enabled) = partial.enabled {
        config.enabled = enabled;
    }
    if let Some(host) = partial.host {
        config.host = host;
    }
    if let Some(port) = partial.port {
        config.port = port;
    }
    if let Some(token) = partial.token {
        config.token = token;
    }
    if let Some(allow) = partial.allow_unauthenticated_loopback {
        config.allow_unauthenticated_loopback = allow;
    }
}

fn apply_laser_config(config: &mut LaserConfig, partial: PartialLaserConfig) {
    if let Some(color) = partial.color {
        config.color = color.clone();
        config.dot.color = color.clone();
        config.minimal.color = color.clone();
        config.crosshair.color = color.clone();
        config.arrow.color = color.clone();
        config.ring.color = color.clone();
        config.bullseye.color = color.clone();
        config.highlight.color = color;
    }
    if let Some(size) = partial.size {
        config.size = size;
        config.dot.size = size;
        config.minimal.size = size;
        config.crosshair.size = size;
        config.arrow.size = size;
        config.ring.size = size;
        config.bullseye.size = size;
        config.highlight.size = size;
    }
    if let Some(style) = partial.style {
        config.style = style;
    }
    if let Some(dot) = partial.dot {
        apply_pointer_style_config(&mut config.dot, dot);
    }
    if let Some(minimal) = partial.minimal {
        apply_pointer_style_config(&mut config.minimal, minimal);
    }
    if let Some(crosshair) = partial.crosshair {
        apply_pointer_style_config(&mut config.crosshair, crosshair);
    }
    if let Some(arrow) = partial.arrow {
        apply_pointer_style_config(&mut config.arrow, arrow);
    }
    if let Some(ring) = partial.ring {
        apply_pointer_style_config(&mut config.ring, ring);
    }
    if let Some(bullseye) = partial.bullseye {
        apply_pointer_style_config(&mut config.bullseye, bullseye);
    }
    if let Some(highlight) = partial.highlight {
        apply_pointer_style_config(&mut config.highlight, highlight);
    }
}

fn apply_pointer_style_config(config: &mut PointerStyleConfig, partial: PartialPointerStyleConfig) {
    if let Some(color) = partial.color {
        config.color = color;
    }
    if let Some(size) = partial.size {
        config.size = size;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::time::{SystemTime, UNIX_EPOCH};

    fn temp_config_dir(name: &str) -> PathBuf {
        let suffix = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("system time should be after unix epoch")
            .as_nanos();
        let dir = std::env::temp_dir().join(format!("dais_config_test_{name}_{suffix}"));
        std::fs::create_dir_all(&dir).expect("should create temp config test dir");
        dir
    }

    #[test]
    fn partial_config_overrides_selected_fields() {
        let mut config = Config::default();
        let partial = PartialConfig {
            display: Some(PartialDisplayConfig {
                mode: Some("screen-share".to_string()),
                single_monitor_view: Some("split".to_string()),
                audience_monitor: Some("Projector".to_string()),
                presenter_monitor: None,
            }),
            timer: Some(PartialTimerConfig {
                mode: Some(TimerMode::Countdown),
                duration_minutes: Some(OptionalU32Value::Value(45)),
                warning_minutes: Some(OptionalU32Value::Value(10)),
                overrun_color: Some(false),
            }),
            save_slide_timings: Some(false),
            ..Default::default()
        };

        apply_partial_config(&mut config, partial);

        assert_eq!(config.display.mode, "screen-share");
        assert_eq!(config.display.single_monitor_view, "split");
        assert_eq!(config.display.audience_monitor, "Projector");
        assert_eq!(config.timer.mode, TimerMode::Countdown);
        assert_eq!(config.timer.duration_minutes, Some(45));
        assert_eq!(config.timer.warning_minutes, Some(10));
        assert!(!config.timer.overrun_color);
        assert!(!config.save_slide_timings);
    }

    #[test]
    fn partial_config_overrides_text_box_defaults() {
        let mut config = Config::default();
        let partial = PartialConfig {
            text_boxes: Some(PartialTextBoxConfig {
                color: Some("#112233".to_string()),
                background: Some("#445566AA".to_string()),
                typst_prelude: Some("#set align(horizon)".to_string()),
            }),
            ..Default::default()
        };

        apply_partial_config(&mut config, partial);

        assert_eq!(config.text_boxes.color, "#112233");
        assert_eq!(config.text_boxes.background, "#445566AA");
        assert_eq!(config.text_boxes.typst_prelude, "#set align(horizon)");
    }

    #[test]
    fn partial_config_overrides_export_defaults() {
        let mut config = Config::default();
        let partial = PartialConfig {
            export: Some(PartialExportConfig {
                format: Some("svg".to_string()),
                layers: Some("ink".to_string()),
                handout: Some(true),
                whiteboard: Some("append".to_string()),
            }),
            ..Default::default()
        };

        apply_partial_config(&mut config, partial);

        assert_eq!(config.export.format, "svg");
        assert_eq!(config.export.layers, "ink");
        assert!(config.export.handout);
        assert_eq!(config.export.whiteboard, "append");
    }

    #[test]
    fn partial_laser_defaults_apply_to_all_pointer_styles() {
        let mut config = Config::default();
        let partial = PartialConfig {
            laser: Some(PartialLaserConfig {
                color: Some("#FFFFFF".to_string()),
                size: Some(20.0),
                ..Default::default()
            }),
            ..Default::default()
        };

        apply_partial_config(&mut config, partial);

        assert_eq!(config.laser.dot.color, "#FFFFFF");
        assert_eq!(config.laser.minimal.color, "#FFFFFF");
        assert_eq!(config.laser.crosshair.color, "#FFFFFF");
        assert_eq!(config.laser.arrow.color, "#FFFFFF");
        assert_eq!(config.laser.ring.color, "#FFFFFF");
        assert_eq!(config.laser.bullseye.color, "#FFFFFF");
        assert_eq!(config.laser.highlight.color, "#FFFFFF");
        assert!((config.laser.dot.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.minimal.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.crosshair.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.arrow.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.ring.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.bullseye.size - 20.0).abs() < f32::EPSILON);
        assert!((config.laser.highlight.size - 20.0).abs() < f32::EPSILON);
    }

    #[test]
    fn partial_laser_pointer_style_overrides_defaults() {
        let partial: PartialConfig = toml::from_str(
            r##"
            [laser]
            color = "#FFFFFF"
            size = 14.0
            style = "crosshair"

            [laser.crosshair]
            color = "#00FF00"
            size = 30.0

            [laser.minimal]
            size = 8.0

            [laser.highlight]
            color = "#FFFF0080"
            "##,
        )
        .unwrap();
        let mut config = Config::default();

        apply_partial_config(&mut config, partial);

        assert_eq!(config.laser.style, "crosshair");
        assert_eq!(config.laser.dot.color, "#FFFFFF");
        assert!((config.laser.dot.size - 14.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.minimal.color, "#FFFFFF");
        assert!((config.laser.minimal.size - 8.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.crosshair.color, "#00FF00");
        assert!((config.laser.crosshair.size - 30.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.arrow.color, "#FFFFFF");
        assert!((config.laser.arrow.size - 14.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.ring.color, "#FFFFFF");
        assert!((config.laser.ring.size - 14.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.bullseye.color, "#FFFFFF");
        assert!((config.laser.bullseye.size - 14.0).abs() < f32::EPSILON);
        assert_eq!(config.laser.highlight.color, "#FFFF0080");
        assert!((config.laser.highlight.size - 14.0).abs() < f32::EPSILON);
    }

    #[test]
    fn partial_config_can_clear_optional_timer_values() {
        let mut config = Config::default();
        config.timer.duration_minutes = Some(20);
        config.timer.warning_minutes = Some(5);

        let partial = PartialConfig {
            timer: Some(PartialTimerConfig {
                duration_minutes: Some(OptionalU32Value::Null(())),
                warning_minutes: Some(OptionalU32Value::Null(())),
                ..Default::default()
            }),
            ..Default::default()
        };

        apply_partial_config(&mut config, partial);

        assert_eq!(config.timer.duration_minutes, None);
        assert_eq!(config.timer.warning_minutes, None);
    }

    #[test]
    fn portable_config_skips_machine_config() {
        let dir = temp_config_dir("portable_skips_machine");
        let machine_config = dir.join("machine.toml");
        let pdf_path = dir.join("slides.pdf");
        std::fs::write(&machine_config, "[display]\nmode = \"screen-share\"\n")
            .expect("should write machine config");

        let regular = load_config_from_paths(
            &pdf_path,
            Some(&machine_config),
            None,
            ConfigLoadOptions { portable: false },
        );
        let portable = load_config_from_paths(
            &pdf_path,
            Some(&machine_config),
            None,
            ConfigLoadOptions { portable: true },
        );

        assert_eq!(regular.display.mode, "screen-share");
        assert_eq!(portable.display.mode, "dual");

        let _ = std::fs::remove_dir_all(dir);
    }

    #[test]
    fn portable_config_still_loads_project_and_explicit_config() {
        let dir = temp_config_dir("portable_keeps_project_explicit");
        let explicit_config = dir.join("explicit.toml");
        let pdf_dir = dir.join("talk");
        std::fs::create_dir_all(&pdf_dir).expect("should create pdf dir");
        let pdf_path = pdf_dir.join("slides.pdf");
        std::fs::write(pdf_dir.join("dais.toml"), "[display]\nmode = \"single\"\n")
            .expect("should write project config");
        std::fs::write(&explicit_config, "[display]\nmode = \"screen-share\"\n")
            .expect("should write explicit config");

        let config = load_config_from_paths(
            &pdf_path,
            None,
            Some(&explicit_config),
            ConfigLoadOptions { portable: true },
        );

        assert_eq!(config.display.mode, "screen-share");

        let _ = std::fs::remove_dir_all(dir);
    }
}