par-term-settings-ui 0.7.0

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
//! Dynamic profile sources section.
//!
//! Manages remote URL profile sources: list, enable/disable, edit form, HTTP headers.

use crate::section::{collapsing_section, collapsing_section_with_state};
use crate::settings_ui::SettingsUI;
use par_term_config::ConflictResolution;
use par_term_config::DynamicProfileSource;
use std::collections::HashSet;

/// Show the dynamic profile sources section.
pub(super) fn show_dynamic_sources_section(
    ui: &mut egui::Ui,
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    collapsed: &mut HashSet<String>,
) {
    collapsing_section_with_state(
        ui,
        "Dynamic Profile Sources",
        "profiles_dynamic_sources",
        true,
        collapsed,
        |ui, collapsed| {
            ui.label(
                egui::RichText::new(
                    "Fetch profile definitions from remote URLs for team-shared configurations.",
                )
                .small()
                .color(egui::Color32::GRAY),
            );
            ui.add_space(4.0);

            // Collect mutations to apply after iteration
            let mut delete_index: Option<usize> = None;
            let mut toggle_index: Option<usize> = None;
            let mut start_edit_index: Option<usize> = None;

            let source_count = settings.config.dynamic_profile_sources.len();

            if source_count == 0 && settings.dynamic_source_editing.is_none() {
                ui.label(
                    egui::RichText::new("No dynamic profile sources configured.")
                        .color(egui::Color32::GRAY),
                );
            }

            // Show each source
            for i in 0..source_count {
                let is_editing = settings.dynamic_source_editing == Some(i);

                if is_editing {
                    // Show inline edit form
                    show_dynamic_source_edit_form(
                        ui,
                        settings,
                        changes_this_frame,
                        Some(i),
                        collapsed,
                    );
                } else {
                    let source = &settings.config.dynamic_profile_sources[i];

                    ui.horizontal(|ui| {
                        // Enabled checkbox
                        let mut enabled = source.enabled;
                        if ui.checkbox(&mut enabled, "").changed() {
                            toggle_index = Some(i);
                        }

                        // URL (truncated)
                        let url_display = if source.url.len() > 60 {
                            format!("{}...", &source.url[..57])
                        } else {
                            source.url.clone()
                        };
                        ui.label(egui::RichText::new(&url_display).monospace().color(
                            if source.enabled {
                                egui::Color32::LIGHT_GRAY
                            } else {
                                egui::Color32::DARK_GRAY
                            },
                        ))
                        .on_hover_text(&source.url);

                        // Right-aligned buttons
                        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                            // Delete button (rightmost)
                            if ui
                                .small_button(
                                    egui::RichText::new("Remove")
                                        .color(egui::Color32::from_rgb(200, 80, 80)),
                                )
                                .clicked()
                            {
                                delete_index = Some(i);
                            }

                            // Edit button
                            if ui.small_button("Edit").clicked() {
                                start_edit_index = Some(i);
                            }

                            // Status info
                            let conflict_label = source.conflict_resolution.display_name();
                            ui.label(
                                egui::RichText::new(conflict_label)
                                    .small()
                                    .color(egui::Color32::GRAY),
                            );
                        });
                    });
                }
            }

            // Apply mutations after iteration
            if let Some(i) = delete_index {
                settings.config.dynamic_profile_sources.remove(i);
                settings.has_changes = true;
                *changes_this_frame = true;
                // Reset editing state if we deleted the item being edited
                if settings.dynamic_source_editing == Some(i) {
                    settings.dynamic_source_editing = None;
                    settings.dynamic_source_edit_buffer = None;
                } else if let Some(editing) = settings.dynamic_source_editing {
                    // Adjust editing index if a preceding item was deleted
                    if editing > i {
                        settings.dynamic_source_editing = Some(editing - 1);
                    }
                }
            }

            if let Some(i) = toggle_index {
                settings.config.dynamic_profile_sources[i].enabled =
                    !settings.config.dynamic_profile_sources[i].enabled;
                settings.has_changes = true;
                *changes_this_frame = true;
            }

            if let Some(i) = start_edit_index {
                settings.dynamic_source_editing = Some(i);
                settings.dynamic_source_edit_buffer =
                    Some(settings.config.dynamic_profile_sources[i].clone());
                settings.dynamic_source_new_header_key = String::new();
                settings.dynamic_source_new_header_value = String::new();
            }

            ui.separator();

            // Show "add new" form if editing index is set to a new entry sentinel
            let is_adding = settings.dynamic_source_editing.is_some()
                && settings
                    .dynamic_source_editing
                    .expect("dynamic_source_editing checked is_some() above")
                    >= source_count;
            if is_adding {
                show_dynamic_source_edit_form(ui, settings, changes_this_frame, None, collapsed);
            } else if settings.dynamic_source_editing.is_none()
                && ui.button("+ Add Source").clicked()
            {
                // Use source_count as sentinel for "new entry"
                settings.dynamic_source_editing = Some(source_count);
                settings.dynamic_source_edit_buffer = Some(DynamicProfileSource::default());
                settings.dynamic_source_new_header_key = String::new();
                settings.dynamic_source_new_header_value = String::new();
            }
        },
    );
}

/// Show the edit form for a dynamic profile source.
///
/// `edit_index` is `Some(i)` when editing an existing source, `None` when adding a new one.
fn show_dynamic_source_edit_form(
    ui: &mut egui::Ui,
    settings: &mut SettingsUI,
    changes_this_frame: &mut bool,
    edit_index: Option<usize>,
    collapsed: &mut HashSet<String>,
) {
    ui.separator();

    // Save / Cancel buttons at top (always visible)
    ui.horizontal(|ui| {
        if ui.button("Save").clicked() {
            if let Some(buffer) = settings.dynamic_source_edit_buffer.take() {
                if let Some(i) = edit_index {
                    // Update existing source
                    settings.config.dynamic_profile_sources[i] = buffer;
                } else {
                    // Add new source
                    settings.config.dynamic_profile_sources.push(buffer);
                }
                settings.has_changes = true;
                *changes_this_frame = true;
            }
            settings.dynamic_source_editing = None;
        }

        if ui.button("Cancel").clicked() {
            settings.dynamic_source_editing = None;
            settings.dynamic_source_edit_buffer = None;
        }
    });

    ui.separator();

    // Edit form fields inside a scrollable area
    if settings.dynamic_source_edit_buffer.is_some() {
        // Split borrows: extract header-key/value pointers separately before
        // borrowing edit_buffer as mut so we stay within Rust's borrow rules.
        let (source, new_header_key, new_header_value) = {
            let s = settings;
            (
                s.dynamic_source_edit_buffer.as_mut().unwrap(),
                &mut s.dynamic_source_new_header_key,
                &mut s.dynamic_source_new_header_value,
            )
        };

        egui::ScrollArea::vertical()
            .max_height(350.0)
            .id_salt("dynamic_source_edit_scroll")
            .show(ui, |ui| {
                egui::Grid::new("dynamic_source_edit_grid")
                    .num_columns(2)
                    .spacing([12.0, 6.0])
                    .show(ui, |ui| {
                        // URL
                        ui.label("URL:");
                        ui.add(
                            egui::TextEdit::singleline(&mut source.url)
                                .desired_width(350.0)
                                .hint_text("https://example.com/profiles.yaml"),
                        );
                        ui.end_row();

                        // Enabled
                        ui.label("Enabled:");
                        ui.checkbox(&mut source.enabled, "");
                        ui.end_row();

                        // Refresh interval (seconds -> displayed as minutes)
                        ui.label("Refresh interval:");
                        let mut minutes = (source.refresh_interval_secs as f32 / 60.0).round();
                        if ui
                            .add(
                                egui::Slider::new(&mut minutes, 1.0..=60.0)
                                    .suffix(" min")
                                    .integer(),
                            )
                            .changed()
                        {
                            source.refresh_interval_secs = (minutes as u64) * 60;
                        }
                        ui.end_row();

                        // Max download size (bytes -> displayed as KB)
                        ui.label("Max download size:");
                        let mut kb = (source.max_size_bytes as f32 / 1024.0).round() as u32;
                        if ui
                            .add(
                                egui::DragValue::new(&mut kb)
                                    .range(1..=10240)
                                    .suffix(" KB")
                                    .speed(10),
                            )
                            .changed()
                        {
                            source.max_size_bytes = kb as usize * 1024;
                        }
                        ui.end_row();

                        // Fetch timeout
                        ui.label("Fetch timeout:");
                        let mut timeout = source.fetch_timeout_secs as u32;
                        if ui
                            .add(
                                egui::Slider::new(&mut timeout, 5..=60)
                                    .suffix(" sec")
                                    .integer(),
                            )
                            .changed()
                        {
                            source.fetch_timeout_secs = timeout as u64;
                        }
                        ui.end_row();

                        // Conflict resolution
                        ui.label("Conflict resolution:");
                        egui::ComboBox::from_id_salt("dynamic_source_conflict")
                            .selected_text(source.conflict_resolution.display_name())
                            .show_ui(ui, |ui| {
                                for variant in ConflictResolution::variants() {
                                    ui.selectable_value(
                                        &mut source.conflict_resolution,
                                        variant.clone(),
                                        variant.display_name(),
                                    );
                                }
                            });
                        ui.end_row();
                    });

                ui.add_space(8.0);

                show_headers_section(ui, source, new_header_key, new_header_value, collapsed);
            });
    }

    ui.separator();
}

/// Show the HTTP headers collapsing section within the edit form.
fn show_headers_section(
    ui: &mut egui::Ui,
    source: &mut DynamicProfileSource,
    new_header_key: &mut String,
    new_header_value: &mut String,
    collapsed: &mut HashSet<String>,
) {
    let header_count = source.headers.len();
    let header_label = if header_count > 0 {
        format!("HTTP Headers ({})", header_count)
    } else {
        "HTTP Headers".to_string()
    };
    let http_default_open = header_count > 0;
    collapsing_section(
        ui,
        &header_label,
        "dynamic_source_headers",
        http_default_open,
        collapsed,
        |ui| {
            ui.label(
                egui::RichText::new(
                    "Custom headers sent with each fetch request (e.g., Authorization).",
                )
                .small()
                .color(egui::Color32::GRAY),
            );
            ui.add_space(4.0);

            let mut delete_header_key: Option<String> = None;

            if !source.headers.is_empty() {
                // Sort keys for stable display order
                let mut sorted_keys: Vec<String> = source.headers.keys().cloned().collect();
                sorted_keys.sort();

                egui::Grid::new("dynamic_source_headers_grid")
                    .num_columns(3)
                    .spacing([8.0, 4.0])
                    .show(ui, |ui| {
                        ui.label(egui::RichText::new("Key").small().strong());
                        ui.label(egui::RichText::new("Value").small().strong());
                        ui.label(""); // Delete column
                        ui.end_row();

                        for key in &sorted_keys {
                            ui.label(egui::RichText::new(key).monospace());

                            // Show value (mask if Authorization-like)
                            let value = &source.headers[key];
                            let display_value = if key.to_lowercase().contains("auth")
                                || key.to_lowercase().contains("token")
                            {
                                if value.len() > 8 {
                                    format!("{}...", &value[..8])
                                } else {
                                    "*".repeat(value.len())
                                }
                            } else {
                                value.clone()
                            };
                            ui.label(
                                egui::RichText::new(&display_value)
                                    .monospace()
                                    .color(egui::Color32::GRAY),
                            );

                            if ui
                                .small_button(
                                    egui::RichText::new("X")
                                        .color(egui::Color32::from_rgb(200, 80, 80)),
                                )
                                .on_hover_text("Remove header")
                                .clicked()
                            {
                                delete_header_key = Some(key.clone());
                            }
                            ui.end_row();
                        }
                    });
            }

            if let Some(key) = delete_header_key {
                source.headers.remove(&key);
            }

            ui.add_space(4.0);

            // Add header form
            ui.horizontal(|ui| {
                ui.add(
                    egui::TextEdit::singleline(new_header_key)
                        .desired_width(120.0)
                        .hint_text("Header name"),
                );
                ui.add(
                    egui::TextEdit::singleline(new_header_value)
                        .desired_width(180.0)
                        .hint_text("Header value"),
                );
                if ui
                    .small_button("+ Add")
                    .on_hover_text("Add header")
                    .clicked()
                    && !new_header_key.is_empty()
                {
                    source
                        .headers
                        .insert(new_header_key.clone(), new_header_value.clone());
                    new_header_key.clear();
                    new_header_value.clear();
                }
            });
        },
    );
}