par-term-settings-ui 0.19.0

Settings UI for par-term terminal emulator
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
//! Import/Export Preferences section for the advanced settings tab.
//!
//! Covers: export to file, import from file (replace/merge), import from URL.
//! Also provides the public `merge_config` function used externally.

use crate::SettingsUI;
use crate::section::{INPUT_WIDTH, keyword_section};
use par_term_config::Config;
use std::collections::HashSet;

// ============================================================================
// Import/Export Section
// ============================================================================

pub(crate) fn show_import_export_section(
    ui: &mut egui::Ui,
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    collapsed: &mut HashSet<String>,
) {
    keyword_section(
        ui,
        "Import/Export Preferences",
        "advanced_import_export",
        &["backup"],
        true,
        collapsed,
        |ui| {
            ui.label("Export your current configuration or import settings from a file or URL.");
            ui.add_space(8.0);

            // --- Export ---
            ui.label(egui::RichText::new("Export").strong());
            ui.add_space(4.0);

            if ui
                .button("Export Preferences to File")
                .on_hover_text("Save the current configuration to a YAML file")
                .clicked()
            {
                export_preferences(settings);
            }

            ui.add_space(12.0);

            // --- Import from File ---
            ui.label(egui::RichText::new("Import from File").strong());
            ui.add_space(4.0);

            ui.horizontal(|ui| {
                if crate::delete_confirm::confirm_action_button(
                    ui,
                    &mut settings.pending_list_delete,
                    "import",
                    "file_replace",
                    "Import & Replace",
                ) {
                    import_preferences_from_file(settings, changes_this_frame, ImportMode::Replace);
                }

                if ui
                    .button("Import & Merge")
                    .on_hover_text(
                        "Merge settings from a file into the current configuration \
                         (only overrides non-default values)",
                    )
                    .clicked()
                {
                    import_preferences_from_file(settings, changes_this_frame, ImportMode::Merge);
                }
            });

            ui.add_space(12.0);

            // --- Import from URL ---
            ui.label(egui::RichText::new("Import from URL").strong());
            ui.add_space(4.0);

            ui.horizontal(|ui| {
                ui.label("URL:");
                ui.add(
                    egui::TextEdit::singleline(&mut settings.advanced_tab.temp_import_url)
                        .desired_width(INPUT_WIDTH)
                        .hint_text("https://example.com/config.yaml"),
                );
            });

            ui.horizontal(|ui| {
                // Only emptiness disables the buttons. The scheme is judged by
                // `validate_scheme` inside the fetch, which explains a rejection
                // in the status line — a silently greyed-out button for a
                // `file://` URL told the user nothing.
                let url_valid = !settings.advanced_tab.temp_import_url.trim().is_empty();

                let fetch_replace = ui
                    .add_enabled_ui(url_valid, |ui| {
                        crate::delete_confirm::confirm_action_button(
                            ui,
                            &mut settings.pending_list_delete,
                            "import",
                            "url_replace",
                            "Fetch & Replace",
                        )
                    })
                    .inner;
                if fetch_replace {
                    import_preferences_from_url(settings, changes_this_frame, ImportMode::Replace);
                }

                if ui
                    .add_enabled(url_valid, egui::Button::new("Fetch & Merge"))
                    .on_hover_text(
                        "Download and merge into the current configuration (https:// only)",
                    )
                    .clicked()
                {
                    import_preferences_from_url(settings, changes_this_frame, ImportMode::Merge);
                }
            });

            // Show status/error messages
            if let Some(ref msg) = settings.advanced_tab.import_export_status {
                ui.add_space(4.0);
                let color = if settings.advanced_tab.import_export_is_error {
                    egui::Color32::from_rgb(255, 100, 100)
                } else {
                    egui::Color32::from_rgb(100, 200, 100)
                };
                ui.label(egui::RichText::new(msg.as_str()).color(color));
            }

            ui.add_space(4.0);
            ui.label(
                egui::RichText::new(
                    "Merge mode preserves your existing settings and only applies \
                     values that differ from defaults in the imported file.",
                )
                .small()
                .color(egui::Color32::GRAY),
            );
        },
    );
}

// ============================================================================
// Import/Export Helpers
// ============================================================================

/// Maximum size of a configuration fetched from a URL (SEC-020).
///
/// Matches the dynamic-profile fetch limit (`DynamicProfileSource`'s default
/// `max_size_bytes`, enforced in `src/profile/dynamic/fetch.rs`) so both
/// remote-config paths cap the same way.
const MAX_IMPORT_SIZE_BYTES: u64 = 1_048_576;

/// Wall-clock cap on a preference-import fetch.
///
/// [`import_preferences_from_url`] runs on the winit main thread, so this bounds
/// how long the whole window can stop redrawing. The shared agent this replaced
/// set no timeout at all, which made an unresponsive endpoint an indefinite
/// freeze; 30 s matches the timeout the shader downloader and self-updater use.
const IMPORT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(30);

/// Build the agent used for preference imports.
///
/// The TLS provider must be named explicitly. ureq's default is
/// `TlsProvider::Rustls`, but the workspace builds ureq with
/// `default-features = false, features = ["native-tls", "gzip"]`, so the rustls
/// feature is absent — and ureq *panics* rather than erroring when the selected
/// provider's feature is missing ("uri scheme is https, provider is Rustls but
/// feature is not enabled"). The `Agent::new_with_defaults()` this replaced hit
/// exactly that, so importing from any https URL aborted the process. This
/// matches the configuration the shader downloader and self-updater already use.
fn import_agent() -> ureq::Agent {
    let tls_config = ureq::tls::TlsConfig::builder()
        .provider(ureq::tls::TlsProvider::NativeTls)
        .root_certs(ureq::tls::RootCerts::PlatformVerifier)
        .build();

    ureq::Agent::config_builder()
        .tls_config(tls_config)
        .timeout_global(Some(IMPORT_TIMEOUT))
        .build()
        .into()
}

/// Whether to replace or merge when importing preferences.
#[derive(Clone, Copy, PartialEq, Eq)]
enum ImportMode {
    /// Replace the entire configuration.
    Replace,
    /// Merge non-default values from the imported config.
    Merge,
}

/// Record an import/export outcome in the section's status line and, for a
/// failure, in the window's error banner (UX.md SS7).
fn set_import_export_status(settings: &mut SettingsUI, message: String, is_error: bool) {
    if is_error {
        settings.show_error_banner(message.clone());
    }
    settings.advanced_tab.import_export_status = Some(message);
    settings.advanced_tab.import_export_is_error = is_error;
}

/// Export the current configuration to a YAML file.
fn export_preferences(settings: &mut SettingsUI) {
    let path = rfd::FileDialog::new()
        .set_title("Export Preferences")
        .add_filter("YAML", &["yaml", "yml"])
        .set_file_name("par-term-config.yaml")
        .save_file();

    if let Some(path) = path {
        match serde_yaml_ng::to_string(&settings.config) {
            Ok(yaml) => {
                if let Err(e) = std::fs::write(&path, yaml) {
                    set_import_export_status(
                        settings,
                        format!("Failed to write file: {}", e),
                        true,
                    );
                    log::error!("Failed to export preferences: {}", e);
                } else {
                    set_import_export_status(
                        settings,
                        format!("Exported to {}", path.display()),
                        false,
                    );
                    log::info!("Exported preferences to {}", path.display());
                }
            }
            Err(e) => {
                set_import_export_status(
                    settings,
                    format!("Failed to serialize config: {}", e),
                    true,
                );
                log::error!("Failed to serialize preferences: {}", e);
            }
        }
    }
}

/// Import preferences from a local file.
fn import_preferences_from_file(
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    mode: ImportMode,
) {
    let path = rfd::FileDialog::new()
        .set_title("Import Preferences")
        .add_filter("YAML", &["yaml", "yml"])
        .pick_file();

    if let Some(path) = path {
        match std::fs::read_to_string(&path) {
            Ok(content) => {
                apply_imported_config(settings, changes_this_frame, &content, mode);
            }
            Err(e) => {
                set_import_export_status(settings, format!("Failed to read file: {}", e), true);
                log::error!("Failed to read preferences file: {}", e);
            }
        }
    }
}

/// Import preferences from a URL.
///
/// # Blocking
///
/// The fetch is synchronous and runs on the winit main thread, so the window
/// stops redrawing for its duration — bounded by [`IMPORT_TIMEOUT`]. Moving it
/// off-thread needs somewhere to park the in-flight result between frames,
/// which means a new field on `SettingsUI`; until then the timeout is what
/// keeps a dead endpoint from hanging the UI indefinitely.
fn import_preferences_from_url(
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    mode: ImportMode,
) {
    let url = settings.advanced_tab.temp_import_url.trim().to_string();
    if url.is_empty() {
        return;
    }

    // SEC-020: an imported config drives shell execution, startup commands and
    // profiles, so it must not be MITM-replaceable in transit.
    //
    // ARC-006: the same scheme allowlist the dynamic-profile fetch uses. The
    // previous `starts_with("https://")` test was a denylist in disguise — it
    // misclassified `HTTPS://` as insecure (RFC 3986 schemes are
    // case-insensitive) and, on the sibling path that opts into HTTP, let
    // `ftp:`, `data:` and single-slash `file:` through. No HTTP opt-in exists
    // here, so `allow_http` is false: this path is https-only.
    if let Err(message) = par_term_config::url_policy::validate_scheme(&url, false) {
        // The returned string is already a complete user-facing sentence.
        log::warn!("[SEC-020] refusing preference import: {}", message);
        set_import_export_status(settings, message, true);
        return;
    }

    let agent = import_agent();
    match agent.get(&url).call() {
        // SEC-020: cap the response so a hostile or broken endpoint cannot
        // stream an unbounded body into memory.
        Ok(mut response) => match response
            .body_mut()
            .with_config()
            .limit(MAX_IMPORT_SIZE_BYTES)
            .read_to_string()
        {
            Ok(body) => {
                apply_imported_config(settings, changes_this_frame, &body, mode);
            }
            Err(e) => {
                set_import_export_status(
                    settings,
                    format!(
                        "Failed to read response (limit {} bytes): {}",
                        MAX_IMPORT_SIZE_BYTES, e
                    ),
                    true,
                );
                log::error!("Failed to read URL response body: {}", e);
            }
        },
        Err(e) => {
            set_import_export_status(settings, format!("Failed to fetch URL: {}", e), true);
            log::error!("Failed to fetch preferences from URL: {}", e);
        }
    }
}

/// Parse YAML content as a Config and apply it to the settings.
fn apply_imported_config(
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    content: &str,
    mode: ImportMode,
) {
    match serde_yaml_ng::from_str::<Config>(content) {
        Ok(imported) => {
            match mode {
                ImportMode::Replace => {
                    settings.config = imported;
                }
                ImportMode::Merge => {
                    merge_config(&mut settings.config, &imported);
                }
            }
            settings.sync_all_temps_from_config();
            settings.has_changes = true;
            *changes_this_frame = true;
            set_import_export_status(
                settings,
                match mode {
                    ImportMode::Replace => "Configuration replaced successfully.".to_string(),
                    ImportMode::Merge => "Configuration merged successfully.".to_string(),
                },
                false,
            );
            log::info!(
                "Imported preferences (mode={:?})",
                match mode {
                    ImportMode::Replace => "replace",
                    ImportMode::Merge => "merge",
                }
            );
        }
        Err(e) => {
            set_import_export_status(settings, format!("Invalid config file: {}", e), true);
            log::error!("Failed to parse imported config: {}", e);
        }
    }
}

/// Merge an imported Config into the current config.
///
/// For each field, if the imported value differs from the default, it overwrites
/// the current value. This lets users share partial configs that only override
/// specific settings.
pub fn merge_config(current: &mut Config, imported: &Config) {
    let defaults = Config::default();

    // Serialize all three to serde_yaml_ng::Value for field-by-field comparison
    let default_val: serde_yaml_ng::Value =
        serde_yaml_ng::from_str(&serde_yaml_ng::to_string(&defaults).unwrap_or_default())
            .unwrap_or(serde_yaml_ng::Value::Null);
    let imported_val: serde_yaml_ng::Value =
        serde_yaml_ng::from_str(&serde_yaml_ng::to_string(imported).unwrap_or_default())
            .unwrap_or(serde_yaml_ng::Value::Null);
    let mut current_val: serde_yaml_ng::Value =
        serde_yaml_ng::from_str(&serde_yaml_ng::to_string(&*current).unwrap_or_default())
            .unwrap_or(serde_yaml_ng::Value::Null);

    if let (
        serde_yaml_ng::Value::Mapping(ref default_map),
        serde_yaml_ng::Value::Mapping(ref imported_map),
        serde_yaml_ng::Value::Mapping(current_map),
    ) = (default_val, imported_val, &mut current_val)
    {
        for (key, imported_field) in imported_map {
            let default_field = default_map.get(key);
            // Only override if the imported value differs from the default
            if default_field != Some(imported_field) {
                current_map.insert(key.clone(), imported_field.clone());
            }
        }
    }

    // Deserialize the merged value back into Config
    if let Ok(merged) = serde_yaml_ng::from_value::<Config>(current_val) {
        *current = merged;
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::settings_ui::BannerKind;

    #[test]
    fn invalid_import_shows_an_error_banner_and_keeps_the_config() {
        let mut settings = SettingsUI::new_for_tests(Config::default());
        let mut changed = false;

        apply_imported_config(
            &mut settings,
            &mut changed,
            "font_size: [",
            ImportMode::Replace,
        );

        assert_eq!(settings.banner().map(|b| b.kind), Some(BannerKind::Error));
        assert!(!changed);
        assert!(!settings.has_unsaved_changes());
    }

    #[test]
    fn scheme_rejection_shows_an_error_banner() {
        let mut settings = SettingsUI::new_for_tests(Config::default());
        settings.advanced_tab.temp_import_url = "http://example.com/c.yaml".to_string();
        let mut changed = false;

        import_preferences_from_url(&mut settings, &mut changed, ImportMode::Merge);

        assert_eq!(settings.banner().map(|b| b.kind), Some(BannerKind::Error));
    }
}