zippa-db 0.1.1

A fast, lightweight, cross-platform database client for PostgreSQL, MySQL, and SQLite.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
//! The connection editor: the form that was once half of the welcome screen,
//! now a dialog opened from the launcher.
//!
//! [`ConnectionEditor`] is only the *body* of the dialog; the surface around it
//! is `gpui_kit`'s `Dialog`, opened by [`Welcome`](super::Welcome). It emits
//! [`EditorEvent`] and the launcher reacts, the way [`Session`](crate::ui::session::Session)
//! reacts to its panels.

use gpui_kit::assets::IconName;
use gpui_kit::base::TestSupportExt;
use gpui_kit::component::button::{Button, ButtonCustomVariant, ButtonVariants, DropdownButton};
use gpui_kit::component::input::{Input, InputEvent, InputState};
use gpui_kit::component::menu::PopupMenuItem;
use gpui_kit::component::scroll::ScrollableElement;
use gpui_kit::component::{ActiveTheme, Icon, Selectable, Sizable, h_flex, v_flex};
use gpui_kit::prelude::*;
use gpui_kit::{App, Context, Entity, EventEmitter, SharedString, Task, Window, actions, div, px};
use uuid::Uuid;

use crate::db::store::SecretEdits;
use crate::db::{
    Connection, ConnectionConfig, Engine, SafetyMode, SshAuth, SshConfig, SslConfig, SslMode,
    TagColor, is_risky_auto_apply, runtime, store,
};
use crate::ui::busy::spinner;

actions!(zippa_db, [EditorClose, EditorConnect]);

/// What the editor asks its owner to do.
pub enum EditorEvent {
    /// Save the connection without connecting.
    ///
    /// Each of `secrets` is `None` when the user never touched its box, so a
    /// save that was not about the password leaves the stored one alone.
    Saved {
        config: ConnectionConfig,
        secrets: SecretEdits,
    },
    /// Connect with this config, saving it first when `save` is set.
    ///
    /// `secrets` means what it does for [`EditorEvent::Saved`]: `None` for a
    /// box the user never touched, `Some("")` for one they emptied.
    Connect {
        config: ConnectionConfig,
        secrets: SecretEdits,
        save: bool,
    },
    /// The dialog was dismissed without saving or connecting.
    Dismissed,
}

pub struct ConnectionEditor {
    /// `None` while editing a connection that has not been saved.
    id: Option<Uuid>,
    engine: Engine,
    safety: SafetyMode,
    color: Option<TagColor>,
    name: Entity<InputState>,
    host: Entity<InputState>,
    port: Entity<InputState>,
    username: Entity<InputState>,
    password: Entity<InputState>,
    database: Entity<InputState>,
    ssl_mode: SslMode,
    /// The certificate files encryption may need: an authority to trust, and
    /// the client's own certificate and key.
    ssl_ca: Entity<InputState>,
    ssl_cert: Entity<InputState>,
    ssl_key: Entity<InputState>,
    /// The SSH tunnel: whether there is one, how it signs in, and its boxes.
    ssh_enabled: bool,
    ssh_auth: SshAuth,
    ssh_host: Entity<InputState>,
    ssh_port: Entity<InputState>,
    ssh_user: Entity<InputState>,
    ssh_key: Entity<InputState>,
    /// The SSH password or key passphrase. Like the database password, never
    /// loaded back from the keychain, so `ssh_secret_edited` tells an
    /// untouched box from an emptied one.
    ssh_secret: Entity<InputState>,
    ssh_secret_edited: bool,
    /// How the saved connection signed in, which is what its stored secret
    /// is for. A key's passphrase is no password for the jump host (nor the
    /// other way round), so switching method does not keep the stored one.
    saved_ssh_auth: Option<SshAuth>,
    /// Seconds the server lets one statement run; blank for no limit.
    statement_timeout: Entity<InputState>,
    /// Whether the user has typed in the password box since the dialog opened.
    /// The stored password is never loaded into it, so an untouched box has to
    /// mean "leave it alone" rather than "no password".
    password_edited: bool,
    /// What the form has to say below the fields: a test under way or its
    /// outcome, or why the inputs cannot be used.
    status: Status,
    /// The connection test under way, dropped (and so cancelled) with the
    /// editor or by the next test.
    test: Option<Task<()>>,
}

/// The line between the form and its buttons.
#[derive(Clone, Debug, PartialEq, Eq)]
enum Status {
    None,
    Testing,
    Succeeded,
    Failed(String),
}

/// What each field shows while it is empty, for one engine: `(name, user,
/// database)`. The user and database are the ones a fresh server has; MySQL
/// needs no database at all, and SQLite's is a file.
fn placeholders(engine: Engine) -> (&'static str, &'static str, &'static str) {
    match engine {
        Engine::Postgres => ("Local PostgreSQL", "postgres", "postgres"),
        Engine::MySql => ("Local MySQL", "root", "Optional"),
        Engine::Sqlite if cfg!(windows) => ("Local SQLite", "", r"C:\path\to\database.db"),
        Engine::Sqlite => ("Local SQLite", "", "/path/to/database.db"),
    }
}

impl EventEmitter<EditorEvent> for ConnectionEditor {}

impl ConnectionEditor {
    /// Build the form for a new connection, or pre-filled from `config`.
    pub fn new(
        config: Option<ConnectionConfig>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        let engine = config
            .as_ref()
            .map(|c| c.engine)
            .unwrap_or(Engine::Postgres);
        let editing = config.is_some();

        let mut editor = Self {
            id: config.as_ref().map(|c| c.id),
            engine,
            safety: config.as_ref().map(|c| c.safety).unwrap_or_default(),
            color: config.as_ref().and_then(|c| c.color),
            name: cx.new(|cx| InputState::new(window, cx)),
            host: cx.new(|cx| InputState::new(window, cx).default_value("localhost")),
            port: cx.new(|cx| {
                InputState::new(window, cx).default_value(engine.default_port().to_string())
            }),
            username: cx.new(|cx| InputState::new(window, cx)),
            password: cx.new(|cx| {
                let input = InputState::new(window, cx).masked(true);
                // A saved connection's password is never read back into the
                // form, so the placeholder is what tells the user that leaving
                // it blank keeps what is already stored.
                if editing {
                    input.placeholder("Leave blank to keep the saved password")
                } else {
                    input
                }
            }),
            database: cx.new(|cx| InputState::new(window, cx)),
            ssl_mode: SslMode::default(),
            ssl_ca: cx.new(|cx| {
                InputState::new(window, cx).placeholder("Optional: the system's authorities")
            }),
            ssl_cert: cx.new(|cx| InputState::new(window, cx).placeholder("Optional")),
            ssl_key: cx.new(|cx| InputState::new(window, cx).placeholder("Optional")),
            ssh_enabled: false,
            ssh_auth: SshAuth::default(),
            ssh_host: cx.new(|cx| InputState::new(window, cx).placeholder("bastion.example.com")),
            ssh_port: cx.new(|cx| InputState::new(window, cx).default_value("22")),
            ssh_user: cx.new(|cx| InputState::new(window, cx)),
            ssh_key: cx.new(|cx| InputState::new(window, cx).placeholder("~/.ssh/id_ed25519")),
            ssh_secret: cx.new(|cx| {
                let input = InputState::new(window, cx).masked(true);
                if editing {
                    input.placeholder("Leave blank to keep the saved one")
                } else {
                    input
                }
            }),
            ssh_secret_edited: false,
            saved_ssh_auth: None,
            statement_timeout: cx.new(|cx| InputState::new(window, cx).placeholder("No limit")),
            password_edited: false,
            status: Status::None,
            test: None,
        };

        if let Some(config) = config {
            editor.load(&config, window, cx);
        }
        editor.set_placeholders(window, cx);

        // Subscribed after `load`, so filling the form in is not mistaken for
        // the user typing: only a change made from here on is a new password.
        let password = editor.password.clone();
        cx.subscribe_in(&password, window, Self::on_password_event)
            .detach();
        let ssh_secret = editor.ssh_secret.clone();
        cx.subscribe_in(&ssh_secret, window, Self::on_ssh_secret_event)
            .detach();
        for field in editor.fields() {
            cx.subscribe_in(&field, window, Self::on_field_event)
                .detach();
        }

        editor
    }

    fn fields(&self) -> [Entity<InputState>; 15] {
        [
            self.name.clone(),
            self.host.clone(),
            self.port.clone(),
            self.username.clone(),
            self.password.clone(),
            self.database.clone(),
            self.ssl_ca.clone(),
            self.ssl_cert.clone(),
            self.ssl_key.clone(),
            self.ssh_host.clone(),
            self.ssh_port.clone(),
            self.ssh_user.clone(),
            self.ssh_key.clone(),
            self.ssh_secret.clone(),
            self.statement_timeout.clone(),
        ]
    }

    /// Show the current engine's examples in the empty fields.
    fn set_placeholders(&self, window: &mut Window, cx: &mut Context<Self>) {
        let (name, username, database) = placeholders(self.engine);
        for (field, placeholder) in [
            (&self.name, name),
            (&self.username, username),
            (&self.database, database),
        ] {
            field.update(cx, |state, cx| {
                state.set_placeholder(placeholder, window, cx)
            });
        }
    }

    /// A result reported for other inputs no longer says anything about
    /// these, so an edit clears it.
    fn on_field_event(
        &mut self,
        _field: &Entity<InputState>,
        event: &InputEvent,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if matches!(event, InputEvent::Change) {
            self.clear_status(cx);
        }
    }

    /// Forget the last outcome, leaving a test still under way alone.
    fn clear_status(&mut self, cx: &mut Context<Self>) {
        if !matches!(self.status, Status::None | Status::Testing) {
            self.status = Status::None;
            cx.notify();
        }
    }

    /// Note that the user typed in the password box.
    ///
    /// This is what tells an untouched box (keep the stored password) apart
    /// from one the user emptied (forget it).
    fn on_password_event(
        &mut self,
        _password: &Entity<InputState>,
        event: &InputEvent,
        _window: &mut Window,
        _cx: &mut Context<Self>,
    ) {
        if matches!(event, InputEvent::Change) {
            self.password_edited = true;
        }
    }

    /// Note that the user typed in the SSH secret box, the way
    /// [`on_password_event`](Self::on_password_event) does for the password.
    fn on_ssh_secret_event(
        &mut self,
        _secret: &Entity<InputState>,
        event: &InputEvent,
        _window: &mut Window,
        _cx: &mut Context<Self>,
    ) {
        if matches!(event, InputEvent::Change) {
            self.ssh_secret_edited = true;
        }
    }

    fn set_field(
        &self,
        field: &Entity<InputState>,
        value: &str,
        window: &mut Window,
        cx: &mut App,
    ) {
        field.update(cx, |state, cx| {
            state.set_value(value.to_string(), window, cx)
        });
    }

    /// Fill the form in from a saved connection.
    fn load(&mut self, config: &ConnectionConfig, window: &mut Window, cx: &mut Context<Self>) {
        self.engine = config.engine;
        self.safety = config.safety;
        self.color = config.color;
        self.set_field(&self.name.clone(), &config.name, window, cx);
        self.set_field(&self.host.clone(), &config.host, window, cx);
        self.set_field(&self.port.clone(), &config.port.to_string(), window, cx);
        self.set_field(&self.username.clone(), &config.username, window, cx);
        self.set_field(&self.database.clone(), &config.database, window, cx);
        let timeout = config
            .statement_timeout
            .map(|seconds| seconds.to_string())
            .unwrap_or_default();
        self.set_field(&self.statement_timeout.clone(), &timeout, window, cx);
        self.set_field(&self.password.clone(), "", window, cx);
        self.ssl_mode = config.ssl.mode;
        self.set_field(&self.ssl_ca.clone(), &config.ssl.ca_cert, window, cx);
        self.set_field(&self.ssl_cert.clone(), &config.ssl.client_cert, window, cx);
        self.set_field(&self.ssl_key.clone(), &config.ssl.client_key, window, cx);
        self.ssh_enabled = config.ssh.enabled;
        self.ssh_auth = config.ssh.auth;
        self.saved_ssh_auth = Some(config.ssh.auth);
        self.set_field(&self.ssh_host.clone(), &config.ssh.host, window, cx);
        self.set_field(
            &self.ssh_port.clone(),
            &config.ssh.port.to_string(),
            window,
            cx,
        );
        self.set_field(&self.ssh_user.clone(), &config.ssh.username, window, cx);
        self.set_field(&self.ssh_key.clone(), &config.ssh.key_path, window, cx);
        self.set_field(&self.ssh_secret.clone(), "", window, cx);
    }

    /// Put the caret in the first field the user is about to fill in.
    pub fn focus(&self, window: &mut Window, cx: &mut Context<Self>) {
        self.name.update(cx, |input, cx| input.focus(window, cx));
    }

    /// Read the form into a config, reusing the saved connection's id.
    fn config(&self, cx: &App) -> ConnectionConfig {
        let port = self
            .port
            .read(cx)
            .value()
            .trim()
            .parse()
            .unwrap_or_else(|_| self.engine.default_port());

        ConnectionConfig {
            id: self.id.unwrap_or_else(Uuid::new_v4),
            name: self.name.read(cx).value().trim().to_string(),
            engine: self.engine,
            host: self.host.read(cx).value().trim().to_string(),
            port,
            username: self.username.read(cx).value().trim().to_string(),
            database: self.database.read(cx).value().trim().to_string(),
            safety: self.safety,
            color: self.color,
            last_connected: None,
            // Blank and `0` both mean no limit; SQLite has no server to
            // enforce one, so a value left from another engine is dropped.
            statement_timeout: if self.engine.is_file_based() {
                None
            } else {
                self.statement_timeout
                    .read(cx)
                    .value()
                    .trim()
                    .parse()
                    .ok()
                    .filter(|&seconds: &u32| seconds > 0)
            },
            ssl: self.ssl(cx),
            ssh: self.ssh(cx),
        }
    }

    /// Read the tunnel settings. They are kept when the tunnel is switched
    /// off, so switching it back on does not mean typing them again. A port
    /// that is not a number reads as 0, which `SshConfig::invalid` refuses.
    fn ssh(&self, cx: &App) -> SshConfig {
        let text = |input: &Entity<InputState>| input.read(cx).value().trim().to_string();
        let port = text(&self.ssh_port);
        SshConfig {
            enabled: self.ssh_enabled,
            host: text(&self.ssh_host),
            port: if port.is_empty() {
                22
            } else {
                port.parse().unwrap_or(0)
            },
            username: text(&self.ssh_user),
            auth: self.ssh_auth,
            key_path: text(&self.ssh_key),
        }
    }

    fn set_ssh_enabled(&mut self, enabled: bool, cx: &mut Context<Self>) {
        self.ssh_enabled = enabled;
        self.clear_status(cx);
        cx.notify();
    }

    fn set_ssh_auth(&mut self, auth: SshAuth, cx: &mut Context<Self>) {
        self.ssh_auth = auth;
        self.clear_status(cx);
        cx.notify();
    }

    /// Read the encryption settings. The paths are kept whatever the mode, so
    /// stepping down to `Prefer` and back does not lose them.
    fn ssl(&self, cx: &App) -> SslConfig {
        let path = |input: &Entity<InputState>| input.read(cx).value().trim().to_string();
        SslConfig {
            mode: self.ssl_mode,
            ca_cert: path(&self.ssl_ca),
            client_cert: path(&self.ssl_cert),
            client_key: path(&self.ssl_key),
        }
    }

    fn set_ssl_mode(&mut self, mode: SslMode, cx: &mut Context<Self>) {
        self.ssl_mode = mode;
        self.clear_status(cx);
        cx.notify();
    }

    fn set_engine(&mut self, engine: Engine, window: &mut Window, cx: &mut Context<Self>) {
        if self.engine == engine {
            return;
        }

        // Keep the port in step unless the user typed their own.
        let port = self.port.read(cx).value().trim().to_string();
        if port.is_empty() || port == self.engine.default_port().to_string() {
            self.set_field(
                &self.port.clone(),
                &engine.default_port().to_string(),
                window,
                cx,
            );
        }

        self.engine = engine;
        self.set_placeholders(window, cx);
        self.clear_status(cx);
        cx.notify();
    }

    /// Why the inputs cannot be used as they stand, in words for the user.
    ///
    /// An empty port is the engine's default rather than a mistake; one that
    /// is not a port number is, where it used to fall back to the default
    /// without a word.
    fn invalid(&self, cx: &App) -> Option<&'static str> {
        if self.engine.is_file_based() {
            return self
                .database
                .read(cx)
                .value()
                .trim()
                .is_empty()
                .then_some("Enter the path to the database file.");
        }

        if self.host.read(cx).value().trim().is_empty() {
            return Some("Enter the host to connect to.");
        }
        let port = self.port.read(cx).value().trim().to_string();
        if !port.is_empty() && !port.parse::<u16>().is_ok_and(|port| port > 0) {
            return Some("The port must be a number from 1 to 65535.");
        }
        let timeout = self.statement_timeout.read(cx).value().trim().to_string();
        if !timeout.is_empty() && timeout.parse::<u32>().is_err() {
            return Some("The statement timeout must be a whole number of seconds.");
        }
        self.ssl(cx).invalid().or_else(|| self.ssh(cx).invalid())
    }

    /// Report invalid inputs below the form; `true` when there were any.
    fn refuse_invalid(&mut self, cx: &mut Context<Self>) -> bool {
        let Some(message) = self.invalid(cx) else {
            return false;
        };
        self.test = None;
        self.status = Status::Failed(message.to_string());
        cx.notify();
        true
    }

    fn save(&mut self, cx: &mut Context<Self>) {
        if self.refuse_invalid(cx) {
            return;
        }
        let config = self.config(cx);
        let secrets = self.secrets(cx);
        cx.emit(EditorEvent::Saved { config, secrets });
    }

    /// Connect, saving the connection first unless `save` is off.
    fn connect(&mut self, save: bool, cx: &mut Context<Self>) {
        if self.refuse_invalid(cx) {
            return;
        }
        let config = self.config(cx);
        let secrets = self.secrets(cx);
        cx.emit(EditorEvent::Connect {
            config,
            secrets,
            save,
        });
    }

    /// Open a connection with the form as it stands and close it again,
    /// reporting how it went without leaving the dialog.
    ///
    /// The secrets are the ones a Connect would use: what a box holds once
    /// typed in, otherwise what the keychain holds for a saved connection.
    fn test_connection(&mut self, cx: &mut Context<Self>) {
        if self.refuse_invalid(cx) {
            return;
        }

        let config = self.config(cx);
        let secrets = self.secrets(cx);
        let saved = self.id.is_some();
        // The keychain can prompt, or simply be slow, so it is read off the
        // UI thread like the launcher's own lookup.
        let credentials = {
            let config = config.clone();
            cx.background_spawn(async move { store::credentials(&config, &secrets, saved) })
        };

        self.status = Status::Testing;
        cx.notify();

        self.test = Some(cx.spawn(async move |this, cx| {
            let outcome = match credentials.await {
                Ok(credentials) => {
                    let task = runtime::spawn(async move {
                        let connection = Connection::open_with(config, credentials).await?;
                        connection.close().await;
                        anyhow::Ok(())
                    })
                    // A test the editor drops (closed, or a new test started)
                    // stops trying, rather than waiting out a host that does
                    // not answer on the runtime.
                    .abort_on_drop();
                    match task.await {
                        Ok(Ok(())) => Status::Succeeded,
                        Ok(Err(error)) => Status::Failed(format!("{error:#}")),
                        Err(_) => Status::Failed("the test was cancelled".into()),
                    }
                }
                Err(error) => Status::Failed(format!("{error:#}")),
            };
            this.update(cx, |this, cx| {
                this.status = outcome;
                this.test = None;
                cx.notify();
            })
            .ok();
        }));
    }

    /// What the password box means for the keychain.
    ///
    /// `None` when the user never touched it, so an edit that was not about the
    /// password leaves the stored one in place; `Some("")` when they emptied
    /// it, which is how a saved password is forgotten.
    fn password(&self, cx: &App) -> Option<String> {
        self.password_edited
            .then(|| self.password.read(cx).value().to_string())
    }

    /// Both secret boxes, as [`password`](Self::password) reads one.
    fn secrets(&self, cx: &App) -> SecretEdits {
        SecretEdits {
            password: self.password(cx),
            ssh: (self.ssh_secret_edited
                || self
                    .saved_ssh_auth
                    .is_some_and(|saved| saved != self.ssh_auth))
            .then(|| self.ssh_secret.read(cx).value().to_string()),
        }
    }

    fn close(&mut self, cx: &mut Context<Self>) {
        cx.emit(EditorEvent::Dismissed);
    }

    fn on_close(&mut self, _: &EditorClose, _window: &mut Window, cx: &mut Context<Self>) {
        self.close(cx);
    }

    fn on_connect(&mut self, _: &EditorConnect, _window: &mut Window, cx: &mut Context<Self>) {
        self.connect(true, cx);
    }

    fn render_engines(&self, cx: &mut Context<Self>) -> impl IntoElement {
        h_flex().gap_2().children(Engine::ALL.map(|engine| {
            let button = Button::new(SharedString::from(format!("engine-{}", engine.label())))
                .label(engine.label())
                // The logo travels with the label so the engine is picked by
                // sight as well as by reading; the button's own variant colours
                // it, light on the selected one.
                .icon(crate::ui::engine_icon(engine))
                .on_click(
                    cx.listener(move |this, _, window, cx| this.set_engine(engine, window, cx)),
                );

            if self.engine == engine {
                button.primary()
            } else {
                button.outline()
            }
        }))
    }

    /// A row of colour swatches, plus "None"; the selected one is ringed and
    /// carries a check so the state is not told by colour alone.
    fn render_colors(&self, cx: &mut Context<Self>) -> impl IntoElement {
        v_flex()
            .gap_1()
            .child(
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child("Colour"),
            )
            .child(
                h_flex()
                    .gap_1()
                    .children(TagColor::ALL.map(|color| {
                        let selected = self.color == Some(color);
                        let swatch = color.hsla(cx);
                        Button::new(SharedString::from(format!("color-{}", color.key())))
                            .xsmall()
                            .rounded_full()
                            // A custom variant rather than a plain `bg`, so the
                            // hover and press states stay the swatch's colour
                            // instead of the default button's.
                            .custom(
                                ButtonCustomVariant::new(cx)
                                    .color(swatch)
                                    .foreground(color.on_color(cx))
                                    .hover(swatch.opacity(0.85))
                                    .active(swatch.opacity(0.7)),
                            )
                            .bg(swatch)
                            .selected(selected)
                            .accessibility_label(color.label())
                            .tooltip(color.label())
                            .on_click(cx.listener(move |this, _, _window, cx| {
                                this.color = Some(color);
                                cx.notify();
                            }))
                            .when(selected, |this| {
                                this.child(
                                    Icon::new(IconName::Check).text_color(color.on_color(cx)),
                                )
                            })
                    }))
                    .child(
                        Button::new("color-none")
                            .ghost()
                            .xsmall()
                            .label("None")
                            .selected(self.color.is_none())
                            .tooltip("No colour")
                            .on_click(cx.listener(|this, _, _window, cx| {
                                this.color = None;
                                cx.notify();
                            })),
                    ),
            )
    }

    /// Pick how careful this connection is about writes.
    fn render_safety(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let name = self.name.read(cx).value().trim().to_string();
        let hint = is_risky_auto_apply(&name, self.color, self.safety);

        v_flex()
            .gap_1()
            .child(
                div()
                    .text_xs()
                    .text_color(cx.theme().muted_foreground)
                    .child("Inline edits"),
            )
            .when(hint, |this| {
                this.child(
                    div()
                        .text_xs()
                        .text_color(cx.theme().warning)
                        .child("Writes apply immediately on a production connection."),
                )
            })
            .child(
                h_flex()
                    .gap_2()
                    .flex_wrap()
                    .children(SafetyMode::ALL.map(|safety| {
                        let button = Button::new(SharedString::from(format!("safety-{safety:?}")))
                            .label(safety.label())
                            .tooltip(safety.description())
                            .on_click(cx.listener(move |this, _, _window, cx| {
                                this.safety = safety;
                                cx.notify();
                            }));

                        if self.safety == safety {
                            button.primary()
                        } else {
                            button.outline()
                        }
                    })),
            )
    }

    /// Pick how the connection is encrypted, with the certificate files once
    /// the mode insists on encryption (`SslMode::uses_files`); below that they
    /// are neither shown nor sent.
    fn render_ssl(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let files = self.ssl_mode.uses_files();

        v_flex()
            .gap_3()
            .child(
                v_flex()
                    .gap_1()
                    .child(
                        div()
                            .text_xs()
                            .text_color(cx.theme().muted_foreground)
                            .child("SSL"),
                    )
                    .child(
                        h_flex()
                            .gap_2()
                            .flex_wrap()
                            .children(SslMode::ALL.map(|mode| {
                                let button =
                                    Button::new(SharedString::from(format!("ssl-{mode:?}")))
                                        .label(mode.label())
                                        .tooltip(mode.description())
                                        .on_click(cx.listener(move |this, _, _window, cx| {
                                            this.set_ssl_mode(mode, cx)
                                        }));

                                if self.ssl_mode == mode {
                                    button.primary()
                                } else {
                                    button.outline()
                                }
                            })),
                    ),
            )
            .when(files, |this| {
                this.child(field("CA certificate", &self.ssl_ca, cx)).child(
                    h_flex()
                        .gap_3()
                        .child(div().flex_1().child(field(
                            "Client certificate",
                            &self.ssl_cert,
                            cx,
                        )))
                        .child(div().flex_1().child(field("Client key", &self.ssl_key, cx))),
                )
            })
    }

    /// Whether to connect through an SSH tunnel and, when so, the jump host
    /// and how to sign in to it. The database's host and port above are then
    /// as the jump host sees them.
    fn render_ssh(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let enabled = self.ssh_enabled;
        // A certificate is checked against the host the driver dials, which
        // through a tunnel is the tunnel's own loopback end.
        let verify_full = enabled && self.ssl_mode == SslMode::VerifyFull;

        v_flex()
            .gap_3()
            .child(
                v_flex()
                    .gap_1()
                    .child(
                        div()
                            .text_xs()
                            .text_color(cx.theme().muted_foreground)
                            .child("SSH tunnel"),
                    )
                    .child(
                        h_flex()
                            .gap_2()
                            .children([(false, "Off"), (true, "On")].map(|(on, label)| {
                                let button =
                                    Button::new(SharedString::from(format!("ssh-{label}")))
                                        .label(label)
                                        .tooltip(if on {
                                            "Connect through an SSH jump host"
                                        } else {
                                            "Connect to the database directly"
                                        })
                                        .on_click(cx.listener(move |this, _, _window, cx| {
                                            this.set_ssh_enabled(on, cx)
                                        }));
                                if enabled == on {
                                    button.primary()
                                } else {
                                    button.outline()
                                }
                            })),
                    ),
            )
            .when(verify_full, |this| {
                this.child(div().text_xs().text_color(cx.theme().warning).child(
                    "Through a tunnel the certificate is checked against 127.0.0.1, \
                             so Verify full will fail; use Verify CA.",
                ))
            })
            .when(enabled, |this| {
                let secret = self.ssh_auth.secret_label();
                this.child(
                    h_flex()
                        .gap_3()
                        .child(div().flex_1().child(field("SSH host", &self.ssh_host, cx)))
                        .child(div().w_24().child(field("SSH port", &self.ssh_port, cx))),
                )
                .child(field("SSH user", &self.ssh_user, cx))
                .child(
                    h_flex()
                        .gap_2()
                        .flex_wrap()
                        .children(SshAuth::ALL.map(|auth| {
                            let button =
                                Button::new(SharedString::from(format!("ssh-auth-{auth:?}")))
                                    .label(auth.label())
                                    .on_click(cx.listener(move |this, _, _window, cx| {
                                        this.set_ssh_auth(auth, cx)
                                    }));
                            if self.ssh_auth == auth {
                                button.primary()
                            } else {
                                button.outline()
                            }
                        })),
                )
                .when(self.ssh_auth == SshAuth::PrivateKey, |this| {
                    this.child(field("Private key", &self.ssh_key, cx))
                })
                .when_some(secret, |this, label| {
                    this.child(field(label, &self.ssh_secret, cx))
                })
            })
    }

    fn render_form(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let file_based = self.engine.is_file_based();

        v_flex()
            .gap_3()
            .child(self.render_engines(cx))
            .child(field("Name", &self.name, cx))
            .when(file_based, |this| {
                this.child(field("Database file", &self.database, cx))
            })
            .when(!file_based, |this| {
                this.child(
                    h_flex()
                        .gap_3()
                        .child(div().flex_1().child(field("Host", &self.host, cx)))
                        .child(div().w_24().child(field("Port", &self.port, cx))),
                )
                .child(
                    h_flex()
                        .gap_3()
                        .child(div().flex_1().child(field("User", &self.username, cx)))
                        .child(div().flex_1().child(field("Password", &self.password, cx))),
                )
                .child(
                    h_flex()
                        .gap_3()
                        .child(div().flex_1().child(field("Database", &self.database, cx)))
                        .child(div().w_40().child(field(
                            "Statement timeout (s)",
                            &self.statement_timeout,
                            cx,
                        ))),
                )
                .child(self.render_ssl(cx))
                .child(self.render_ssh(cx))
            })
            .child(self.render_colors(cx))
            .child(self.render_safety(cx))
    }

    /// The test's progress or outcome, or why the inputs were refused. Told in
    /// words as well as colour.
    fn render_status(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
        let testing = self.status == Status::Testing;
        let theme = cx.theme();
        let (icon, color, text) = match &self.status {
            Status::None => return None,
            Status::Testing => (
                IconName::Loader,
                theme.muted_foreground,
                "Testing connection…".to_string(),
            ),
            Status::Succeeded => (
                IconName::CircleCheck,
                theme.success,
                "Connection succeeded.".to_string(),
            ),
            Status::Failed(message) => {
                (IconName::CircleX, theme.danger, format!("Error: {message}"))
            }
        };

        Some(
            h_flex()
                .id("editor-status")
                .flex_none()
                .items_start()
                .gap_2()
                .text_sm()
                .text_color(color)
                .child(if testing {
                    spinner(cx).into_any_element()
                } else {
                    Icon::new(icon).flex_none().mt_0p5().into_any_element()
                })
                .child(div().flex_1().min_w_0().child(text)),
        )
    }

    /// Connect, which saves first, with a menu for connecting without saving.
    fn render_connect(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let editor = cx.entity().downgrade();
        let unsaved = if self.id.is_some() {
            "Connect Without Saving Changes"
        } else {
            "Connect Without Saving"
        };

        DropdownButton::new("editor-connect-split")
            .primary()
            .button(
                Button::new("editor-connect")
                    .label("Connect")
                    .tooltip_with_action(
                        "Save and connect",
                        &EditorConnect,
                        Some("ConnectionEditor"),
                    )
                    .on_click(cx.listener(|this, _, _window, cx| this.connect(true, cx))),
            )
            .dropdown_menu(move |menu, _window, _cx| {
                let editor = editor.clone();
                menu.item(PopupMenuItem::new(unsaved).on_click(move |_, _window, cx| {
                    editor.update(cx, |this, cx| this.connect(false, cx)).ok();
                }))
            })
    }

    /// The password this form would write to the keychain, for a test to read.
    #[cfg(test)]
    pub(crate) fn password_intent_for_test(&self, cx: &App) -> Option<String> {
        self.password(cx)
    }

    /// Pick `engine` and fill the database field in, the way clicking and
    /// typing would.
    #[cfg(test)]
    pub(crate) fn fill_for_test(
        &mut self,
        engine: Engine,
        database: &str,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.set_engine(engine, window, cx);
        self.set_field(&self.database.clone(), database, window, cx);
    }

    /// Pick an SSL mode the way its button does.
    #[cfg(test)]
    pub(crate) fn set_ssl_mode_for_test(&mut self, mode: SslMode, cx: &mut Context<Self>) {
        self.set_ssl_mode(mode, cx);
    }

    /// Type into the CA, client certificate, and client key boxes.
    #[cfg(test)]
    pub(crate) fn set_ssl_files_for_test(
        &self,
        [ca, cert, key]: [&str; 3],
        window: &mut Window,
        cx: &mut App,
    ) {
        self.set_field(&self.ssl_ca, ca, window, cx);
        self.set_field(&self.ssl_cert, cert, window, cx);
        self.set_field(&self.ssl_key, key, window, cx);
    }

    /// Switch the tunnel on and fill its boxes in, the way clicking and typing
    /// would: `[host, port, user]`.
    #[cfg(test)]
    pub(crate) fn fill_ssh_for_test(
        &mut self,
        auth: SshAuth,
        [host, port, user]: [&str; 3],
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.set_ssh_enabled(true, cx);
        self.set_ssh_auth(auth, cx);
        self.set_field(&self.ssh_host.clone(), host, window, cx);
        self.set_field(&self.ssh_port.clone(), port, window, cx);
        self.set_field(&self.ssh_user.clone(), user, window, cx);
    }

    /// The secret boxes as the form would hand them to the keychain.
    #[cfg(test)]
    pub(crate) fn secrets_for_test(&self, cx: &App) -> SecretEdits {
        self.secrets(cx)
    }

    /// The config the form would save or connect with.
    #[cfg(test)]
    pub(crate) fn config_for_test(&self, cx: &App) -> ConnectionConfig {
        self.config(cx)
    }

    /// Type `value` over the port box's contents.
    #[cfg(test)]
    pub(crate) fn set_port_for_test(&self, value: &str, window: &mut Window, cx: &mut App) {
        self.set_field(&self.port, value, window, cx);
    }

    /// The line below the form, as the user reads it; empty when there is none.
    #[cfg(test)]
    pub(crate) fn status_for_test(&self) -> String {
        match &self.status {
            Status::None => String::new(),
            Status::Testing => "testing".into(),
            Status::Succeeded => "succeeded".into(),
            Status::Failed(message) => format!("Error: {message}"),
        }
    }

    /// What the name, user, and database boxes show while empty.
    #[cfg(test)]
    pub(crate) fn placeholders_for_test(&self, cx: &App) -> [String; 3] {
        [&self.name, &self.username, &self.database]
            .map(|field| field.read(cx).presentation().placeholder().to_string())
    }

    /// Run the Test Connection button's check.
    #[cfg(test)]
    pub(crate) fn test_connection_for_test(&mut self, cx: &mut Context<Self>) {
        self.test_connection(cx);
    }

    /// Connect the way the split button does: saving first, or from its menu
    /// without.
    #[cfg(test)]
    pub(crate) fn connect_for_test(&mut self, save: bool, cx: &mut Context<Self>) {
        self.connect(save, cx);
    }

    /// Put the caret in the name box, where the dialog opens with it.
    #[cfg(test)]
    pub(crate) fn focus_name_for_test(&self, window: &mut Window, cx: &mut Context<Self>) {
        self.focus(window, cx);
    }

    /// Put the caret in the password box, the way a click would.
    #[cfg(test)]
    pub(crate) fn focus_password_for_test(&self, window: &mut Window, cx: &mut Context<Self>) {
        self.password
            .update(cx, |input, cx| input.focus(window, cx));
    }
}

impl Render for ConnectionEditor {
    fn render(&mut self, _window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        v_flex()
            .id("connection-editor")
            .size_full()
            .gap_3()
            .key_context("ConnectionEditor")
            .on_action(cx.listener(Self::on_close))
            .on_action(cx.listener(Self::on_connect))
            .child(
                // The inputs' focus ring is drawn outside their border, which
                // this scroll area would clip at its edges; the padding gives
                // the ring room, and the negative margin keeps the fields
                // lined up with the title and the buttons. The margin sits on
                // a wrapper because a scrollable keeps its own margin on the
                // content, inside the edge that clips.
                div()
                    .id("editor-form")
                    .test_support()
                    .flex_1()
                    .min_h_0()
                    .mx(px(-4.))
                    .child(
                        div()
                            .size_full()
                            .overflow_y_scrollbar()
                            .child(div().p(px(4.)).child(self.render_form(cx))),
                    ),
            )
            .children(self.render_status(cx))
            .child(
                h_flex()
                    .flex_none()
                    .gap_2()
                    .child(
                        Button::new("editor-test")
                            .outline()
                            .label("Test Connection")
                            .loading(self.status == Status::Testing)
                            .tooltip("Check that these settings connect, without closing")
                            .on_click(cx.listener(|this, _, _window, cx| this.test_connection(cx))),
                    )
                    .child(div().flex_1())
                    .child(
                        Button::new("editor-cancel")
                            .ghost()
                            .label("Cancel")
                            .on_click(cx.listener(|this, _, _window, cx| this.close(cx))),
                    )
                    .child(
                        Button::new("editor-save")
                            .outline()
                            .label("Save")
                            .tooltip("Save this connection without connecting")
                            .on_click(cx.listener(|this, _, _window, cx| this.save(cx))),
                    )
                    .child(self.render_connect(cx)),
            )
    }
}

/// A label and its input, the form's repeated row.
fn field(label: &str, input: &Entity<InputState>, cx: &App) -> impl IntoElement {
    v_flex()
        .gap_1()
        .child(
            div()
                .text_xs()
                .text_color(cx.theme().muted_foreground)
                .child(label.to_string()),
        )
        .child(
            div()
                .id(SharedString::from(format!("field-{label}")))
                .test_support()
                .child(Input::new(input)),
        )
}