par-term-settings-ui 0.12.2

Settings UI for par-term terminal emulator
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
//! SettingsUI state management and lifecycle methods.

use par_term_config::{
    BackgroundImageMode, Config, CursorShaderMetadataCache, Profile, ProfileId, ShaderMetadataCache,
};
use rfd::FileDialog;
use std::collections::HashSet;

use crate::profile_modal_ui::ProfileModalUI;
use crate::sidebar::SettingsTab;
use crate::{ArrangementManager, InstallationType};

use super::SettingsUI;

fn load_assistant_prompts_for_settings() -> (Vec<par_term_config::AssistantPrompt>, Option<String>)
{
    match par_term_config::list_prompts() {
        Ok(prompts) => (prompts, None),
        Err(error) => (Vec::new(), Some(error)),
    }
}

impl SettingsUI {
    /// Clear the latest shader lint/readability output.
    pub fn clear_shader_lint_result(&mut self) {
        self.shader_lint_result = None;
        self.shader_lint_error = None;
    }

    /// Run shader lint/readability analysis for the selected background shader.
    pub fn run_shader_lint_for_selected_shader(&mut self) {
        self.shader_lint_result = None;
        self.shader_lint_error = None;

        if self.temp_custom_shader.is_empty() {
            self.shader_lint_error = Some("No background shader selected".to_string());
            return;
        }

        let Some(lint_fn) = self.shader_lint_fn else {
            self.shader_lint_error = Some("Shader lint is not available".to_string());
            return;
        };

        let shader_path = par_term_config::Config::shader_path(&self.temp_custom_shader);
        let (brightness, text_opacity) = self.current_shader_readability_values();
        match lint_fn(&shader_path, brightness, text_opacity) {
            Ok(result) => self.shader_lint_result = Some(result),
            Err(error) => self.shader_lint_error = Some(error),
        }
    }

    fn current_shader_readability_values(&mut self) -> (Option<f32>, Option<f32>) {
        let shader_name = self.temp_custom_shader.clone();
        let current_override = self.config.shader_configs.get(&shader_name);
        let metadata = self.shader_metadata_cache.get(&shader_name).cloned();
        let meta_defaults = metadata.as_ref().map(|metadata| &metadata.defaults);

        let brightness = current_override
            .and_then(|override_config| override_config.brightness)
            .or_else(|| meta_defaults.and_then(|defaults| defaults.brightness))
            .or(Some(self.config.shader.custom_shader_brightness));
        let text_opacity = current_override
            .and_then(|override_config| override_config.text_opacity)
            .or_else(|| meta_defaults.and_then(|defaults| defaults.text_opacity))
            .or(Some(self.config.shader.custom_shader_text_opacity));

        (brightness, text_opacity)
    }

    /// Create a new settings UI.
    ///
    /// This loads assistant prompt files from the configured prompt library.
    pub fn new(config: Config) -> Self {
        let (assistant_prompts, assistant_prompt_error) = load_assistant_prompts_for_settings();
        Self::new_with_assistant_prompts(config, assistant_prompts, assistant_prompt_error)
    }

    /// Create a settings UI with no assistant prompt filesystem access.
    pub fn new_for_tests(config: Config) -> Self {
        Self::new_with_assistant_prompts(config, Vec::new(), None)
    }

    /// Create a settings UI with caller-supplied assistant prompt state.
    ///
    /// Unlike [`SettingsUI::new`], this does not read prompt files from disk.
    pub fn new_with_assistant_prompts(
        config: Config,
        assistant_prompts: Vec<par_term_config::AssistantPrompt>,
        assistant_prompt_error: Option<String>,
    ) -> Self {
        // Extract values before moving config
        let initial_cols = config.cols;
        let initial_rows = config.rows;
        let initial_collapsed: HashSet<String> =
            config.collapsed_settings_sections.iter().cloned().collect();

        Self {
            visible: false,
            temp_font_bold: config.font_family_bold.clone().unwrap_or_default(),
            temp_font_italic: config.font_family_italic.clone().unwrap_or_default(),
            temp_font_bold_italic: config.font_family_bold_italic.clone().unwrap_or_default(),
            temp_font_family: config.font_family.clone(),
            temp_font_size: config.font_size,
            temp_line_spacing: config.line_spacing,
            temp_char_spacing: config.char_spacing,
            temp_enable_text_shaping: config.enable_text_shaping,
            temp_enable_ligatures: config.enable_ligatures,
            temp_enable_kerning: config.enable_kerning,
            font_pending_changes: false,
            temp_custom_shell: config.custom_shell.clone().unwrap_or_default(),
            temp_shell_args: config
                .shell_args
                .as_ref()
                .map(|args| args.join(" "))
                .unwrap_or_default(),
            temp_working_directory: config.working_directory.clone().unwrap_or_default(),
            temp_startup_directory: config.startup_directory.clone().unwrap_or_default(),
            temp_initial_text: config.initial_text.clone(),
            temp_background_image: config.background_image.clone().unwrap_or_default(),
            temp_custom_shader: config.shader.custom_shader.clone().unwrap_or_default(),
            temp_cursor_shader: config.shader.cursor_shader.clone().unwrap_or_default(),
            temp_shader_channel0: config
                .shader
                .custom_shader_channel0
                .clone()
                .unwrap_or_default(),
            temp_shader_channel1: config
                .shader
                .custom_shader_channel1
                .clone()
                .unwrap_or_default(),
            temp_shader_channel2: config
                .shader
                .custom_shader_channel2
                .clone()
                .unwrap_or_default(),
            temp_shader_channel3: config
                .shader
                .custom_shader_channel3
                .clone()
                .unwrap_or_default(),
            temp_cubemap_path: config
                .shader
                .custom_shader_cubemap
                .clone()
                .unwrap_or_default(),
            temp_background_color: config.background_color,
            temp_pane_bg_path: String::new(),
            temp_pane_bg_mode: BackgroundImageMode::default(),
            temp_pane_bg_opacity: 1.0,
            temp_pane_bg_darken: 0.0,
            temp_pane_bg_index: None,
            last_live_opacity: config.window.window_opacity,
            current_cols: initial_cols,
            current_rows: initial_rows,
            supported_vsync_modes: vec![
                par_term_config::VsyncMode::Immediate,
                par_term_config::VsyncMode::Mailbox,
                par_term_config::VsyncMode::Fifo,
            ],
            vsync_warning: None,
            config,
            has_changes: false,
            search_query: String::new(),
            focus_search: true,
            shader_editor_visible: false,
            shader_editor_source: String::new(),
            shader_editor_error: None,
            shader_editor_original: String::new(),
            cursor_shader_editor_visible: false,
            cursor_shader_editor_source: String::new(),
            cursor_shader_editor_error: None,
            cursor_shader_editor_original: String::new(),
            available_agent_ids: Vec::new(),
            assistant_prompts,
            assistant_prompt_error,
            editing_assistant_prompt_index: None,
            adding_new_assistant_prompt: false,
            temp_assistant_prompt_title: String::new(),
            temp_assistant_prompt_body: String::new(),
            temp_assistant_prompt_auto_submit: false,
            assistant_prompts_changed: false,
            available_shaders: Self::scan_shaders_folder(),
            available_cubemaps: Self::scan_cubemaps_folder(),
            new_shader_name: String::new(),
            show_create_shader_dialog: false,
            show_delete_shader_dialog: false,
            shader_search_query: String::new(),
            shader_search_matches: Vec::new(),
            shader_search_current: 0,
            shader_search_visible: false,
            shader_metadata_cache: ShaderMetadataCache::with_shaders_dir(
                par_term_config::Config::shaders_dir(),
            ),
            shader_controls_cache: std::collections::HashMap::new(),
            cursor_shader_metadata_cache: CursorShaderMetadataCache::with_shaders_dir(
                par_term_config::Config::shaders_dir(),
            ),
            shader_lint_result: None,
            shader_lint_error: None,
            shader_settings_expanded: true,
            cursor_shader_settings_expanded: true,
            keybinding_recording_index: None,
            keybinding_recorded_combo: None,
            test_notification_requested: false,
            selected_tab: SettingsTab::default(),
            collapsed_sections: initial_collapsed,
            shell_integration_action: None,
            profile_modal_ui: ProfileModalUI::new(),
            profile_save_requested: false,
            profile_open_requested: None,
            shader_installing: false,
            shader_status: None,
            shader_error: None,
            shader_overwrite_prompt_visible: false,
            shader_conflicts: Vec::new(),
            shader_install_receiver: None,
            editing_trigger_index: None,
            temp_trigger_name: String::new(),
            temp_trigger_pattern: String::new(),
            temp_trigger_actions: Vec::new(),
            temp_trigger_prompt_before_run: true,
            adding_new_trigger: false,
            trigger_pattern_error: None,
            editing_coprocess_index: None,
            temp_coprocess_name: String::new(),
            temp_coprocess_command: String::new(),
            temp_coprocess_args: String::new(),
            temp_coprocess_auto_start: false,
            temp_coprocess_copy_output: true,
            temp_coprocess_restart_policy: par_term_config::automation::RestartPolicy::Never,
            temp_coprocess_restart_delay_ms: 0,
            adding_new_coprocess: false,
            trigger_resync_requested: false,
            pending_coprocess_actions: Vec::new(),
            coprocess_running: Vec::new(),
            coprocess_errors: Vec::new(),
            coprocess_output: Vec::new(),
            coprocess_output_expanded: Vec::new(),
            editing_script_index: None,
            temp_script_name: String::new(),
            temp_script_path: String::new(),
            temp_script_args: String::new(),
            temp_script_auto_start: false,
            temp_script_enabled: true,
            temp_script_restart_policy: par_term_config::automation::RestartPolicy::Never,
            temp_script_restart_delay_ms: 0,
            temp_script_subscriptions: String::new(),
            temp_script_allow_write_text: false,
            temp_script_allow_run_command: false,
            temp_script_allow_change_config: false,
            temp_script_write_text_rate_limit: 0,
            temp_script_run_command_rate_limit: 0,
            adding_new_script: false,
            pending_script_actions: Vec::new(),
            script_running: Vec::new(),
            script_errors: Vec::new(),
            script_output: Vec::new(),
            script_output_expanded: Vec::new(),
            script_panels: Vec::new(),
            open_log_requested: false,
            identify_panes_requested: false,
            update_install_requested: false,
            check_now_requested: false,
            update_status: None,
            update_result: None,
            last_update_result: None,
            update_installing: false,
            update_install_receiver: None,
            editing_snippet_index: None,
            temp_snippet_id: String::new(),
            temp_snippet_title: String::new(),
            temp_snippet_content: String::new(),
            temp_snippet_keybinding: String::new(),
            temp_snippet_folder: String::new(),
            temp_snippet_description: String::new(),
            temp_snippet_keybinding_enabled: true,
            temp_snippet_auto_execute: false,
            temp_snippet_variables: Vec::new(),
            adding_new_snippet: false,
            editing_action_index: None,
            temp_action_type: 0,
            temp_action_id: String::new(),
            temp_action_title: String::new(),
            temp_action_command: String::new(),
            temp_action_args: String::new(),
            temp_action_new_tab_command: String::new(),
            temp_action_text: String::new(),
            temp_action_keys: String::new(),
            temp_action_keybinding: String::new(),
            temp_action_prefix_char: String::new(),
            temp_action_split_direction: 0,
            temp_action_split_command: String::new(),
            temp_action_split_focus_new: true,
            temp_action_split_delay_ms: 200,
            temp_action_split_command_is_direct: false,
            temp_action_split_percent: 66,
            adding_new_action: false,
            recording_snippet_keybinding: false,
            snippet_recorded_combo: None,
            recording_action_keybinding: false,
            action_recorded_combo: None,
            recording_custom_action_prefix_key: false,
            custom_action_prefix_key_recorded_combo: None,
            temp_action_steps: Vec::new(),
            temp_action_check_type: 0,
            temp_action_check_value: String::new(),
            temp_action_case_sensitive: false,
            temp_action_env_name: String::new(),
            temp_action_env_value: String::new(),
            temp_action_env_check_existence: false,
            temp_action_on_true_id: String::new(),
            temp_action_on_false_id: String::new(),
            temp_action_repeat_action_id: String::new(),
            temp_action_repeat_count: 3,
            temp_action_repeat_delay_ms: 0,
            temp_action_stop_on_success: false,
            temp_action_stop_on_failure: false,
            temp_action_capture_output: false,
            temp_action_keybinding_enabled: true,
            dynamic_source_editing: None,
            dynamic_source_edit_buffer: None,
            dynamic_source_new_header_key: String::new(),
            dynamic_source_new_header_value: String::new(),
            temp_import_url: String::new(),
            import_export_status: None,
            import_export_is_error: false,
            show_reset_defaults_dialog: false,
            arrangement_save_name: String::new(),
            arrangement_confirm_restore: None,
            arrangement_confirm_delete: None,
            arrangement_confirm_overwrite: None,
            arrangement_confirm_replace: None,
            arrangement_rename_id: None,
            arrangement_rename_text: String::new(),
            pending_arrangement_actions: Vec::new(),
            arrangement_manager: ArrangementManager::new(),
            app_version: "",
            installation_type: InstallationType::StandaloneBinary,
            shader_install_fn: None,
            shader_detect_modified_fn: None,
            shader_uninstall_fn: None,
            shader_lint_fn: None,
            shader_has_files_fn: None,
            shader_count_files_fn: None,
            shell_integration_is_installed_fn: None,
            shell_integration_detected_shell_fn: None,
            shell_integration_install_fn: None,
            shell_integration_uninstall_fn: None,
        }
    }

    /// Update the current terminal dimensions (called when window resizes)
    pub fn update_current_size(&mut self, cols: usize, rows: usize) {
        self.current_cols = cols;
        self.current_rows = rows;
    }

    /// Update the list of supported vsync modes (called when renderer is initialized)
    pub fn update_supported_vsync_modes(&mut self, modes: Vec<par_term_config::VsyncMode>) {
        self.supported_vsync_modes = modes;
        self.vsync_warning = None;
    }

    /// Check if a vsync mode is supported
    pub fn is_vsync_mode_supported(&self, mode: par_term_config::VsyncMode) -> bool {
        self.supported_vsync_modes.contains(&mode)
    }

    /// Set vsync warning message
    pub fn set_vsync_warning(&mut self, warning: Option<String>) {
        self.vsync_warning = warning;
    }

    /// Open a native file picker dialog and return the selected file path.
    pub fn pick_file_path(&self, title: &str) -> Option<String> {
        FileDialog::new()
            .set_title(title)
            .pick_file()
            .map(|p| p.display().to_string())
    }

    /// Open a native folder picker dialog and return the selected directory path.
    pub fn pick_folder_path(&self, title: &str) -> Option<String> {
        FileDialog::new()
            .set_title(title)
            .pick_folder()
            .map(|p| p.display().to_string())
    }

    /// Update the config copy (e.g., when config is reloaded).
    pub fn update_config(&mut self, config: Config) {
        if !self.has_changes {
            self.config = config;
            self.last_live_opacity = self.config.window.window_opacity;
            if !self.font_pending_changes {
                self.sync_font_temps_from_config();
            }
        }
    }

    /// Force-update the config copy, bypassing the `has_changes` guard.
    pub fn force_update_config(&mut self, config: Config) {
        self.config = config;
        self.sync_all_temps_from_config();
        self.has_changes = false;
    }

    pub(super) fn sync_font_temps_from_config(&mut self) {
        self.temp_font_family = self.config.font_family.clone();
        self.temp_font_size = self.config.font_size;
        self.temp_line_spacing = self.config.line_spacing;
        self.temp_char_spacing = self.config.char_spacing;
        self.temp_enable_text_shaping = self.config.enable_text_shaping;
        self.temp_enable_ligatures = self.config.enable_ligatures;
        self.temp_enable_kerning = self.config.enable_kerning;
        self.temp_font_bold = self.config.font_family_bold.clone().unwrap_or_default();
        self.temp_font_italic = self.config.font_family_italic.clone().unwrap_or_default();
        self.temp_font_bold_italic = self
            .config
            .font_family_bold_italic
            .clone()
            .unwrap_or_default();
        self.font_pending_changes = false;
    }

    /// Sync ALL temp fields from config
    pub fn sync_all_temps_from_config(&mut self) {
        self.sync_font_temps_from_config();
        self.temp_custom_shell = self.config.custom_shell.clone().unwrap_or_default();
        self.temp_shell_args = self
            .config
            .shell_args
            .as_ref()
            .map(|args| args.join(" "))
            .unwrap_or_default();
        self.temp_working_directory = self.config.working_directory.clone().unwrap_or_default();
        self.temp_startup_directory = self.config.startup_directory.clone().unwrap_or_default();
        self.temp_initial_text = self.config.initial_text.clone();
        self.temp_background_image = self.config.background_image.clone().unwrap_or_default();
        self.temp_background_color = self.config.background_color;
        self.temp_custom_shader = self.config.shader.custom_shader.clone().unwrap_or_default();
        self.temp_cursor_shader = self.config.shader.cursor_shader.clone().unwrap_or_default();
        self.temp_shader_channel0 = self
            .config
            .shader
            .custom_shader_channel0
            .clone()
            .unwrap_or_default();
        self.temp_shader_channel1 = self
            .config
            .shader
            .custom_shader_channel1
            .clone()
            .unwrap_or_default();
        self.temp_shader_channel2 = self
            .config
            .shader
            .custom_shader_channel2
            .clone()
            .unwrap_or_default();
        self.temp_shader_channel3 = self
            .config
            .shader
            .custom_shader_channel3
            .clone()
            .unwrap_or_default();
        self.temp_cubemap_path = self
            .config
            .shader
            .custom_shader_cubemap
            .clone()
            .unwrap_or_default();
        self.last_live_opacity = self.config.window.window_opacity;
    }

    /// Reset all settings to their default values
    pub(super) fn reset_all_to_defaults(&mut self) {
        self.config = Config::default();
        self.sync_all_temps_from_config();
        self.has_changes = true;
        self.search_query.clear();
    }

    /// Apply font changes from temp variables to config
    pub fn apply_font_changes(&mut self) {
        self.config.font_family = self.temp_font_family.clone();
        self.config.font_size = self.temp_font_size;
        self.config.line_spacing = self.temp_line_spacing;
        self.config.char_spacing = self.temp_char_spacing;
        self.config.enable_text_shaping = self.temp_enable_text_shaping;
        self.config.enable_ligatures = self.temp_enable_ligatures;
        self.config.enable_kerning = self.temp_enable_kerning;
        self.config.font_family_bold = if self.temp_font_bold.is_empty() {
            None
        } else {
            Some(self.temp_font_bold.clone())
        };
        self.config.font_family_italic = if self.temp_font_italic.is_empty() {
            None
        } else {
            Some(self.temp_font_italic.clone())
        };
        self.config.font_family_bold_italic = if self.temp_font_bold_italic.is_empty() {
            None
        } else {
            Some(self.temp_font_bold_italic.clone())
        };
        self.font_pending_changes = false;
    }

    /// Toggle settings window visibility
    pub fn toggle(&mut self) {
        self.visible = !self.visible;
        if self.visible {
            self.focus_search = true;
        }
    }

    /// Get a reference to the working config (for live sync)
    pub fn current_config(&self) -> &Config {
        &self.config
    }

    /// Sync the current collapsed sections state into the config's persisted field.
    pub(super) fn sync_collapsed_sections_to_config(&mut self) {
        self.config.collapsed_settings_sections = self.collapsed_sections.iter().cloned().collect();
    }

    /// Get a snapshot of the current collapsed section IDs for persistence on close.
    pub fn collapsed_sections_snapshot(&self) -> Vec<String> {
        self.collapsed_sections.iter().cloned().collect()
    }

    /// Check if a test notification was requested and clear the flag
    pub fn take_test_notification_request(&mut self) -> bool {
        let requested = self.test_notification_requested;
        self.test_notification_requested = false;
        requested
    }

    /// Sync profiles from the main window's profile manager into the inline editor.
    pub fn sync_profiles(&mut self, profiles: Vec<Profile>) {
        self.profile_modal_ui.load_profiles(profiles);
    }

    /// Take profile save request: returns working profiles if save was requested.
    pub fn take_profile_save_request(&mut self) -> Option<Vec<Profile>> {
        if self.profile_save_requested {
            self.profile_save_requested = false;
            Some(self.profile_modal_ui.get_working_profiles().to_vec())
        } else {
            None
        }
    }

    /// Take profile open request: returns and clears the profile ID to open.
    pub fn take_profile_open_request(&mut self) -> Option<ProfileId> {
        self.profile_open_requested.take()
    }

    /// Check whether the Assistant prompt library changed and clear the flag.
    pub fn take_assistant_prompts_changed(&mut self) -> bool {
        let changed = self.assistant_prompts_changed;
        self.assistant_prompts_changed = false;
        changed
    }
}

#[cfg(test)]
mod assistant_prompt_tests {
    use super::*;
    use par_term_config::{AssistantPrompt, Config};
    use std::path::PathBuf;

    #[test]
    fn settings_ui_new_with_assistant_prompts_uses_injected_prompt_state() {
        let prompt = AssistantPrompt {
            path: PathBuf::from("injected.md"),
            title: "Injected".to_string(),
            auto_submit: true,
            prompt: "Use this prompt".to_string(),
        };

        let settings = SettingsUI::new_with_assistant_prompts(
            Config::default(),
            vec![prompt.clone()],
            Some("injected error".to_string()),
        );

        assert_eq!(settings.assistant_prompts, vec![prompt]);
        assert_eq!(
            settings.assistant_prompt_error.as_deref(),
            Some("injected error")
        );
    }

    #[test]
    fn settings_ui_new_for_tests_initializes_empty_prompt_state_without_prompt_file_access() {
        let settings = SettingsUI::new_for_tests(Config::default());

        assert!(settings.assistant_prompts.is_empty());
        assert!(settings.assistant_prompt_error.is_none());
        assert_eq!(settings.editing_assistant_prompt_index, None);
        assert!(!settings.adding_new_assistant_prompt);
        assert_eq!(settings.temp_assistant_prompt_title, "");
        assert_eq!(settings.temp_assistant_prompt_body, "");
        assert!(!settings.temp_assistant_prompt_auto_submit);
        assert!(!settings.assistant_prompts_changed);
    }

    #[test]
    fn take_assistant_prompts_changed_returns_and_clears_flag() {
        let mut settings = SettingsUI::new_for_tests(Config::default());
        settings.assistant_prompts_changed = true;

        assert!(settings.take_assistant_prompts_changed());
        assert!(!settings.take_assistant_prompts_changed());
    }

    fn test_shader_lint_callback(
        path: &std::path::Path,
        brightness: Option<f32>,
        text_opacity: Option<f32>,
    ) -> Result<String, String> {
        Ok(format!(
            "linted {} brightness={:?} text_opacity={:?}",
            path.display(),
            brightness,
            text_opacity
        ))
    }

    #[test]
    fn run_shader_lint_for_selected_shader_stores_callback_result() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let shader_path = temp_dir.path().join("readable.glsl");
        std::fs::write(&shader_path, "void mainImage(out vec4 c, in vec2 p) {}").unwrap();

        let mut config = Config::default();
        config.shader.custom_shader = Some(shader_path.display().to_string());
        let mut settings = SettingsUI::new_for_tests(config);
        settings.temp_custom_shader = shader_path.display().to_string();
        settings.shader_lint_fn = Some(test_shader_lint_callback);

        settings.run_shader_lint_for_selected_shader();

        assert_eq!(
            settings.shader_lint_result,
            Some(format!(
                "linted {} brightness=Some(0.15) text_opacity=Some(1.0)",
                shader_path.display()
            ))
        );
        assert!(settings.shader_lint_error.is_none());
    }

    #[test]
    fn run_shader_lint_for_selected_shader_passes_per_shader_overrides() {
        let temp_dir = tempfile::tempdir().expect("temp dir");
        let shader_path = temp_dir.path().join("readable.glsl");
        let shader_name = shader_path.display().to_string();
        let mut config = Config::default();
        config.shader.custom_shader = Some(shader_name.clone());
        config
            .get_or_create_shader_override(&shader_name)
            .brightness = Some(0.3);
        config
            .get_or_create_shader_override(&shader_name)
            .text_opacity = Some(0.96);
        let mut settings = SettingsUI::new_for_tests(config);
        settings.temp_custom_shader = shader_name;
        settings.shader_lint_fn = Some(test_shader_lint_callback);

        settings.run_shader_lint_for_selected_shader();

        assert_eq!(
            settings.shader_lint_result,
            Some(format!(
                "linted {} brightness=Some(0.3) text_opacity=Some(0.96)",
                shader_path.display()
            ))
        );
    }

    #[test]
    fn clear_shader_lint_result_removes_result_and_error() {
        let mut settings = SettingsUI::new_for_tests(Config::default());
        settings.shader_lint_result = Some("Readability: 82/100".to_string());
        settings.shader_lint_error = Some("old error".to_string());

        settings.clear_shader_lint_result();

        assert!(settings.shader_lint_result.is_none());
        assert!(settings.shader_lint_error.is_none());
    }

    #[test]
    fn run_shader_lint_for_selected_shader_reports_missing_callback() {
        let mut settings = SettingsUI::new_for_tests(Config::default());
        settings.temp_custom_shader = "missing.glsl".to_string();

        settings.run_shader_lint_for_selected_shader();

        assert_eq!(
            settings.shader_lint_error.as_deref(),
            Some("Shader lint is not available")
        );
        assert!(settings.shader_lint_result.is_none());
    }
}