smtp-test-tool 0.1.1

Cross-platform SMTP / IMAP / POP3 connectivity tester with IT-actionable diagnostics.
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
//! eframe / egui GUI for smtp-test-tool.
//!
//! * Single static binary, no external runtime needed.
//! * Auto-follows OS dark/light via the `dark-light` crate.
//! * AccessKit screen-reader integration is enabled via the eframe feature.
//! * All status conveyed in text too - colour is never the only signal.

#![cfg_attr(all(windows, not(debug_assertions)), windows_subsystem = "windows")]

use eframe::egui;
use smtp_test_tool::config::{default_save_path, discover_config_path, Config};
use smtp_test_tool::providers::{self, Provider};
use smtp_test_tool::runner::{TestOutcome, TestResults};
use smtp_test_tool::theme::{detect as detect_appearance, Appearance, ThemeChoice};
use smtp_test_tool::tls::Security;
use smtp_test_tool::{outlook_defaults, run_tests, Profile};
use std::path::PathBuf;
use std::sync::mpsc::{Receiver, Sender};
use std::sync::{Arc, Mutex};
use std::thread;
use tracing::level_filters::LevelFilter;
use tracing_subscriber::layer::SubscriberExt;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::Layer;

// -----------------------------------------------------------------------
// Log capture - a custom tracing Layer that pushes formatted records
// into a Vec the GUI displays.  Thread-safe.
// -----------------------------------------------------------------------
#[derive(Clone, Copy, Debug)]
enum LogLevel {
    Trace,
    Debug,
    Info,
    Warn,
    Error,
}

#[derive(Clone, Debug)]
struct LogLine {
    level: LogLevel,
    text: String,
}

#[derive(Default)]
struct LogSink {
    lines: Mutex<Vec<LogLine>>,
}

impl LogSink {
    fn push(&self, level: LogLevel, text: String) {
        if let Ok(mut g) = self.lines.lock() {
            // Cap memory at 5000 lines so a long --wire run stays responsive.
            if g.len() > 5000 {
                g.drain(..1000);
            }
            g.push(LogLine { level, text });
        }
    }
    fn drain_into(&self, dst: &mut Vec<LogLine>) {
        if let Ok(mut g) = self.lines.lock() {
            dst.extend(g.drain(..));
        }
    }
}

struct GuiLayer {
    sink: Arc<LogSink>,
}

impl<S> Layer<S> for GuiLayer
where
    S: tracing::Subscriber,
{
    fn on_event(
        &self,
        event: &tracing::Event<'_>,
        _ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
        let mut visitor = FieldFmt::default();
        event.record(&mut visitor);
        let lvl = match *event.metadata().level() {
            tracing::Level::TRACE => LogLevel::Trace,
            tracing::Level::DEBUG => LogLevel::Debug,
            tracing::Level::INFO => LogLevel::Info,
            tracing::Level::WARN => LogLevel::Warn,
            tracing::Level::ERROR => LogLevel::Error,
        };
        self.sink.push(lvl, visitor.message);
    }
}

#[derive(Default)]
struct FieldFmt {
    message: String,
}

impl tracing::field::Visit for FieldFmt {
    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
        if field.name() == "message" {
            self.message = format!("{value:?}");
            // strip the surrounding quotes Debug puts on strings
            if self.message.starts_with('"') && self.message.ends_with('"') {
                self.message = self.message[1..self.message.len() - 1].to_string();
            }
        } else {
            self.message
                .push_str(&format!(" {}={value:?}", field.name()));
        }
    }
    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        if field.name() == "message" {
            self.message = value.to_string();
        } else {
            self.message.push_str(&format!(" {}={value}", field.name()));
        }
    }
}

// -----------------------------------------------------------------------
// Application state
// -----------------------------------------------------------------------
struct App {
    cfg_path: Option<PathBuf>,
    cfg: Config,
    profile_name: String,
    profile: Profile,
    log_sink: Arc<LogSink>,
    log_buf: Vec<LogLine>,
    show_pwd: bool,
    busy: bool,
    result_rx: Option<Receiver<TestResults>>,
    last_results: TestResults,
    to_csv: String,
    cc_csv: String,
    bcc_csv: String,
    tab: Tab,
    /// What the OS reported at startup; cached so 'Follow OS' does not
    /// re-shell-out to `defaults` / `gsettings` every frame.
    os_appearance: Appearance,
    /// Last appearance we actually applied via `Context::set_visuals`;
    /// lets us re-apply only on real change.
    applied_appearance: Appearance,
}

#[derive(PartialEq, Copy, Clone)]
enum Tab {
    Servers,
    Send,
    Tls,
    Advanced,
}

impl App {
    fn new(sink: Arc<LogSink>, cc: &eframe::CreationContext<'_>) -> Self {
        // Load config FIRST so we can honour the user's theme choice
        // (rule #4: dark + light, with manual override).
        let cfg_path = discover_config_path();
        // Surface any parse error so the user knows their config was
        // ignored - silent fallback used to mask real bugs.
        let cfg = cfg_path
            .as_ref()
            .and_then(|p| match Config::load(p) {
                Ok(c) => {
                    tracing::info!("loaded config {}", p.display());
                    Some(c)
                }
                Err(e) => {
                    tracing::warn!("failed to load config {}: {:#}", p.display(), e);
                    None
                }
            })
            .unwrap_or_else(|| Config {
                active: "default".into(),
                profiles: [("default".into(), outlook_defaults())]
                    .into_iter()
                    .collect(),
            });
        let profile_name = cfg.active.clone();
        let profile = cfg
            .profile(&profile_name)
            .cloned()
            .unwrap_or_else(outlook_defaults);

        // Detect OS appearance once (cached), then resolve through the
        // user's stored ThemeChoice (Auto / Dark / Light).
        let os_appearance = detect_appearance();
        let initial_choice = ThemeChoice::from_config_str(&profile.theme);
        let initial = initial_choice.resolve(os_appearance);
        cc.egui_ctx.set_visuals(visuals_for(initial));
        if os_appearance == Appearance::Unknown && initial_choice == ThemeChoice::Auto {
            tracing::info!("OS did not advertise a colour scheme; defaulting to dark");
        }

        let to_csv = profile.to.join(", ");
        let cc_csv = profile.cc.join(", ");
        let bcc_csv = profile.bcc.join(", ");

        Self {
            cfg_path,
            cfg,
            profile_name,
            profile,
            log_sink: sink,
            log_buf: Vec::new(),
            show_pwd: false,
            busy: false,
            result_rx: None,
            last_results: TestResults::default(),
            to_csv,
            cc_csv,
            bcc_csv,
            tab: Tab::Servers,
            os_appearance,
            applied_appearance: initial,
        }
    }

    /// Re-apply the user's current theme preference if it produces a
    /// different concrete appearance than what we last applied.  Called
    /// once per frame; cheap no-op when nothing changed.
    fn refresh_theme(&mut self, ctx: &egui::Context) {
        let choice = ThemeChoice::from_config_str(&self.profile.theme);
        let target = choice.resolve(self.os_appearance);
        if target != self.applied_appearance {
            ctx.set_visuals(visuals_for(target));
            self.applied_appearance = target;
            tracing::info!(
                "theme: now {} (choice={}, os={:?})",
                target_label(target),
                choice.as_str(),
                self.os_appearance
            );
        }
    }

    /// Overwrite the SMTP / IMAP / POP3 host, port, and security fields
    /// on the active profile from a curated provider preset.  Leaves
    /// every other field (credentials, profile name, theme, ...) alone.
    /// Providers without POP3 (iCloud, Proton Bridge) disable the POP3
    /// test rather than leaving stale data behind.
    fn apply_provider(&mut self, p: &Provider) {
        self.profile.smtp_host = p.smtp.host.into();
        self.profile.smtp_port = p.smtp.port;
        self.profile.smtp_security = p.smtp.security;
        self.profile.imap_host = p.imap.host.into();
        self.profile.imap_port = p.imap.port;
        self.profile.imap_security = p.imap.security;
        match p.pop {
            Some(pop) => {
                self.profile.pop_host = pop.host.into();
                self.profile.pop_port = pop.port;
                self.profile.pop_security = pop.security;
                // Leave pop_enabled untouched; user may want POP off
                // even on providers that support it.
            }
            None => {
                self.profile.pop_enabled = false;
            }
        }
        tracing::info!("applied provider preset: {}", p.name);
    }

    fn run_tests_async(&mut self) {
        // Sync CSV fields back into profile.
        self.profile.to = csv_to_vec(&self.to_csv);
        self.profile.cc = csv_to_vec(&self.cc_csv);
        self.profile.bcc = csv_to_vec(&self.bcc_csv);

        let (tx, rx): (Sender<TestResults>, Receiver<TestResults>) = std::sync::mpsc::channel();
        self.result_rx = Some(rx);
        self.busy = true;
        let profile = self.profile.clone();
        thread::spawn(move || {
            let r = run_tests(&profile);
            let _ = tx.send(r);
        });
    }

    fn save_config(&mut self) -> anyhow::Result<()> {
        // sync CSVs first
        self.profile.to = csv_to_vec(&self.to_csv);
        self.profile.cc = csv_to_vec(&self.cc_csv);
        self.profile.bcc = csv_to_vec(&self.bcc_csv);

        // No credential handling here: Profile.password and .oauth_token
        // are `#[serde(skip)]` so they are dropped at serialise time
        // unconditionally.  See AGENTS.md rule #8.
        self.cfg
            .upsert_profile(&self.profile_name, self.profile.clone());
        self.cfg.active = self.profile_name.clone();
        let target = self.cfg_path.clone().unwrap_or_else(default_save_path);
        self.cfg.save(&target)?;
        self.cfg_path = Some(target);
        Ok(())
    }
}

fn csv_to_vec(s: &str) -> Vec<String> {
    s.split(',')
        .map(|s| s.trim().to_string())
        .filter(|s| !s.is_empty())
        .collect()
}

impl eframe::App for App {
    // egui 0.34: `ui()` is the required entry; `update(ctx, frame)` is
    // deprecated and provided as a no-op default by the trait.
    fn ui(&mut self, root_ui: &mut egui::Ui, _frame: &mut eframe::Frame) {
        let ctx = root_ui.ctx().clone();
        // React to a theme change made on the Advanced tab the previous
        // frame.  No-op when the chosen theme already matches.
        self.refresh_theme(&ctx);
        // Drain log lines from the sink.
        self.log_sink.drain_into(&mut self.log_buf);
        if self.log_buf.len() > 5000 {
            let drop = self.log_buf.len() - 5000;
            self.log_buf.drain(..drop);
        }

        // Poll background test thread.
        if let Some(rx) = &self.result_rx {
            if let Ok(r) = rx.try_recv() {
                self.last_results = r;
                self.busy = false;
                self.result_rx = None;
            }
        }
        if self.busy {
            ctx.request_repaint_after(std::time::Duration::from_millis(150));
        }

        // ----- top bar ------------------------------------------------
        egui::Panel::top("top").show_inside(root_ui, |ui| {
            ui.horizontal(|ui| {
                ui.label("Profile:");
                let names = self.cfg.profile_names();
                egui::ComboBox::from_id_salt("profile")
                    .selected_text(&self.profile_name)
                    .show_ui(ui, |ui| {
                        for n in &names {
                            if ui.selectable_label(&self.profile_name == n, n).clicked() {
                                self.profile_name = n.clone();
                                if let Some(p) = self.cfg.profile(n) {
                                    self.profile = p.clone();
                                    self.to_csv = self.profile.to.join(", ");
                                    self.cc_csv = self.profile.cc.join(", ");
                                    self.bcc_csv = self.profile.bcc.join(", ");
                                }
                            }
                        }
                    });
                if ui.button("Save Config").clicked() {
                    if let Err(e) = self.save_config() {
                        tracing::error!("save failed: {e:#}");
                    } else {
                        tracing::info!(
                            "Saved profile [{}] to {}",
                            self.profile_name,
                            self.cfg_path
                                .as_ref()
                                .map(|p| p.display().to_string())
                                .unwrap_or_default()
                        );
                    }
                }
                // Provider preset menu: applies one curated set of
                // host/port/security values to all three protocol
                // blocks below.  Other fields (credentials, etc.) are
                // left alone.
                let mut chosen: Option<&'static Provider> = None;
                // "..." rather than a unicode arrow because the default
                // egui font ships without U+25BE (small down-pointing
                // triangle) and falls back to a tofu glyph.
                ui.menu_button("Provider preset...", |ui| {
                    for p in providers::PROVIDERS {
                        let mut label = p.name.to_string();
                        if p.pop.is_none() {
                            label.push_str("  (no POP3)");
                        }
                        if ui.button(label).clicked() {
                            chosen = Some(p);
                            ui.close();
                        }
                    }
                });
                if let Some(p) = chosen {
                    self.apply_provider(p);
                    if let Some(note) = p.note {
                        tracing::info!("note: {note}");
                    }
                }
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    ui.label(
                        self.cfg_path
                            .as_ref()
                            .map(|p| format!("{}", p.display()))
                            .unwrap_or_else(|| "no config file".into()),
                    );
                });
            });
        });

        // ----- bottom: action bar + summary ---------------------------
        egui::Panel::bottom("bottom").show_inside(root_ui, |ui| {
            ui.horizontal(|ui| {
                let run = ui.add_enabled(
                    !self.busy,
                    egui::Button::new(if self.busy { "Running..." } else { "Run Test" }),
                );
                if run.clicked() {
                    self.run_tests_async();
                }
                ui.separator();
                outcome_chip(ui, "SMTP", self.last_results.smtp);
                outcome_chip(ui, "IMAP", self.last_results.imap);
                outcome_chip(ui, "POP3", self.last_results.pop3);
                ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                    if ui.button("Clear Log").clicked() {
                        self.log_buf.clear();
                    }
                });
            });
        });

        // ----- log panel along the bottom (own region, deterministic
        // height) so the tab content above never fights it for space.
        // egui 0.34: BottomPanel can have a fixed default + be resizable
        // by the user via the splitter at the top edge.
        egui::Panel::bottom("log")
            .resizable(true)
            .default_size(260.0)
            .min_size(120.0)
            .show_inside(root_ui, |ui| {
                ui.label(egui::RichText::new("Log").strong());
                egui::ScrollArea::vertical()
                    .stick_to_bottom(true)
                    .auto_shrink([false, false])
                    .show(ui, |ui| {
                        for line in &self.log_buf {
                            let (color, tag) = level_style(line.level, ui.visuals().dark_mode);
                            ui.horizontal_wrapped(|ui| {
                                ui.label(egui::RichText::new(tag).color(color).monospace());
                                ui.label(egui::RichText::new(&line.text).monospace());
                            });
                        }
                    });
            });

        // ----- main: tabs + tab content fills the remaining space ----
        // CentralPanel must be added AFTER all other panels per egui 0.34.
        egui::CentralPanel::default().show_inside(root_ui, |ui| {
            ui.horizontal(|ui| {
                ui.selectable_value(&mut self.tab, Tab::Servers, "Servers");
                ui.selectable_value(&mut self.tab, Tab::Send, "Send Mail");
                ui.selectable_value(&mut self.tab, Tab::Tls, "TLS / Auth");
                ui.selectable_value(&mut self.tab, Tab::Advanced, "Advanced");
            });
            ui.separator();

            egui::ScrollArea::vertical()
                .auto_shrink([false, false])
                .show(ui, |ui| match self.tab {
                    Tab::Servers => tab_servers(ui, self),
                    Tab::Send => tab_send(ui, self),
                    Tab::Tls => tab_tls(ui, self),
                    Tab::Advanced => tab_advanced(ui, self),
                });
        });
    }
}

// ---------- helpers -------------------------------------------------------

fn visuals_for(a: Appearance) -> egui::Visuals {
    match a {
        Appearance::Light => egui::Visuals::light(),
        // Both Dark and (defensively) Unknown map to dark, matching the
        // documented fallback in ThemeChoice::resolve.
        Appearance::Dark | Appearance::Unknown => egui::Visuals::dark(),
    }
}

fn target_label(a: Appearance) -> &'static str {
    match a {
        Appearance::Dark => "dark",
        Appearance::Light => "light",
        Appearance::Unknown => "dark (fallback)",
    }
}

/// Show the resolved OS hint next to 'Follow OS' so the user knows
/// what Auto currently maps to.
fn theme_label(choice: ThemeChoice, os: Appearance) -> String {
    match choice {
        ThemeChoice::Auto => format!("Follow OS ({})", target_label(os)),
        ThemeChoice::Dark => "Dark".to_string(),
        ThemeChoice::Light => "Light".to_string(),
    }
}

fn outcome_chip(ui: &mut egui::Ui, name: &str, o: Option<TestOutcome>) {
    let (txt, col) = match o {
        Some(TestOutcome::Pass) => (
            format!("{name}: PASS"),
            egui::Color32::from_rgb(0x0e, 0x7c, 0x0e),
        ),
        Some(TestOutcome::Fail) => (
            format!("{name}: FAIL"),
            egui::Color32::from_rgb(0xa3, 0x00, 0x00),
        ),
        Some(TestOutcome::Skipped) => (format!("{name}: skip"), egui::Color32::GRAY),
        None => (format!("{name}: -"), egui::Color32::GRAY),
    };
    ui.label(egui::RichText::new(txt).color(col).monospace());
}

fn level_style(lvl: LogLevel, dark: bool) -> (egui::Color32, &'static str) {
    if dark {
        match lvl {
            LogLevel::Trace => (egui::Color32::from_rgb(0xa0, 0xa0, 0xa0), "[TRACE]"),
            LogLevel::Debug => (egui::Color32::from_rgb(0xa0, 0xa0, 0xa0), "[DEBUG]"),
            LogLevel::Info => (egui::Color32::from_rgb(0xf0, 0xf0, 0xf0), "[INFO ]"),
            LogLevel::Warn => (egui::Color32::from_rgb(0xff, 0xd1, 0x66), "[WARN ]"),
            LogLevel::Error => (egui::Color32::from_rgb(0xff, 0x6b, 0x6b), "[ERROR]"),
        }
    } else {
        match lvl {
            LogLevel::Trace => (egui::Color32::from_rgb(0x55, 0x55, 0x55), "[TRACE]"),
            LogLevel::Debug => (egui::Color32::from_rgb(0x55, 0x55, 0x55), "[DEBUG]"),
            LogLevel::Info => (egui::Color32::from_rgb(0x11, 0x11, 0x11), "[INFO ]"),
            LogLevel::Warn => (egui::Color32::from_rgb(0x8a, 0x4b, 0x00), "[WARN ]"),
            LogLevel::Error => (egui::Color32::from_rgb(0xa3, 0x00, 0x00), "[ERROR]"),
        }
    }
}

// ---------- tabs ----------------------------------------------------------
fn tab_servers(ui: &mut egui::Ui, a: &mut App) {
    // Credentials: use ui.horizontal() rows (like proto_block) rather than
    // a Grid, because Grid sizes cells by intrinsic content and never
    // grows text-edits.  We left-align labels to a fixed width column
    // (LABEL_W) so they line up vertically, then hand the remainder of
    // the row to the entry.
    const LABEL_W: f32 = 100.0;
    const SHOW_W: f32 = 70.0; // approx "☑ Show" checkbox
    const HINT_W: f32 = 160.0; // approx "(XOAUTH2, optional)"

    ui.horizontal(|ui| {
        ui.add_sized([LABEL_W, 0.0], egui::Label::new("Username:"));
        let mut u = a.profile.user.clone().unwrap_or_default();
        let resp = ui.add_sized(
            [ui.available_width(), 0.0],
            egui::TextEdit::singleline(&mut u),
        );
        if resp.changed() {
            a.profile.user = Some(u).filter(|s| !s.is_empty());
        }
    });
    ui.horizontal(|ui| {
        ui.add_sized([LABEL_W, 0.0], egui::Label::new("Password:"));
        let mut pwd = a.profile.password.clone().unwrap_or_default();
        let entry_w = (ui.available_width() - SHOW_W).max(80.0);
        let resp = ui.add_sized(
            [entry_w, 0.0],
            egui::TextEdit::singleline(&mut pwd).password(!a.show_pwd),
        );
        if resp.changed() {
            a.profile.password = Some(pwd).filter(|s| !s.is_empty());
        }
        ui.checkbox(&mut a.show_pwd, "Show");
    });
    ui.horizontal(|ui| {
        ui.add_sized([LABEL_W, 0.0], egui::Label::new("OAuth token:"));
        let mut t = a.profile.oauth_token.clone().unwrap_or_default();
        let entry_w = (ui.available_width() - HINT_W).max(80.0);
        let resp = ui.add_sized(
            [entry_w, 0.0],
            egui::TextEdit::singleline(&mut t).password(true),
        );
        if resp.changed() {
            a.profile.oauth_token = Some(t).filter(|s| !s.is_empty());
        }
        ui.add_sized(
            [HINT_W, 0.0],
            egui::Label::new(egui::RichText::new("(XOAUTH2, optional)").weak()),
        );
    });
    ui.separator();
    proto_block(
        ui,
        "SMTP",
        &mut a.profile.smtp_enabled,
        &mut a.profile.smtp_host,
        &mut a.profile.smtp_port,
        &mut a.profile.smtp_security,
    );
    proto_block(
        ui,
        "IMAP",
        &mut a.profile.imap_enabled,
        &mut a.profile.imap_host,
        &mut a.profile.imap_port,
        &mut a.profile.imap_security,
    );
    proto_block(
        ui,
        "POP3",
        &mut a.profile.pop_enabled,
        &mut a.profile.pop_host,
        &mut a.profile.pop_port,
        &mut a.profile.pop_security,
    );
}

fn proto_block(
    ui: &mut egui::Ui,
    name: &str,
    enabled: &mut bool,
    host: &mut String,
    port: &mut u16,
    sec: &mut Security,
) {
    ui.horizontal(|ui| {
        ui.checkbox(enabled, format!("Test {name}"));
        ui.label("Host:");
        ui.text_edit_singleline(host);
        ui.label("Port:");
        ui.add(egui::DragValue::new(port).range(1..=65535));
        ui.label("Security:");
        egui::ComboBox::from_id_salt(format!("{name}-sec"))
            .selected_text(sec.as_str())
            .show_ui(ui, |ui| {
                ui.selectable_value(sec, Security::None, "none");
                ui.selectable_value(sec, Security::StartTls, "starttls");
                ui.selectable_value(sec, Security::Implicit, "ssl");
            });
    });
}

fn tab_send(ui: &mut egui::Ui, a: &mut App) {
    ui.checkbox(
        &mut a.profile.send_test,
        "Actually send a test email (otherwise only AUTH is tested)",
    );
    ui.separator();
    egui::Grid::new("msg").num_columns(2).show(ui, |ui| {
        opt_line(ui, "MAIL FROM (envelope):", &mut a.profile.mail_from);
        opt_line(ui, "From: (header)       :", &mut a.profile.from_addr);
        ui.label("To  (comma sep):");
        ui.text_edit_singleline(&mut a.to_csv);
        ui.end_row();
        ui.label("Cc  (comma sep):");
        ui.text_edit_singleline(&mut a.cc_csv);
        ui.end_row();
        ui.label("Bcc (comma sep):");
        ui.text_edit_singleline(&mut a.bcc_csv);
        ui.end_row();
        opt_line(ui, "Reply-To:", &mut a.profile.reply_to);
        ui.label("Subject:");
        ui.text_edit_singleline(&mut a.profile.subject);
        ui.end_row();
    });
    ui.label("Body:");
    ui.add(
        egui::TextEdit::multiline(&mut a.profile.body)
            .desired_rows(6)
            .desired_width(f32::INFINITY),
    );
}

fn opt_line(ui: &mut egui::Ui, label: &str, v: &mut Option<String>) {
    ui.label(label);
    let mut buf = v.clone().unwrap_or_default();
    if ui.text_edit_singleline(&mut buf).changed() {
        *v = if buf.is_empty() { None } else { Some(buf) };
    }
    ui.end_row();
}

fn tab_tls(ui: &mut egui::Ui, a: &mut App) {
    ui.checkbox(
        &mut a.profile.insecure_tls,
        "Disable certificate verification (INSECURE - testing only)",
    );
    ui.horizontal(|ui| {
        ui.label("CA bundle (PEM):");
        let mut buf = a
            .profile
            .ca_file
            .as_ref()
            .map(|p| p.display().to_string())
            .unwrap_or_default();
        if ui.text_edit_singleline(&mut buf).changed() {
            a.profile.ca_file = if buf.is_empty() {
                None
            } else {
                Some(buf.into())
            };
        }
    });
}

fn tab_advanced(ui: &mut egui::Ui, a: &mut App) {
    egui::Grid::new("adv").num_columns(2).show(ui, |ui| {
        ui.label("Timeout (s):");
        ui.add(egui::DragValue::new(&mut a.profile.timeout_secs).range(1..=600));
        ui.end_row();

        ui.label("EHLO/HELO name:");
        let mut e = a.profile.ehlo_name.clone().unwrap_or_default();
        if ui.text_edit_singleline(&mut e).changed() {
            a.profile.ehlo_name = if e.is_empty() { None } else { Some(e) };
        }
        ui.end_row();

        ui.label("IMAP folder:");
        ui.text_edit_singleline(&mut a.profile.imap_folder);
        ui.end_row();

        ui.label("Log level:");
        egui::ComboBox::from_id_salt("loglvl")
            .selected_text(&a.profile.log_level)
            .show_ui(ui, |ui| {
                for lv in ["trace", "debug", "info", "warn", "error"] {
                    ui.selectable_value(&mut a.profile.log_level, lv.into(), lv);
                }
            });
        ui.end_row();

        ui.label("Theme:");
        let mut current = ThemeChoice::from_config_str(&a.profile.theme);
        let previous = current;
        egui::ComboBox::from_id_salt("themechoice")
            .selected_text(theme_label(current, a.os_appearance))
            .show_ui(ui, |ui| {
                ui.selectable_value(
                    &mut current,
                    ThemeChoice::Auto,
                    theme_label(ThemeChoice::Auto, a.os_appearance),
                );
                ui.selectable_value(&mut current, ThemeChoice::Dark, "Dark");
                ui.selectable_value(&mut current, ThemeChoice::Light, "Light");
            });
        if current != previous {
            a.profile.theme = current.as_str().to_string();
        }
        ui.end_row();
    });
}

// -----------------------------------------------------------------------
// main
// -----------------------------------------------------------------------
fn main() -> eframe::Result<()> {
    let sink = Arc::new(LogSink::default());
    let layer = GuiLayer { sink: sink.clone() };
    // The GUI log panel shows user-relevant events.  Default to INFO so we
    // do not flood it with eframe/winit/glow internal trace lines; advanced
    // users can opt into DEBUG by setting RUST_LOG, e.g.:
    //   RUST_LOG=smtp_test_tool=debug smtp-test-tool-gui
    let filter = tracing_subscriber::EnvFilter::try_from_default_env().unwrap_or_else(|_| {
        tracing_subscriber::EnvFilter::new("info,eframe=warn,winit=warn,wgpu_core=warn,naga=warn")
    });
    tracing_subscriber::registry()
        .with(filter)
        .with(layer)
        .init();
    // LevelFilter is still re-exported, keep the import so future tweaks
    // don't need a re-edit.
    let _keep = LevelFilter::INFO;

    let opts = eframe::NativeOptions {
        viewport: egui::ViewportBuilder::default()
            .with_inner_size([960.0, 760.0])
            .with_min_inner_size([720.0, 520.0])
            .with_title("SMTP Test Tool"),
        ..Default::default()
    };
    eframe::run_native(
        "SMTP Test Tool",
        opts,
        Box::new(|cc| Ok(Box::new(App::new(sink, cc)))),
    )
}