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
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
//! Root view: every open connection in a tab of its own.
//!
//! A tab holds either the connection manager or an open session. Connecting
//! turns the tab it was opened from into that session and disconnecting turns
//! it back, so a connection is always somewhere on the bar rather than
//! replacing what the window was showing. The window keeps at least one tab,
//! the way the session keeps at least one editor. The bar only takes a row of
//! the window once there is more than one tab to choose between; a lone
//! connection is closed from its shortcut or the File menu.

use std::collections::HashMap;
use std::rc::Rc;
use std::sync::Arc;

use gpui_kit::base::TestSupportExt;
use gpui_kit::component::button::{Button, ButtonVariant, ButtonVariants};
use gpui_kit::component::dialog::DialogButtonProps;
use gpui_kit::component::tab::{Tab, TabBar, TabVariant};
use gpui_kit::component::{
    ActiveTheme, Disableable, Icon, IconName, Sizable, Size, TitleBar, WindowExt, h_flex, v_flex,
};
use gpui_kit::prelude::*;
use gpui_kit::{
    AnyElement, App, ClipboardItem, Context, Entity, EntityId, FocusHandle, Hsla, MouseButton,
    Pixels, SharedString, Window, actions, div, px,
};

use crate::crash_log;
use crate::menu::Quit;

use crate::db::{Connection, TagColor, runtime, store};
use crate::settings;
use crate::ui::session::{NewTab, QuickSwitcher, Refresh, SearchSchema, Session, SessionEvent};
use crate::ui::settings_window::{self, OpenSettings};
use crate::ui::shortcuts_dialog::{self, ShowShortcuts};
use crate::ui::value_dialog::{self, Dismissed, ValueView};
use crate::ui::welcome::{SavedConnections, Welcome, WelcomeEvent};
use crate::workspace_state::{self, SessionState, WorkspaceState};

/// The value dialog is a reading pane rather than a prompt, so it is wider
/// and taller than a dialog's default.
const VALUE_DIALOG_WIDTH: Pixels = px(640.);
const VALUE_DIALOG_HEIGHT: Pixels = px(416.);

actions!(
    zippa_db,
    [
        NewConnection,
        CloseConnection,
        NextConnection,
        PreviousConnection
    ]
);

/// What a tab holds: the connection manager, or a connection that is open.
enum TabContent {
    Connect(Entity<Welcome>),
    Session(Entity<Session>),
}

impl TabContent {
    fn title(&self, cx: &App) -> SharedString {
        match self {
            Self::Connect(_) => "New connection".into(),
            Self::Session(session) => session.read(cx).connection().config.display_name().into(),
        }
    }

    /// The mark a tab leads with: the engine's own logo for a connection, so
    /// the target is told at a glance.
    ///
    /// The manager is not a connection and is not on a database, so it is not
    /// an engine that decides its icon — but it takes the slot all the same, so
    /// every tab's name starts at one spine.
    fn icon(&self, cx: &App) -> Icon {
        match self {
            Self::Connect(_) => Icon::new(IconName::Plus),
            Self::Session(session) => {
                crate::ui::engine_icon(session.read(cx).connection().config.engine)
            }
        }
    }

    /// The engine's own accent, so tabs for different engines are told apart
    /// without reading the target string.
    fn icon_color(&self, cx: &App) -> Option<Hsla> {
        match self {
            Self::Connect(_) => None,
            Self::Session(session) => Some(crate::ui::engine_color(
                session.read(cx).connection().config.engine,
                cx,
            )),
        }
    }

    /// The connection's colour, if it has one.
    fn color(&self, cx: &App) -> Option<TagColor> {
        match self {
            Self::Connect(_) => None,
            Self::Session(session) => session.read(cx).connection().config.color,
        }
    }

    /// The database the session is on, named the way a tab wants it.
    ///
    /// A file-based engine is one database, and that database is the file, so
    /// the tab shows the file's name rather than its whole path — the same
    /// short form the database picker uses.
    fn database(&self, cx: &App) -> Option<String> {
        let Self::Session(session) = self else {
            return None;
        };
        let connection = session.read(cx).connection();
        Some(match connection.config.engine.is_file_based() {
            true => crate::db::file_name(connection.database()),
            false => connection.database().to_string(),
        })
    }

    /// The database line a tab should draw, kept only when it says something the
    /// name does not.
    ///
    /// An unnamed SQLite connection takes the file's name as its own, so the
    /// tab would otherwise read the same name twice.
    fn database_line(&self, cx: &App) -> Option<String> {
        let database = self.database(cx)?;
        (database.as_str() != self.title(cx).as_str()).then_some(database)
    }

    /// Name, colour and database in one line, for a screen reader. The label below
    /// is drawn as an icon beside two stacked lines, so it carries no text of
    /// its own for a name to come from.
    fn aria_label(&self, cx: &App) -> SharedString {
        let mut label = self.title(cx).to_string();
        if let Some(color) = self.color(cx) {
            label.push_str(" · ");
            label.push_str(color.label());
        }
        if let Some(database) = self.database_line(cx) {
            label.push_str(" · ");
            label.push_str(&database);
        }
        label.into()
    }

    /// The tab's contents: the engine icon beside the name, with the database
    /// it is on beneath it for a connection.
    ///
    /// The name keeps the tab's own colour and the database sits muted and a
    /// step smaller underneath, so a bar of connections is scanned by name and
    /// the database is read when it matters. The manager is neither a
    /// connection nor on a database, so it is its icon and its name alone.
    fn content(&self, cx: &App) -> AnyElement {
        let icon = {
            let icon = self.icon(cx);
            match self.icon_color(cx) {
                Some(color) => icon.text_color(color),
                None => icon,
            }
        };

        let label = match self {
            Self::Connect(_) => v_flex().min_w_0().child(self.title(cx)),
            Self::Session(_) => {
                let title = div().min_w_0().truncate().child(self.title(cx)).text_sm();

                // The same dot the title bar draws beside the name, so the
                // colour reads without relying on the faint tab tint alone.
                let name = h_flex()
                    .gap_1p5()
                    .min_w_0()
                    .child(title)
                    .when_some(self.color(cx), |this, color| {
                        this.child(crate::ui::color_dot(color, cx))
                    });

                // The database is secondary to the name, so it sits muted and
                // a step smaller underneath it.
                let database = self.database_line(cx).map(|database| {
                    div()
                        .min_w_0()
                        .truncate()
                        .text_xs()
                        .text_color(cx.theme().muted_foreground)
                        .child(database)
                });

                v_flex().min_w_0().child(name).children(database)
            }
        };

        h_flex()
            .gap_2()
            .min_w_0()
            .child(icon)
            .child(label)
            .into_any_element()
    }
}

pub struct Workspace {
    tabs: Vec<TabContent>,
    active: usize,
    /// The value dialog, while one is open over the window.
    value: Option<Entity<ValueView>>,
    /// Held by the window itself, so the connection shortcuts answer even when
    /// nothing inside a tab has the caret.
    focus: FocusHandle,
    /// Tabs a startup restore is reconnecting, keyed by the connection manager
    /// that is connecting them. Their contents are kept here until the session
    /// exists, so a failed reconnect does not erase the user's tabs.
    pending: HashMap<EntityId, SessionState>,
    /// The snapshot last written, so an unchanged one is not written again.
    last_saved: Option<WorkspaceState>,
}

impl Workspace {
    pub fn new(window: &mut Window, cx: &mut Context<Self>) -> Self {
        // A workspace file that cannot be read must not keep the app from
        // starting; an empty one is simply the first launch.
        let state = workspace_state::load().unwrap_or_else(|error| {
            eprintln!("could not read the workspace: {error:#}");
            WorkspaceState::default()
        });
        Self::build(state, window, cx)
    }

    /// Build a workspace, restoring `state`'s tabs into it.
    fn build(state: WorkspaceState, window: &mut Window, cx: &mut Context<Self>) -> Self {
        // The window knows the system appearance more reliably than the app
        // does on Linux, and it is the only thing that hears about a change.
        settings::follow_system_appearance(window, cx);
        window
            .observe_window_appearance(settings::follow_system_appearance)
            .detach();

        let focus = cx.focus_handle();
        focus.focus(window, cx);

        let mut workspace = Self {
            tabs: Vec::new(),
            active: 0,
            value: None,
            focus,
            pending: HashMap::new(),
            last_saved: None,
        };
        workspace.restore_tabs(state, window, cx);
        workspace
    }

    /// If the last run crashed, say so once. Either answer clears the
    /// report, so it is not shown again; "Copy report" puts the whole
    /// thing, backtrace included, on the clipboard for a bug report.
    ///
    /// This needs the window's root layer, so it runs after the window is
    /// open, not during the build.
    pub(crate) fn report_crash(window: &mut Window, cx: &mut App) {
        let Some(report) = crash_log::pending() else {
            return;
        };
        let summary = crash_log::summary(&report);
        let report = Rc::new(report);
        window.open_alert_dialog(cx, move |alert, _, _| {
            let report = Rc::clone(&report);
            alert
                .title("Zippa DB crashed")
                .description(format!(
                    "The last session ended in a crash:\n\n{summary}\n\nCopy the full report to send it with a bug report."
                ))
                .button_props(
                    DialogButtonProps::default()
                        .ok_text("Copy report")
                        .cancel_text("Dismiss")
                        .show_cancel(true),
                )
                .on_ok(move |_, _, cx| {
                    cx.write_to_clipboard(ClipboardItem::new_string(report.to_string()));
                    crash_log::clear();
                    true
                })
                .on_cancel(move |_, _, _| {
                    crash_log::clear();
                    true
                })
        });
    }

    /// Reopen every connection the last session had, then let each turn its
    /// tab into a session and restore its own tabs.
    ///
    /// Nothing is restored synchronously: a connection has to be opened first,
    /// and that follows the same path a manual connect does.
    fn restore_tabs(&mut self, state: WorkspaceState, window: &mut Window, cx: &mut Context<Self>) {
        let connections = if state.sessions.is_empty() {
            Vec::new()
        } else {
            // The launchers' own list, so a file that cannot be read is
            // reported once, by the first of them.
            SavedConnections::get(cx).to_vec()
        };

        let mut active = 0;
        for (index, session) in state.sessions.into_iter().enumerate() {
            // A connection deleted since the file was written is skipped.
            if !connections
                .iter()
                .any(|config| config.id == session.connection)
            {
                continue;
            }

            let welcome = Self::welcome(window, cx);
            self.pending.insert(welcome.entity_id(), session.clone());
            welcome.update(cx, |welcome, cx| {
                welcome.open(session.connection, window, cx)
            });
            if index == state.active {
                active = self.tabs.len();
            }
            self.tabs.push(TabContent::Connect(welcome));
        }

        if self.tabs.is_empty() {
            // Nothing to restore: the window opens on the connection manager.
            self.open_connect_tab(window, cx);
            return;
        }

        self.active = active.min(self.tabs.len() - 1);
        self.focus_active(window, cx);
        cx.notify();
    }

    /// Add a tab showing the connection manager and make it active.
    fn open_connect_tab(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let welcome = Self::welcome(window, cx);
        self.tabs.push(TabContent::Connect(welcome));
        self.active = self.tabs.len() - 1;
        self.focus_active(window, cx);
        self.save_state(cx);
        cx.notify();
    }

    fn welcome(window: &mut Window, cx: &mut Context<Self>) -> Entity<Welcome> {
        let welcome = cx.new(|cx| Welcome::new(window, cx));
        cx.subscribe_in(&welcome, window, Self::on_welcome_event)
            .detach();
        welcome
    }

    fn activate_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if index >= self.tabs.len() || index == self.active {
            return;
        }

        self.active = index;
        self.focus_active(window, cx);
        self.save_state(cx);
        cx.notify();
    }

    /// Put the caret in the session being shown, so its shortcuts work without
    /// clicking into it first.
    fn focus_active(&self, window: &mut Window, cx: &mut Context<Self>) {
        match self.tabs.get(self.active) {
            Some(TabContent::Session(session)) => {
                let session = session.clone();
                session.update(cx, |session, cx| session.focus(window, cx));
            }
            // The launcher puts the caret in its search box when there is
            // something to search; focus left behind in a hidden tab would
            // keep answering keystrokes.
            Some(TabContent::Connect(welcome)) => {
                let welcome = welcome.clone();
                welcome.update(cx, |welcome, cx| welcome.focus(window, cx));
            }
            _ => self.focus.focus(window, cx),
        }
    }

    /// Close a tab, asking first if it holds a connection with unsaved
    /// changes in one of its own tabs.
    fn close_tab(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if index >= self.tabs.len() {
            return;
        }

        if let TabContent::Session(session) = &self.tabs[index]
            && let Some(warning) = session.read(cx).leave_warning(cx)
        {
            self.confirm_close_tab(session.clone(), warning, window, cx);
            return;
        }

        self.close_tab_now(index, window, cx);
    }

    /// Ask before throwing away a connection's unsaved tabs; closes it on
    /// confirmation, by whatever index it still holds by then.
    fn confirm_close_tab(
        &mut self,
        session: Entity<Session>,
        (title, warning): (&'static str, String),
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let workspace = cx.entity().downgrade();

        window.open_alert_dialog(cx, move |alert, _, _| {
            let workspace = workspace.clone();
            let session = session.clone();
            alert
                .title(title)
                .description(format!("{warning} Close it anyway?"))
                .button_props(
                    DialogButtonProps::default()
                        .ok_text("Close Anyway")
                        .ok_variant(ButtonVariant::Danger)
                        .cancel_text("Keep Open")
                        .show_cancel(true),
                )
                .on_ok(move |_, window, cx| {
                    if let Some(workspace) = workspace.upgrade() {
                        workspace.update(cx, |this, cx| {
                            if let Some(index) = this.tab_of(
                                |tab| matches!(tab, TabContent::Session(open) if open == &session),
                            ) {
                                this.close_tab_now(index, window, cx);
                            }
                        });
                    }
                    true
                })
        });
    }

    /// Replace a session's tab with a fresh connection manager, the way the
    /// Disconnect action does. The caller has already decided any
    /// unsaved work in the session's tabs does not matter.
    fn disconnect(
        &mut self,
        session: Entity<Session>,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let Some(index) =
            self.tab_of(|tab| matches!(tab, TabContent::Session(open) if open == &session))
        else {
            return;
        };

        session.update(cx, |session, cx| session.stop_runs(cx));
        close(session.read(cx).connection());
        // Disconnecting keeps the tab, so another connection can be opened
        // from where the last one was.
        self.tabs[index] = TabContent::Connect(Self::welcome(window, cx));
        self.focus_active(window, cx);
        self.save_state(cx);
        cx.notify();
    }

    /// Ask before disconnecting a connection whose own tabs hold unsaved
    /// changes; disconnects it on confirmation.
    fn confirm_disconnect(
        &mut self,
        session: Entity<Session>,
        (title, warning): (&'static str, String),
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let workspace = cx.entity().downgrade();

        window.open_alert_dialog(cx, move |alert, _, _| {
            let workspace = workspace.clone();
            let session = session.clone();
            alert
                .title(title)
                .description(format!("{warning} Disconnect anyway?"))
                .button_props(
                    DialogButtonProps::default()
                        .ok_text("Disconnect Anyway")
                        .ok_variant(ButtonVariant::Danger)
                        .cancel_text("Keep Connected")
                        .show_cancel(true),
                )
                .on_ok(move |_, window, cx| {
                    if let Some(workspace) = workspace.upgrade() {
                        workspace.update(cx, |this, cx| {
                            this.disconnect(session.clone(), window, cx);
                        });
                    }
                    true
                })
        });
    }

    /// Remove a tab outright; the caller has already decided any unsaved
    /// changes in it do not matter.
    fn close_tab_now(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {
        if index >= self.tabs.len() {
            return;
        }

        if let TabContent::Session(session) = &self.tabs[index] {
            session.update(cx, |session, cx| session.stop_runs(cx));
            close(session.read(cx).connection());
        }
        // A connection manager on its way out has nothing left to restore into.
        if let TabContent::Connect(welcome) = &self.tabs[index] {
            let welcome = welcome.entity_id();
            self.pending.remove(&welcome);
        }
        self.tabs.remove(index);

        if self.tabs.is_empty() {
            // The window always shows something.
            self.open_connect_tab(window, cx);
            return;
        }

        // Closing a tab to the left of the active one shifts it along; the
        // tab the user was looking at stays in front either way.
        if index < self.active {
            self.active -= 1;
        }
        self.active = self.active.min(self.tabs.len() - 1);
        self.focus_active(window, cx);
        self.save_state(cx);
        cx.notify();
    }

    fn on_welcome_event(
        &mut self,
        welcome: &Entity<Welcome>,
        event: &WelcomeEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        let WelcomeEvent::Connected(connection) = event;
        let session = cx.new(|cx| Session::new(connection.clone(), window, cx));
        cx.subscribe_in(&session, window, Self::on_session_event)
            .detach();

        // A startup restore parked this tab's contents here; a manual connect
        // has nothing pending. The connection id is checked because a user who
        // reconnects somewhere else from a failed restore's launcher should not
        // get the old connection's tabs. The entry stays in `pending` until the
        // tab has been swapped, so a checkpoint taken while the tabs are being
        // rebuilt still records them.
        let pending = self.pending.get(&welcome.entity_id()).cloned();
        let mut orphaned = None;
        match pending {
            Some(state) if state.connection == connection.config.id => {
                session.update(cx, |session, cx| session.restore(state, window, cx));
            }
            // The launcher connected somewhere else: the tabs it was holding
            // for the connection that failed move to a launcher of their own,
            // so they are still saved and the user can try that one again.
            Some(state) => orphaned = Some(state),
            None => {}
        }

        // The tab the connection was opened from becomes the connection. Its
        // tab being gone would mean it was closed mid-connect, and the pool is
        // open either way, so it gets a tab of its own instead.
        match self.tab_of(|tab| matches!(tab, TabContent::Connect(open) if open == welcome)) {
            Some(index) => {
                self.tabs[index] = TabContent::Session(session);
                // The tab is already in front: a manual connect is started from
                // the tab showing it, and a restore has already put the saved
                // tab in front. Stepping to whichever connection finished last
                // would lose that, so `active` is left alone.
            }
            None => {
                self.tabs.push(TabContent::Session(session));
                self.active = self.tabs.len() - 1;
            }
        }
        self.pending.remove(&welcome.entity_id());
        if let Some(state) = orphaned {
            let parked = Self::welcome(window, cx);
            self.pending.insert(parked.entity_id(), state);
            self.tabs.push(TabContent::Connect(parked));
        }

        self.focus_active(window, cx);
        self.save_state(cx);
        cx.notify();
    }

    fn on_session_event(
        &mut self,
        session: &Entity<Session>,
        event: &SessionEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        match event {
            // Something about the session's tabs changed; the saved state is
            // rewritten at these checkpoints rather than on every keystroke.
            // A tab also draws the connection's name and the database it is on,
            // and a connection changing database is only heard about here, so
            // the bar is redrawn with it.
            SessionEvent::Changed => {
                self.save_state(cx);
                cx.notify();
            }
            SessionEvent::Disconnected => {
                // Disconnecting drops the session and every tab in it, so ask
                // first when any of them holds work that was never written —
                // the same guard closing the tab uses.
                if let Some(warning) = session.read(cx).leave_warning(cx) {
                    self.confirm_disconnect(session.clone(), warning, window, cx);
                    return;
                }
                self.disconnect(session.clone(), window, cx);
            }
        }
    }

    /// The window's tabs as they would be restored.
    ///
    /// Only session tabs are recorded: a blank connection manager is scratch
    /// form state, so it is neither saved nor restored. A manager still holding
    /// a pending restore is recorded from that state, so a failed reconnect
    /// does not erase the user's tabs from the file.
    pub(crate) fn snapshot(&self, cx: &App) -> WorkspaceState {
        let mut sessions = Vec::new();
        let mut active = 0;

        for (index, tab) in self.tabs.iter().enumerate() {
            let state = match tab {
                TabContent::Session(session) => Some(session.read(cx).snapshot(cx)),
                TabContent::Connect(welcome) => self.pending.get(&welcome.entity_id()).cloned(),
            };

            if let Some(state) = state {
                if index == self.active {
                    active = sessions.len();
                }
                sessions.push(state);
            }
        }

        WorkspaceState {
            active,
            sessions,
            ..WorkspaceState::default()
        }
    }

    /// Write the current state, unless it is what was written last.
    ///
    /// The file is small but the UI thread should not wait on it, so the write
    /// goes to the background.
    fn save_state(&mut self, cx: &mut Context<Self>) {
        let state = self.snapshot(cx);
        if self.last_saved.as_ref() == Some(&state) {
            return;
        }
        self.last_saved = Some(state.clone());

        let ticket = store::ticket();
        let written = state.clone();
        let write = cx.background_spawn(async move { workspace_state::save(&written, ticket) });
        cx.spawn(async move |this, cx| {
            if let Err(error) = write.await {
                eprintln!("could not save the workspace: {error:#}");
                // Forget it was saved, so the next checkpoint tries again
                // rather than skipping a snapshot that never reached the disk.
                this.update(cx, |this, _| {
                    if this.last_saved.as_ref() == Some(&state) {
                        this.last_saved = None;
                    }
                })
                .ok();
            }
        })
        .detach();
    }

    /// Write the current state now, for the process that is about to end.
    ///
    /// Synchronous on purpose: this is the last chance to record text typed
    /// since the last checkpoint, and a background write would race the
    /// shutdown that is already under way.
    pub(crate) fn flush_state(&mut self, cx: &mut Context<Self>) {
        let state = self.snapshot(cx);
        if self.last_saved.as_ref() == Some(&state) {
            return;
        }
        self.last_saved = Some(state.clone());

        if let Err(error) = workspace_state::save(&state, store::ticket()) {
            eprintln!("could not save the workspace: {error:#}");
        }
    }

    /// Show the value a grid asked for, if one is waiting.
    ///
    /// A cell has no window to build a text box with, so it leaves the value
    /// in a global and the dialog is opened here, where there is one. The
    /// surface is `gpui_kit`'s `Dialog`, so the focus trap and the overlay
    /// that keeps mouse events off the grid behind come with it; the view
    /// this workspace holds is only the body inside it.
    fn take_value_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
        let Some(request) = value_dialog::take(cx) else {
            return;
        };

        // One value dialog at a time: a second request while one is open must
        // not stack another, or the first view's dismiss would pop the wrong
        // dialog and `value` would point at a closed one. The grid sits behind
        // the modal overlay, so this cannot happen through the UI.
        if self.value.is_some() {
            return;
        }

        let view = cx.new(|cx| ValueView::new(request, window, cx));
        // Saving or dismissing from inside the body closes the dialog from
        // this side; the routes the dialog answers itself (its close button,
        // a press on the overlay) come back through `on_close` below.
        cx.subscribe_in(&view, window, |this, _, _: &Dismissed, window, cx| {
            this.value = None;
            window.close_dialog(cx);
            this.focus_active(window, cx);
            cx.notify();
        })
        .detach();

        let workspace = cx.entity().downgrade();
        let body = view.clone();
        window.open_dialog(cx, move |dialog, _window, _cx| {
            let workspace = workspace.clone();
            dialog
                // The body carries its own heading and its own buttons, so
                // the dialog contributes the surface alone.
                .w(VALUE_DIALOG_WIDTH)
                .h(VALUE_DIALOG_HEIGHT)
                .close_button(false)
                // `enter` is the text box's own key and the box is
                // multi-line, so the dialog's keys are left to `ValueDialog`.
                .keyboard(false)
                .on_close(move |_, _window, cx| {
                    workspace
                        .update(cx, |this, cx| {
                            this.value = None;
                            cx.notify();
                        })
                        .ok();
                })
                .child(body.clone())
        });

        view.update(cx, |view, cx| view.focus(window, cx));
        self.value = Some(view);
    }

    fn tab_of(&self, held_by: impl Fn(&TabContent) -> bool) -> Option<usize> {
        self.tabs.iter().position(held_by)
    }

    fn on_new_connection(
        &mut self,
        _: &NewConnection,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.open_connect_tab(window, cx);
    }

    fn on_show_shortcuts(
        &mut self,
        _: &ShowShortcuts,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        shortcuts_dialog::open(window, cx);
    }

    fn on_close_connection(
        &mut self,
        _: &CloseConnection,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.close_tab(self.active, window, cx);
    }

    /// Quit, asking first when a tab has a transaction open: the server
    /// rolls it back when the process goes, which every other way of leaving
    /// a connection asks about. Unsaved query text needs no question, since
    /// it is kept for the next launch.
    fn on_quit(&mut self, _: &Quit, window: &mut Window, cx: &mut Context<Self>) {
        let open: usize = self
            .tabs
            .iter()
            .filter_map(|tab| match tab {
                TabContent::Session(session) => Some(session.read(cx).open_transactions(cx)),
                TabContent::Connect(_) => None,
            })
            .sum();
        if open == 0 {
            cx.quit();
            return;
        }
        if window.has_active_dialog(cx) {
            return;
        }

        let description = match open {
            1 => "A tab has an open transaction, which will be rolled back.".to_string(),
            count => format!("{count} tabs have open transactions, which will be rolled back."),
        };
        window.open_alert_dialog(cx, move |alert, _, _| {
            alert
                .title("Open Transaction")
                .description(format!("{description} Quit anyway?"))
                .button_props(
                    DialogButtonProps::default()
                        .ok_text("Quit Anyway")
                        .ok_variant(ButtonVariant::Danger)
                        .cancel_text("Cancel")
                        .show_cancel(true),
                )
                .on_ok(|_, _, cx| {
                    cx.quit();
                    true
                })
        });
    }

    fn on_next_connection(
        &mut self,
        _: &NextConnection,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.step(1, window, cx);
    }

    fn on_previous_connection(
        &mut self,
        _: &PreviousConnection,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        self.step(-1, window, cx);
    }

    /// Move `delta` tabs along the bar, wrapping at either end.
    fn step(&mut self, delta: isize, window: &mut Window, cx: &mut Context<Self>) {
        let count = self.tabs.len() as isize;
        if count < 2 {
            return;
        }

        let next = (self.active as isize + delta).rem_euclid(count);
        self.activate_tab(next as usize, window, cx);
    }

    fn render_tab_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let workspace = cx.entity().downgrade();

        TabBar::new("connection-tabs")
            .with_variant(TabVariant::Underline)
            // Each tab stacks the name over the database, so the bar takes the
            // one size whose frame has room for both lines.
            .with_size(Size::Large)
            .selected_index(self.active)
            .on_click(
                cx.listener(|this, index: &usize, window, cx| {
                    this.activate_tab(*index, window, cx)
                }),
            )
            .children(self.tabs.iter().enumerate().map(|(index, tab)| {
                let close_button = workspace.clone();
                let middle_click = workspace.clone();

                Tab::new()
                    .aria_label(tab.aria_label(cx))
                    .px_2()
                    // The connection's colour, faint enough that the text on
                    // it keeps its contrast.
                    .when_some(tab.color(cx), |this, color| this.bg(color.tint(cx)))
                    // The engine icon and both lines are drawn by `content`, so
                    // the tab carries no label of its own.
                    .child(tab.content(cx))
                    // Middle-click closes, the way it does in a browser.
                    .on_mouse_down(MouseButton::Middle, move |_, window, cx| {
                        if let Some(workspace) = middle_click.upgrade() {
                            workspace.update(cx, |this, cx| this.close_tab(index, window, cx));
                        }
                    })
                    .suffix(
                        Button::new(SharedString::from(format!("close-connection-{index}")))
                            .ghost()
                            .xsmall()
                            .icon(IconName::Close)
                            .accessibility_label(format!("Close {}", tab.title(cx)))
                            .tooltip_with_action(
                                "Close connection",
                                &CloseConnection,
                                Some("Workspace"),
                            )
                            .on_click(move |_, window, cx| {
                                if let Some(workspace) = close_button.upgrade() {
                                    workspace
                                        .update(cx, |this, cx| this.close_tab(index, window, cx));
                                }
                            }),
                    )
            }))
    }

    /// The session showing in the active tab, if any.
    fn active_session(&self) -> Option<Entity<Session>> {
        match self.tabs.get(self.active)? {
            TabContent::Session(session) => Some(session.clone()),
            TabContent::Connect(_) => None,
        }
    }

    fn on_quick_switcher_click(
        &mut self,
        _: &gpui_kit::ClickEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(session) = self.active_session() {
            crate::ui::quick_switcher::open(session, window, cx);
        }
    }

    fn on_quick_switcher(
        &mut self,
        _: &QuickSwitcher,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(session) = self.active_session() {
            crate::ui::quick_switcher::open(session, window, cx);
        }
    }

    fn on_search_schema(&mut self, _: &SearchSchema, window: &mut Window, cx: &mut Context<Self>) {
        if let Some(session) = self.active_session() {
            let _ = crate::ui::schema_search::open(session, window, cx);
        }
    }

    fn on_refresh_click(
        &mut self,
        _: &gpui_kit::ClickEvent,
        _window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(session) = self.active_session() {
            session.update(cx, |session, cx| session.refresh(cx));
        }
    }

    fn on_new_query_click(
        &mut self,
        _: &gpui_kit::ClickEvent,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) {
        if let Some(session) = self.active_session() {
            session.update(cx, |session, cx| session.new_query_tab(window, cx));
        }
    }

    /// The window's own bar: who we are connected to on the left, the actions
    /// that apply to it on the right, OS buttons inset by the component.
    fn render_title_bar(&self, cx: &mut Context<Self>) -> impl IntoElement {
        let session = self.active_session();
        let connected = session.is_some();

        TitleBar::new()
            .child(h_flex().flex_1().min_w_0().gap_2().when_some(
                session.clone(),
                |this, session| {
                    let (name, color) = {
                        let session = session.read(cx);
                        (session.display_name(), session.connection().config.color)
                    };
                    this.when_some(color, |this, color| {
                        this.child(crate::ui::color_dot(color, cx))
                    })
                    .child(div().text_xs().truncate().max_w(px(130.)).child(name))
                    // The bar starts a window move on mouse-move while
                    // held, so interactive children swallow their own
                    // press to avoid dragging the window instead.
                    .child(
                        h_flex()
                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                            .child(Session::render_database_picker(&session, cx)),
                    )
                },
            ))
            .child(
                h_flex()
                    .flex_1()
                    .min_w_0()
                    .justify_end()
                    .gap_1()
                    .px_1()
                    // Every button here is icon-only, so each one carries the
                    // name a screen reader announces: without it there is
                    // nothing to announce but the icon's file.
                    //
                    // The bar starts a window move on mouse-move while held,
                    // so each button swallows its own press the way the
                    // database picker does. The container must not: it would
                    // swallow the empty space between the buttons too, and
                    // the whole right half of the bar would stop dragging. A
                    // disabled button is inert space, so it lets the press
                    // through to the bar instead.
                    .child(
                        Button::new("quick-switcher")
                            .ghost()
                            .xsmall()
                            .icon(gpui_kit::assets::IconName::Search)
                            .accessibility_label("Quick switcher")
                            .tooltip_with_action("Quick switcher", &QuickSwitcher, Some("Session"))
                            .disabled(!connected)
                            .when(connected, |this| {
                                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
                                    cx.stop_propagation()
                                })
                            })
                            .on_click(cx.listener(Self::on_quick_switcher_click)),
                    )
                    .child(
                        Button::new("refresh")
                            .ghost()
                            .xsmall()
                            .icon(gpui_kit::assets::IconName::RefreshCw)
                            .accessibility_label("Refresh")
                            .tooltip_with_action("Refresh", &Refresh, Some("Session"))
                            .disabled(!connected)
                            .when(connected, |this| {
                                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
                                    cx.stop_propagation()
                                })
                            })
                            .on_click(cx.listener(Self::on_refresh_click)),
                    )
                    .child(
                        Button::new("new-query")
                            .ghost()
                            .xsmall()
                            .icon(gpui_kit::assets::IconName::FilePlus)
                            .accessibility_label("New query")
                            .tooltip_with_action("New query", &NewTab, Some("Session"))
                            .disabled(!connected)
                            .when(connected, |this| {
                                this.on_mouse_down(MouseButton::Left, |_, _, cx| {
                                    cx.stop_propagation()
                                })
                            })
                            .on_click(cx.listener(Self::on_new_query_click)),
                    )
                    .child(
                        Button::new("new-connection")
                            .ghost()
                            .xsmall()
                            .icon(gpui_kit::assets::IconName::DatabasePlus)
                            .accessibility_label("Open another connection")
                            .tooltip_with_action(
                                "Open another connection",
                                &NewConnection,
                                Some("Workspace"),
                            )
                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                            .on_click(
                                cx.listener(|this, _, window, cx| {
                                    this.open_connect_tab(window, cx)
                                }),
                            ),
                    )
                    // The settings used to be reachable only by a keystroke
                    // nobody is told about, so they get a button of their own.
                    .child(
                        Button::new("settings")
                            .ghost()
                            .xsmall()
                            .icon(gpui_kit::assets::IconName::Settings)
                            .accessibility_label("Settings")
                            .tooltip_with_action("Settings", &OpenSettings, None)
                            .on_mouse_down(MouseButton::Left, |_, _, cx| cx.stop_propagation())
                            .on_click(|_, _window, cx| settings_window::open(cx)),
                    ),
            )
    }
}

/// Drain the pool in the background; the UI does not wait for it.
fn close(connection: Arc<Connection>) {
    runtime::spawn(async move { connection.close().await });
}

impl Render for Workspace {
    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
        // A requested value dialog is opened before anything else, so it is
        // on screen in the frame that asked for it; the kit's root hosts it
        // above this tree.
        self.take_value_dialog(window, cx);

        let body = match &self.tabs[self.active] {
            TabContent::Connect(welcome) => welcome.clone().into_any_element(),
            TabContent::Session(session) => session.clone().into_any_element(),
        };

        v_flex()
            .size_full()
            .track_focus(&self.focus)
            .key_context("Workspace")
            .on_action(cx.listener(Self::on_new_connection))
            .on_action(cx.listener(Self::on_close_connection))
            .on_action(cx.listener(Self::on_quit))
            .on_action(cx.listener(Self::on_show_shortcuts))
            .on_action(cx.listener(Self::on_next_connection))
            .on_action(cx.listener(Self::on_previous_connection))
            .on_action(cx.listener(Self::on_quick_switcher))
            .on_action(cx.listener(Self::on_search_schema))
            .bg(cx.theme().background)
            .text_color(cx.theme().foreground)
            .child(self.render_title_bar(cx))
            // A strip for a single connection is a title the title bar already
            // carries, so it is only worth the row once there is more than one
            // tab to choose between. Closing the last one still works from
            // `Cmd`/`Ctrl`+`Shift`+`W` and the File menu.
            .when(self.tabs.len() > 1, |this| {
                this.child(
                    v_flex()
                        .id("connection-bar")
                        .test_support()
                        .flex_none()
                        .border_b_1()
                        .border_color(cx.theme().border)
                        .child(self.render_tab_bar(cx)),
                )
            })
            .child(div().flex_1().min_h_0().child(body))
    }
}

#[cfg(test)]
impl Workspace {
    /// Build a workspace from an injected state, so a test never reads the
    /// developer's real workspace file.
    pub(crate) fn with_state_for_test(
        state: WorkspaceState,
        window: &mut Window,
        cx: &mut Context<Self>,
    ) -> Self {
        Self::build(state, window, cx)
    }

    /// The state this workspace would write, for a test to check.
    pub(crate) fn state_for_test(&self, cx: &App) -> WorkspaceState {
        self.snapshot(cx)
    }

    pub(crate) fn tab_titles_for_test(&self, cx: &App) -> Vec<String> {
        self.tabs
            .iter()
            .map(|tab| tab.title(cx).to_string())
            .collect()
    }

    /// What each tab announces: its name, tag and database. The tab draws them
    /// itself, so this is the only text a test can read the bar back as.
    pub(crate) fn tab_labels_for_test(&self, cx: &App) -> Vec<String> {
        self.tabs
            .iter()
            .map(|tab| tab.aria_label(cx).to_string())
            .collect()
    }

    pub(crate) fn active_for_test(&self) -> usize {
        self.active
    }

    /// The connection manager in the active tab, to connect from.
    pub(crate) fn value_dialog_for_test(&self) -> Option<Entity<ValueView>> {
        self.value.clone()
    }

    pub(crate) fn active_welcome_for_test(&self) -> Option<Entity<Welcome>> {
        match self.tabs.get(self.active)? {
            TabContent::Connect(welcome) => Some(welcome.clone()),
            TabContent::Session(_) => None,
        }
    }

    pub(crate) fn active_session_for_test(&self) -> Option<Entity<Session>> {
        match self.tabs.get(self.active)? {
            TabContent::Session(session) => Some(session.clone()),
            TabContent::Connect(_) => None,
        }
    }
}