//! The workspace: the one root every action mutates and every view reads. //! //! The struct and its render live here; the methods that act on it are //! grouped by concern in the sibling modules, which are parts of this same //! inherent impl rather than types of their own. mod agent; mod agent_read; mod agent_write; mod commands; mod diagrams; #[cfg(test)] mod e2e; mod editing; mod exports; use exports::ExportMenu; mod files; mod filters; mod folders; mod forms; mod import_dialog; mod import_rows; mod modes; mod objects; mod profiles; mod projects; mod queries; mod query_move; mod sidebar; mod stable_import; mod tabs; mod transactions; mod welcome; use std::collections::{HashMap, HashSet}; use crate::export::ClipboardFormat; use gpui_component::menu::{DropdownMenu, PopupMenu, PopupMenuItem}; pub(crate) use diagrams::{SideRead, drawn_in_diagrams}; pub(crate) use exports::SchemaExportDialog; pub(crate) use import_dialog::PreviewGrid; #[cfg(test)] pub(crate) use profiles::restored; pub(crate) use profiles::unavailable_reason; pub(crate) use projects::project_name_refusal; pub(crate) use queries::error_in_buffer; use crate::actions::{DisconnectAgents, ShowAgentActivity}; use crate::channel::Channel; use crate::connection_form::{Origin, passphrase_to_persist, password_to_persist}; use crate::session::{catalog_relation, write_buffer, write_grids}; use crate::settings_panel::{SettingMatch, SettingsTab, filter_settings, render_settings_panel}; use crate::sidebar::{ Density, ListingScope, ViewMode, effective_listing_scope, effective_view_mode, }; use crate::sql::{Mode, appended_statement, remember_statement, update_batch}; use crate::theme::{install_fonts, install_theme, restored_fonts, restored_theme}; use crate::*; /// What the app is set to, as opposed to what a connection is. The theme and /// the fonts stay in their globals -- every view reads those at render time, /// without a workspace to ask. pub(crate) struct Settings { pub(crate) chrome_font_size: f32, pub(crate) editor_font_size: f32, pub(crate) grid_font_size: f32, pub(crate) row_limit: Option, /// How much of the window the desktop shows through, for themes with no /// entry in `theme_opacity`. Nothing writes it any more; it is what a /// single shared value from before per-theme opacity restores as. pub(crate) opacity: f32, /// Opacity per theme, keyed by theme name: light glass starts at its own /// default, so one shared value painted a different look on each. pub(crate) theme_opacity: HashMap, /// Whether the theme follows the system between `light_theme` and /// `dark_theme`. The theme on screen is still the global; these name the /// one put on when the system changes side. pub(crate) match_system_appearance: bool, pub(crate) light_theme: String, pub(crate) dark_theme: String, /// One request to GitHub at launch. Off switch because local-first users /// get to say no to the only request DBDelve makes on its own. pub(crate) check_for_updates: bool, /// Some people want the connection colour on the switcher only, not a /// painted band across the window. pub(crate) color_titlebar: bool, /// Whether a new tab sorts on a header click by reordering the rows it /// holds rather than by asking the server again. Off by default, which is /// how every tab sorted before this was a choice. pub(crate) client_sort: bool, /// The edit mode a new table tab starts in. Classic by default, which is /// how editing worked before a view had a mode. pub(crate) edit_mode: EditMode, /// Whether completing a relation writes it as `schema.relation`, for /// databases whose search path does not reach every schema. pub(crate) qualify_completions: bool, /// Whether completing a table after FROM or JOIN adds a short alias, and /// after JOIN offers the condition its foreign keys imply. pub(crate) alias_completions: bool, /// Whether a statement the user runs that dbdelve cannot parse runs without /// the run-once prompt, for people who live in a dialect sqlparser misreads. pub(crate) run_unreadable: bool, /// Whether the diagnostic log takes DBDelve's debug lines and other /// crates' info, applied as it changes (`logging::set_verbose`). pub(crate) verbose_logging: bool, /// Whether the first-run greeting has played on the welcome surface. pub(crate) welcomed: bool, /// Whether the offer to move the saved queries to a folder was turned /// down or taken, so it is not made again. pub(crate) queries_move_dismissed: bool, /// Keybinding overrides, keyed by action id. Applied to the keymap on /// the next launch -- see `src/keybindings.rs`. pub(crate) custom_keybindings: HashMap, /// Which sidebar is drawn: the tree of the connection in front, or every /// connection under its project. pub(crate) view_mode: ViewMode, /// Which connections that sidebar lists: every project's, or only those /// of the project in front. pub(crate) listing_scope: ListingScope, /// How tall the connections tree's rows are. pub(crate) density: Density, /// Whether the connections tree's rows show their host. pub(crate) show_host: bool, /// Whether either tree shows sizes, and whether any is read. pub(crate) show_sizes: bool, } impl Settings { pub(crate) fn font_size(&self, slot: FontSlot) -> f32 { match slot { FontSlot::Chrome => self.chrome_font_size, FontSlot::Editor => self.editor_font_size, FontSlot::Grid => self.grid_font_size, } } } impl Default for Settings { fn default() -> Self { Self { chrome_font_size: layout::BODY_FONT_SIZE, editor_font_size: EDITOR_FONT_SIZE_DEFAULT, grid_font_size: layout::BODY_FONT_SIZE, row_limit: Some(PREVIEW_ROW_LIMIT), opacity: theme::OPACITY_DEFAULT, theme_opacity: HashMap::new(), match_system_appearance: true, light_theme: theme::starting_theme(theme::Appearance::Light) .name .to_string(), dark_theme: theme::starting_theme(theme::Appearance::Dark) .name .to_string(), check_for_updates: true, color_titlebar: true, client_sort: false, edit_mode: EditMode::Classic, qualify_completions: false, alias_completions: true, run_unreadable: false, verbose_logging: false, welcomed: false, queries_move_dismissed: false, custom_keybindings: HashMap::new(), view_mode: ViewMode::default(), listing_scope: ListingScope::default(), density: Density::default(), show_host: true, show_sizes: true, } } } impl Settings { pub(crate) fn opacity_for(&self, theme: &Theme) -> f32 { opacity_for(&self.theme_opacity, self.opacity, theme) } pub(crate) fn set_opacity_for(&mut self, theme: &Theme, opacity: f32) { let opacity = opacity.clamp(theme::OPACITY_MIN, theme::OPACITY_MAX); self.theme_opacity.insert(theme.name.to_string(), opacity); } pub(crate) fn theme_for(&self, side: theme::Appearance) -> &str { match side { theme::Appearance::Light => &self.light_theme, theme::Appearance::Dark => &self.dark_theme, } } pub(crate) fn set_theme_for(&mut self, side: theme::Appearance, name: &str) { let slot = match side { theme::Appearance::Light => &mut self.light_theme, theme::Appearance::Dark => &mut self.dark_theme, }; *slot = name.to_string(); } /// `None` while the theme does not match the system. A name nothing /// answers to any more is that side's starting theme. pub(crate) fn system_theme(&self, system: theme::Appearance) -> Option { self.match_system_appearance .then(|| restored_theme(Some(self.theme_for(system)), system)) } /// The side a theme list opens for, asked again whenever one opens: a /// list waiting on an import scan may find matching turned on or off /// since it was asked for. pub(crate) fn list_side( &self, asked: Option, system: theme::Appearance, ) -> Option { self.match_system_appearance .then(|| asked.unwrap_or(system)) } /// Where a theme picked from a list for `side` goes: the light or dark /// slot it fills, if any, and whether it goes on screen now. A list that /// outlived a change to matching still takes effect: a side's pick shows /// once nothing is matched, and a plain pick while matching fills the /// system's side, or the next change would take it off again. pub(crate) fn pick_target( &self, side: Option, system: theme::Appearance, ) -> (Option, bool) { let matching = self.match_system_appearance; let slot = side.or(matching.then_some(system)); let shows = side.is_none_or(|side| !matching || side == system); (slot, shows) } } /// A stored entry wins. Without one, light glass starts at its own default /// rather than the shared `fallback`, which for an existing user came from /// dark glass; every other theme takes the fallback. pub(crate) fn opacity_for( theme_opacity: &HashMap, fallback: f32, theme: &Theme, ) -> f32 { theme_opacity.get(theme.name).copied().unwrap_or_else(|| { if theme.is_glass && theme.appearance == theme::Appearance::Light { theme.default_opacity() } else { fallback } }) } /// Connections read from another client, held while the user picks the /// project they go into. pub(crate) struct PendingImport { pub(crate) source: crate::import::Source, pub(crate) report: crate::import::Report, /// How many are not here already, which is what the question counts. pub(crate) fresh: usize, /// `None` for No project. pub(crate) project: Option, } pub(crate) struct Workspace { pub(crate) profiles: Vec, /// How many connections each mode change's read-only hold was handed to, /// in order: what the tests ask of the fan-out, which runs on the /// blocking pool where nothing can be counted. #[cfg(test)] pub(crate) held: Vec, /// The database each session opened for another database was issued for, /// in order: a landing that opens again is a second entry. #[cfg(test)] pub(crate) opened: Vec, /// How many size reads were started, which run on the blocking pool where /// nothing can be counted. #[cfg(test)] pub(crate) size_reads: usize, /// Profiles on an engine this build cannot open, held as they were read /// and written back by `remember_profiles`; never restored. pub(crate) unavailable: Vec, /// Discovered once in `main`, before the profiles that name them load. pub(crate) plugins: Vec<&'static crate::db::Plugin>, pub(crate) settings: Settings, /// The profile in front, by index; `None` is the welcome surface, which /// Disconnect leads back to with connections still listed on it. pub(crate) active: Option, pub(crate) form: Option, /// Whether the menu bar last set lists Import Rows. menu_imports_rows: bool, /// The diagram in front at the last render, told to let its render caches /// go once it is not. shown_diagram: Option>, /// Bumped by every import asked for, so a paste still being read when /// another is asked for opens nothing when it lands. import_requests: u64, pub(crate) projects: Vec, /// The welcome surface's project name field, while a project is being /// named there. pub(crate) project_name: Option>, /// The project that field renames; `None` while it names a new one. pub(crate) renaming_project: Option, pub(crate) project_name_needs_focus: bool, /// The field a row-limit menu turned into after Custom…, and whose limit /// it sets. One at a time: it closes the moment it loses focus. pub(crate) custom_limit: Option<(LimitTarget, Entity)>, pub(crate) custom_limit_needs_focus: bool, /// The project whose delete button has been clicked once and is waiting /// for the second. pub(crate) pending_project_deletion: Option, /// Whether the settings panel is up. On the workspace rather than a /// session, because nothing it changes belongs to one connection. pub(crate) settings_open: bool, /// Which category the settings panel is showing. Not persisted -- see /// [`SettingsTab`]. pub(crate) settings_tab: SettingsTab, pub(crate) settings_search: Entity, /// What the settings search finds, worked out as it is typed into rather /// than every frame. `None` while it is empty. pub(crate) settings_matches: Option>, /// The panel's own focus, so zoom can tell the panel being read from the /// pane beside it. pub(crate) settings_focus: FocusHandle, pub(crate) settings_search_needs_focus: bool, /// Whether the palette was opened from inside the settings panel -- a /// theme or a font being picked -- and so hands the keyboard back there. pub(crate) palette_from_settings: bool, /// The action id currently listening for its next keystroke, if a /// keyboard row has one mid-capture. Not persisted: a capture in progress /// does not survive the panel closing, let alone a relaunch. pub(crate) rebinding: Option<&'static str>, /// Whether the explorer column is folded away. Not persisted: a hidden /// sidebar is a thing done for the next minute, not a preference. pub(crate) sidebar_hidden: bool, /// Zoom over each font size, as a percentage. Not persisted: the sizes in /// Settings are the preference, and a zoom is for the next screen share /// or the one wide cell, with ⌘0 the way back. pub(crate) chrome_zoom: u32, pub(crate) editor_zoom: u32, pub(crate) grid_zoom: u32, pub(crate) shell_split: Entity, pub(crate) tab_strip: crate::tab_drag::TabStrip, /// The sidebar row a dragged shortcut would land beside, and whether /// after it: what draws the insertion line, and what a drop on that row /// reads, since a drop is not told where on the row it was let go. pub(crate) explorer_drop: Option<(gpui::SharedString, bool)>, /// Where the sidebar's edge is unless a drag has moved it. The library /// rescales every panel by its share when the window changes size, so this /// is what puts the sidebar back. pub(crate) sidebar_width: std::cell::Cell, /// The window's width the last time the sidebar was put right, which is how /// a window resize is told from a drag of the handle. pub(crate) sidebar_container: std::cell::Cell, /// The sidebar's actual width the last time `settle_sidebar` looked, which /// may be less than `sidebar_width` when the container is too narrow to /// hold it. Comparing against this rather than against `sidebar_width` /// itself is what tells a real drag from that squeeze settling back out. pub(crate) sidebar_last_size: std::cell::Cell, /// The list a reference arrow opens, and which lookup it is waiting on. pub(crate) reference_popup: Option, pub(crate) reference_checks: u64, pub(crate) row_panel: views::RowPanel, /// Whether the plan pane's copy button was just used, so it can show a /// tick the way `row_panel.copied` does. One flag rather than a keyed /// slot: only one plan pane is ever on screen at a time. pub(crate) plan_copied: bool, /// An import's read is still out, so a second click doesn't start another /// round of Keychain prompts whose summary would say all were duplicates. pub(crate) importing: bool, pub(crate) pending_import: Option, /// The other clients installed here, looked for once at launch rather /// than on every frame of the welcome surface. pub(crate) importable: Vec, /// How many connections a DBDelve install here has for a nightly to /// import, looked for once at launch like `importable`. pub(crate) stable_connections: usize, pub(crate) stable_import: Option, /// What `note` says while there is no connection and no form to say it /// on: the welcome surface's line. pub(crate) welcome_notice: Option, pub(crate) cleanup_notices: Vec, pub(crate) queries_notice: Option, /// Statements written for data files opened before their profile had /// connected: profile id, query tab, statement. Run once it has. pub(crate) runs_on_connect: Vec<(String, u64, String)>, /// Where the last SQL file was opened or saved, for Save As to start in. /// Kept for the session only. pub(crate) sql_directory: Option, /// What the window's edited mark was last set to, so it is set only when /// it changes rather than every frame. pub(crate) window_edited: bool, /// Why the welcome surface's name field refused what was typed: a line /// of its own, so a refusal never covers the notice, which may be the /// only word that the profiles file failed to load. pub(crate) project_name_error: Option, /// The welcome surface's half of `editor_needs_focus`: set when whatever /// held focus over it has gone, applied on the next frame. pub(crate) welcome_needs_focus: bool, /// The welcome surface's connection URL field. Kept rather than built /// with the surface: a fresh one every frame would lose what was typed. pub(crate) welcome_url: Entity, /// When the welcome surface last came on screen, and whether it was /// greeting a first run. `None` while something else is in front, so it /// enters again the next time it is shown. pub(crate) welcome_entrance: Option, /// A column a structure tab asked to see, waiting for its data tab's rows: /// the tab's id and the column's name. pub(crate) reveal_on_rows: Option<(u64, String)>, /// Whether `store::load_profiles` failed and could not move the file it /// failed on aside. Set once at startup and never cleared: the file is /// still sitting there, and a session that never saw it must not be the /// one that overwrites it, whatever it has made since. pub(crate) store_unreadable: bool, pub(crate) next_generation: u64, /// The palette, built from scratch every time it opens. Its rows are a /// snapshot of what the catalog held and which tab was in front, and both /// can move underneath it — so it is thrown away on the way out rather /// than kept and refreshed. pub(crate) palette: Option>, /// The rows last confirmed in the palette, by scope and label, newest /// first, for its Recent group. Kept for the session only. pub(crate) palette_recents: Vec<(Scope, String)>, /// The projects folded in the palette's Connections scope, by name. Kept /// for the session only, and never the one in front as a palette opens. pub(crate) collapsed_projects: HashSet, /// The theme in force when the theme picker opened, while it is open. The /// installed one is only a preview until a row is confirmed. pub(crate) theme_before_preview: Option, /// The `Show DDL` dialog: one object's definition, read-only. Only the /// relation menu's Show DDL opens it and only its own Close and `escape` /// end it. pub(crate) ddl_view: Option, /// Numbers each Show DDL read, so an answer that comes back after the /// dialog was closed, or put up for another object, is not drawn. pub(crate) last_ddl_request: u64, /// The id of the profile whose agent-visibility dialog is open. Only that /// dialog sets it, and `set_agent_visible` grants visibility only to the /// profile it names. pub(crate) agent_visibility_prompt: Option, /// Whether an agent's read of the profile in [`Self::agent_visibility_prompt`] /// can make the owner's commit wait. Read from the file once, when the /// dialog opens, so drawing it never touches the disk. pub(crate) agent_visibility_blocks_commits: bool, /// The agent bridge: the socket, and the calls waiting on this window. pub(crate) agent: agent::AgentState, /// Whether the `Agent activity` dialog is up. Only the popover's item /// opens it and only its own close and `escape` end it. pub(crate) agent_audit_open: bool, /// The opacity field in the settings panel. Kept here rather than built /// with the card, because an input is state the user is part-way through /// typing into and a fresh one every frame would swallow the keystroke. pub(crate) opacity_input: Entity, /// The window's own focus, for the moments when nothing inside it can hold /// any. See [`Focus::Window`]. pub(crate) focus: FocusHandle, /// Around the sidebar's tree, whose own handle the library keeps to /// itself: what tells an `escape` in the tree from one anywhere else. pub(crate) explorer_focus: FocusHandle, /// Complex mode's tree: every connection under its project. pub(crate) connections: sidebar::ConnectionsSidebar, /// The dialogs' own, so `enter` answers the one in front instead of /// editing the buffer or the grid it covers. pub(crate) dialog_focus: FocusHandle, /// Which dialog was in front last frame, so a change of it moves the /// keyboard to the one now there. pub(crate) dialog_in_front: std::cell::Cell>, /// The button `enter` presses in it, counted from the right. pub(crate) dialog_choice: std::cell::Cell, /// What held the keyboard when the first dialog went up. pub(crate) focus_before_dialog: std::cell::RefCell>, /// The tab in front, by its profile's id and its own, when its file was /// last looked at: a tab reaching the front by any path is looked at /// once, not every frame. pub(crate) file_looked_at: Option<(String, u64)>, /// The source statement the approval dialog was last drawn from, by call, /// so Approve can refuse a call that was never drawn or whose statement is /// not the one drawn (GATE-10). Written by the render through `&self`. pub(crate) approval_shown: std::cell::RefCell>, /// Where the approval's statement block is scrolled, by call, so the next /// call opens at its first line and the scrollbar reads the same offset. pub(crate) approval_scroll: std::cell::RefCell>, /// See [`Workspace::welcome_project_focus`]. pub(crate) welcome_project_focus: std::cell::RefCell>, pub(crate) update: Option, /// The launch check and the ones after it; dropped, they stop. update_checks: Option>, /// Something `profiles.toml` holds changed and is waiting on /// [`Self::remember_profiles_soon`]'s timer, so quitting writes it. pub(crate) profiles_unsaved: bool, /// That timer; replaced, the one before it stops. profiles_save: Option>, } impl Workspace { pub(crate) fn new( plugins: Vec<&'static crate::db::Plugin>, window: &mut Window, cx: &mut Context, ) -> Self { let row_panel_search = cx.new(|cx| { InputState::new(window, cx) .placeholder("Filter columns and values…") .clean_on_escape() }); cx.subscribe( &row_panel_search, |workspace, input, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { let value = input.read(cx).value(); if let Some((_, _, filter)) = workspace.active_row_panel() { *filter = value; } cx.notify(); } }, ) .detach(); let settings_search = cx.new(|cx| InputState::new(window, cx).placeholder("Search settings")); cx.subscribe(&settings_search, |workspace, _, event: &InputEvent, cx| { if matches!(event, InputEvent::Change) { workspace.search_settings(cx); } }) .detach(); let welcome_url = cx.new(|cx| { InputState::new(window, cx) .placeholder("Paste a connection URL") .clean_on_escape() }); cx.subscribe_in( &welcome_url, window, |workspace, _, event: &InputEvent, window, cx| match event { InputEvent::Change => cx.notify(), InputEvent::PressEnter { .. } => workspace.submit_welcome_url(window, cx), _ => {} }, ) .detach(); let opacity_input = cx.new(|cx| InputState::new(window, cx)); // With the window, because committing reinstalls the theme. Enter and // blur both count as done: a percentage is short enough that clicking // away from it is as much an answer as pressing return. cx.subscribe_in( &opacity_input, window, |workspace, _, event: &InputEvent, window, cx| { if matches!(event, InputEvent::PressEnter { .. } | InputEvent::Blur) { workspace.commit_opacity_input(window, cx); } }, ) .detach(); cx.observe_window_appearance(window, |workspace, window, cx| { workspace.follow_system_appearance(window, cx); }) .detach(); // The desktop portal reports the button layout after the first frame, // and GPUI tells observers without redrawing, so the titlebar would // keep the default buttons until something else repainted it. window .observe_button_layout_changed(|window, _| window.refresh()) .detach(); let mut workspace = Self { profiles: Vec::new(), unavailable: Vec::new(), plugins, settings: Settings::default(), active: None, form: None, menu_imports_rows: false, shown_diagram: None, import_requests: 0, projects: Vec::new(), project_name: None, renaming_project: None, project_name_needs_focus: false, custom_limit: None, custom_limit_needs_focus: false, pending_project_deletion: None, settings_open: false, settings_tab: SettingsTab::default(), settings_search, settings_matches: None, settings_focus: cx.focus_handle(), settings_search_needs_focus: false, palette_from_settings: false, rebinding: None, sidebar_hidden: false, chrome_zoom: 100, editor_zoom: 100, grid_zoom: 100, shell_split: cx.new(|_| ResizableState::default()), tab_strip: crate::tab_drag::TabStrip::default(), explorer_drop: None, sidebar_width: std::cell::Cell::new(px(layout::SIDEBAR_DEFAULT_WIDTH)), sidebar_container: std::cell::Cell::new(px(0.)), sidebar_last_size: std::cell::Cell::new(px(layout::SIDEBAR_DEFAULT_WIDTH)), reference_popup: None, reference_checks: 0, row_panel: views::RowPanel { on_screen: Default::default(), copied: None, search: row_panel_search, searched: Default::default(), inputs: None, focus_input: false, typing: None, revealed: Default::default(), }, plan_copied: false, importing: false, pending_import: None, importable: crate::import::Source::ALL .into_iter() .filter(|source| source.found()) .collect(), stable_connections: stable_import::stable_connections(), stable_import: None, welcome_notice: None, cleanup_notices: Vec::new(), queries_notice: None, runs_on_connect: Vec::new(), sql_directory: None, window_edited: false, project_name_error: None, welcome_needs_focus: true, welcome_url, welcome_entrance: None, reveal_on_rows: None, store_unreadable: false, next_generation: 0, palette: None, palette_recents: Vec::new(), collapsed_projects: HashSet::new(), theme_before_preview: None, ddl_view: None, last_ddl_request: 0, agent_visibility_prompt: None, agent_visibility_blocks_commits: false, agent_audit_open: false, agent: agent::AgentState::default(), opacity_input, #[cfg(test)] held: Vec::new(), #[cfg(test)] opened: Vec::new(), #[cfg(test)] size_reads: 0, focus: cx.focus_handle(), explorer_focus: cx.focus_handle(), connections: sidebar::ConnectionsSidebar::new(window, cx), dialog_focus: cx.focus_handle(), dialog_in_front: std::cell::Cell::default(), dialog_choice: std::cell::Cell::default(), focus_before_dialog: std::cell::RefCell::default(), file_looked_at: None, approval_shown: std::cell::RefCell::default(), approval_scroll: std::cell::RefCell::default(), welcome_project_focus: std::cell::RefCell::default(), update: None, update_checks: None, profiles_unsaved: false, profiles_save: None, }; let mut load_failure = None; // Read once, here, to decide whether to listen. The window keeps no // copy: a saved one is what would write `true` back over another // window's kill switch (see `agent_access_to_save`). let mut listen_at_launch = false; match store::load_profiles(&workspace.plugins) { Ok(store::ProfileList { profiles, active, fonts: stored_fonts, settings: stored_settings, projects, unavailable, }) => { // Before the first frame, so the window is drawn in the faces // the user picked rather than repainted into them. let stored_settings = stored_settings.unwrap_or_default(); listen_at_launch = stored_settings.agent_access.unwrap_or(false); // Ahead of the fonts and the theme, which size gpui-component's // widgets off the chrome size as they install. let chrome_font_size = restored_font_size(FontSlot::Chrome, stored_settings.chrome_font_size); let grid_font_size = restored_font_size(FontSlot::Grid, stored_settings.grid_font_size); workspace.settings.chrome_font_size = chrome_font_size; workspace.settings.grid_font_size = grid_font_size; layout::set_chrome_font_size(chrome_font_size); layout::set_grid_font_size(grid_font_size); let available = cx.text_system().all_font_names(); install_fonts(restored_fonts(stored_fonts, &available), cx); workspace.settings.opacity = restored_opacity(stored_settings.opacity); workspace.settings.theme_opacity = stored_settings .theme_opacity .iter() .flatten() .map(|(name, opacity)| (name.clone(), restored_opacity(Some(*opacity)))) .collect(); let system = theme::Appearance::of_system(window.appearance()); // Older settings could save a fixed theme before the toggle existed. workspace.settings.match_system_appearance = stored_settings.match_system_appearance.unwrap_or( workspace.settings.match_system_appearance && stored_settings.theme.is_none(), ); // Through the list, so a theme gone since is named as the one // it falls back to rather than as nothing at all. for (side, stored) in [ (theme::Appearance::Light, &stored_settings.light_theme), (theme::Appearance::Dark, &stored_settings.dark_theme), ] { let name = restored_theme(stored.as_deref(), side).name; workspace.settings.set_theme_for(side, name); } let restored = workspace .settings .system_theme(system) .unwrap_or_else(|| restored_theme(stored_settings.theme.as_deref(), system)); install_theme( restored.with_opacity(workspace.settings.opacity_for(&restored)), window, cx, ); // The zoom was per-profile until settings existed, so a file // with no app-wide value has one under whichever profile was in // front -- and reading it there is what keeps a person's zoom // across the upgrade instead of resetting it. workspace.settings.editor_font_size = restored_font_size( FontSlot::Editor, stored_settings.editor_font_size.or_else(|| { profiles .iter() .find(|stored| Some(stored.id.as_str()) == active.as_deref()) .or_else(|| profiles.first()) .and_then(|stored| stored.editor_font_size) }), ); workspace.settings.row_limit = stored_settings.row_limit(); workspace.settings.check_for_updates = stored_settings.check_for_updates.unwrap_or(true); workspace.settings.color_titlebar = stored_settings.color_titlebar.unwrap_or(true); workspace.settings.client_sort = stored_settings.client_sort.unwrap_or(false); workspace.settings.edit_mode = EditMode::from_slug(stored_settings.edit_mode.as_deref()); workspace.settings.qualify_completions = stored_settings.qualify_completions.unwrap_or(false); workspace.settings.alias_completions = stored_settings.alias_completions.unwrap_or(true); workspace.settings.run_unreadable = stored_settings.run_unreadable.unwrap_or(false); workspace.settings.verbose_logging = stored_settings.verbose_logging.unwrap_or(false); crate::logging::set_verbose(workspace.settings.verbose_logging); workspace.settings.welcomed = welcome::welcomed( stored_settings.welcomed, !profiles.is_empty() || !unavailable.is_empty(), ); workspace.settings.queries_move_dismissed = stored_settings.queries_move_dismissed.unwrap_or(false); workspace.settings.custom_keybindings = stored_settings .custom_keybindings .clone() .unwrap_or_default(); workspace.settings.view_mode = ViewMode::from_slug(stored_settings.view_mode.as_deref()); workspace.settings.listing_scope = ListingScope::from_slug(stored_settings.listing_scope.as_deref()); workspace.settings.density = Density::from_slug(stored_settings.sidebar_density.as_deref()); workspace.settings.show_host = stored_settings.sidebar_show_host.unwrap_or(true); workspace.settings.show_sizes = stored_settings.sidebar_show_sizes.unwrap_or(true); // Ahead of the restore, which must not prune grids an // unavailable profile under the same id still owns. workspace.unavailable = unavailable; for stored in profiles { workspace.restore_profile(stored, window, cx); } // Where the last session was left. With no `active` it was // left on the welcome surface, and starts there connecting // nothing. workspace.active = active.and_then(|id| { workspace .profiles .iter() .position(|profile| profile.id == id) }); let live = workspace .profiles .iter() .map(|profile| profile.id.as_str()) .chain(workspace.unavailable.iter().map(|gone| gone.id.as_str())) .collect::>(); workspace.projects = projects::normalized_projects(projects, &live); // Only a restore that hid a profile read as Postgres leaves a // choice at launch. Saving after the loop and the projects // writes the whole file, and clears the choice so another // window's later grant is adopted, not overwritten. A launch // that narrowed nothing writes nothing. if !workspace.agent.visibility_choices.is_empty() { workspace.remember_profiles(cx); } } Err(failure) => { workspace.store_unreadable = !failure.moved_aside; load_failure = Some(failure.message); } } match connection_config_from_environment() { Ok(Some(config)) => { let existing = workspace.profiles.iter().position(|profile| { profile.config.engine() == config.engine() && profile.config.endpoint() == config.endpoint() && profile.config.service() == config.service() && profile.config.server().map(|server| server.user.as_str()) == config.server().map(|server| server.user.as_str()) }); workspace.active = Some(match existing { Some(index) => index, None => { let name = default_profile_name(&config); workspace.create_profile( name, config, None, Mode::default(), Origin::Environment, window, cx, ) } }); // The environment picked the profile, so it is the one to come // back to next launch -- when there may be no environment. workspace.remember_profiles(cx); } Ok(None) => {} Err(message) => { let mut form = ConnectionForm::new(None, window, cx); form.error = Some(message); workspace.form = Some(form); } } // A connection nothing connects at launch gets no other rebuild, and // the tree would sit empty over profiles that are all there. workspace.rebuild_connections(cx); workspace.look_at_recent_files(cx); workspace.offer_to_move_queries(); // After the environment's form, which takes the notice over the // welcome surface when there is one. A load failure's last, since it // says nothing will be saved. if let Some(message) = store::stable_import::take_notice() { workspace.note(message, cx); } if let Some(message) = load_failure { workspace.note(message, cx); } // A refusal is shown and nothing saved changes: the choice is the // user's, and a window that found another one serving can be asked // again from the palette. if listen_at_launch && let Err(text) = workspace.listen_for_agents(cx) { workspace.note(text, cx); } if workspace.settings.check_for_updates { workspace.update_checks = Some(Self::check_for_updates(cx)); } // A rebind capture takes the next keystroke whatever it is, and an // interceptor is the only place that can give it one: GPUI matches a // keystroke against the keymap and dispatches the action *before* any // element listener runs, so a capture handler on the row would see // `cmd+enter` only after it had already run the query. It is also the // only place early enough to read back a chord the app already has // bound, which is most of what a rebind is for. With no capture in // progress the panel is just another surface, and keys go where focus // sends them. let this = cx.weak_entity(); cx.intercept_keystrokes(move |event, window, cx| { let keystroke = event.keystroke.clone(); this.update(cx, |workspace, cx| { // The palette opens over the panel and holds the keyboard // while it does, as the connection form does in its place. let Some(id) = workspace.rebinding.filter(|_| { workspace.settings_open && workspace.palette.is_none() && workspace.form.is_none() }) else { return; }; // Starting a capture puts focus in the panel, so focus // anywhere else is a click elsewhere: a change of mind, and // the key is for whatever took focus. A window focused on // nothing is not elsewhere: that is a button pressed from the // keyboard and unmounted, which `on_focus_lost` hands back to // the panel. if window.focused(cx).is_some() && !workspace.settings_focus.contains_focused(window, cx) { workspace.cancel_rebind(cx); return; } if keybindings::is_modifier(&keystroke.key) { return; } if keystroke.key == "escape" { workspace.cancel_rebind(cx); } else { // `unparse`, not `to_string` -- the latter is the glyphs // a menu draws, and nothing reads those back. workspace.apply_rebind(id, keystroke.unparse(), cx); } cx.stop_propagation(); }) .ok(); }) .detach(); // A button pressed from the keyboard holds focus, and in the settings // panel one can be gone the next frame -- Reset once there is nothing // left to reset, Edit while its row waits for a key, a row the search // no longer finds. A window focused on nothing has every binding dead, // so the panel takes the keyboard back for it. cx.on_focus_lost(window, |workspace, window, cx| { if workspace.settings_open && window.focus_lost_restore_target(cx).as_ref() == Some(&workspace.settings_focus) { workspace.settings_focus.focus(window, cx); } }) .detach(); // Finish writes synchronously: the process is going, and nothing // would wait for background work to finish. The profiles only when a // write is pending: written unasked, they would put this session's // copy over one another instance saved since. // // The agent socket file goes with the window; the user's choice stays // saved, so the next launch listens again only if access was on. cx.on_app_quit(|workspace: &mut Self, cx: &mut Context| { workspace.persist_buffers(cx); if workspace.profiles_unsaved { let _ = workspace.save_profiles(cx); } workspace.drop_bridge(); async {} }) .detach(); // Another editor may have written the front tab's file while the // window was behind it. cx.observe_window_activation(window, |workspace, window, cx| { if window.is_window_active() { workspace.check_front_file(window, cx); workspace.look_at_recent_files(cx); } }) .detach(); // Window release also persists when the window closes without Quit. cx.on_release(|workspace, cx| { workspace.persist_buffers(cx); if workspace.profiles_unsaved { let _ = workspace.save_profiles(cx); } workspace.drop_bridge(); }) .detach(); match store::stable_import::take_secrets_to_copy() { // The connect reads its password from the keychain, which the // copy is about to write, so it waits for the copy. Some(secrets) => { let then_connect = workspace.profile().map(|profile| profile.id.clone()); cx.on_next_frame(window, move |workspace, _, cx| { workspace.copy_imported_passwords(secrets, then_connect, cx); }); } None => workspace.connect_active(cx), } workspace } pub(crate) fn profile(&self) -> Option<&Profile> { self.profiles.get(self.active?) } pub(crate) fn profile_mut(&mut self) -> Option<&mut Profile> { self.profiles.get_mut(self.active?) } /// The engine every statement dbdelve generates is written for. With no /// profile there is nothing to run it against, so the default is only ever /// used to build a string nobody sends. pub(crate) fn engine(&self) -> Engine { self.profile() .map(|profile| profile.config.engine()) .unwrap_or_default() } /// [`Self::engine`] and the driver that reaches it, which the abilities /// are asked of. pub(crate) fn target(&self) -> Target { self.profile() .map_or(Target::built_in(Engine::default()), |profile| { profile.config.target() }) } pub(crate) fn issued_to(&mut self, id: &str, generation: u64) -> Option<&mut Profile> { self.profiles .iter_mut() .find(|profile| profile.id == id && profile.generation == generation) } /// A notice describes what happened to the last thing the user asked for, so /// asking for the next thing takes it down. Otherwise a refusal like "this /// column cannot be edited" sits in the status bar for the rest of the /// session. /// /// Called from the gestures that run SQL rather than from /// `execute_and_then`, because a statement dbdelve runs on its own — restoring /// a tab at startup — would otherwise clear a notice nobody has read yet, /// and one of those says the connection came up weaker than it asked for. pub(crate) fn clear_notice(&mut self) { match self.profile_mut() { Some(profile) => { profile.session.notice = None; profile.session.tab_notice = None; } None => self.welcome_notice = None, } } /// Said over restored rows while their refresh is in flight, and taken /// down by that refresh landing -- only if it is still what the status bar /// says. pub(crate) const REFRESHING: &str = "These rows are being refreshed."; /// Hands focus back to what is in front once whatever held it has gone: /// the tab, or the welcome surface when there is no connection. A field /// unmounted with focus in it leaves the window focused on nothing, and /// every keybinding dead. pub(crate) fn refocus_front(&mut self) { match self.profile_mut() { Some(profile) => profile.session.editor_needs_focus = true, None => self.welcome_needs_focus = true, } } fn disconnect_agents_action( &mut self, _: &DisconnectAgents, _: &mut Window, cx: &mut Context, ) { self.disconnect_agents(cx); } fn show_agent_activity_action( &mut self, _: &ShowAgentActivity, _: &mut Window, cx: &mut Context, ) { self.show_agent_activity(cx); } pub(crate) fn note(&mut self, message: String, cx: &mut Context) { if let Some(profile) = self.profile_mut() { profile.session.notice = Some(message); } else if let Some(form) = &mut self.form { form.error = Some(message); } else { self.welcome_notice = Some(message); } cx.notify(); } pub(crate) fn zoom_editor_in( &mut self, _: &ZoomEditorIn, window: &mut Window, cx: &mut Context, ) { let slot = self.zoom_target(window, cx); self.set_zoom(slot, self.zoom_step(slot, true), cx); } pub(crate) fn zoom_editor_out( &mut self, _: &ZoomEditorOut, window: &mut Window, cx: &mut Context, ) { let slot = self.zoom_target(window, cx); self.set_zoom(slot, self.zoom_step(slot, false), cx); } pub(crate) fn reset_editor_zoom( &mut self, _: &ResetEditorZoom, window: &mut Window, cx: &mut Context, ) { let slot = self.zoom_target(window, cx); self.set_zoom(slot, 100, cx); } pub(crate) fn zoom(&self, slot: FontSlot) -> u32 { match slot { FontSlot::Chrome => self.chrome_zoom, FontSlot::Editor => self.editor_zoom, FontSlot::Grid => self.grid_zoom, } } /// The chrome's zoom stops where its size would leave the range Settings /// offers, for the titlebar's sake; the editor and the grid have room to /// take every level. fn zoom_step(&self, slot: FontSlot, zoom_in: bool) -> u32 { let next = stepped_zoom(self.zoom(slot), zoom_in); if slot != FontSlot::Chrome { return next; } let (min, _, max) = font_size_range(FontSlot::Chrome); if (min..=max).contains(&zoomed(self.settings.chrome_font_size, next)) { next } else { self.chrome_zoom } } fn set_zoom(&mut self, slot: FontSlot, percent: u32, cx: &mut Context) { match slot { FontSlot::Chrome => { self.chrome_zoom = percent; self.apply_chrome_size(cx); } FontSlot::Editor => self.editor_zoom = percent, FontSlot::Grid => { self.grid_zoom = percent; self.apply_grid_size(cx); } } cx.refresh_windows(); } fn apply_chrome_size(&self, cx: &mut App) { layout::set_chrome_font_size(zoomed(self.settings.chrome_font_size, self.chrome_zoom)); let theme = *theme(cx); theme.apply_to_components(cx); } /// The size the editor is drawn at: the saved size under the zoom. pub(crate) fn editor_size(&self) -> f32 { zoomed(self.settings.editor_font_size, self.editor_zoom) } fn apply_grid_size(&self, cx: &mut App) { layout::set_grid_font_size(zoomed(self.settings.grid_font_size, self.grid_zoom)); // The table reads the gutter's width once and keeps it, so every grid // open anywhere has to be told it changed. for profile in &self.profiles { for grid in profile.session.grids() { grid.update(cx, |table, cx| table.refresh(cx)); } } } /// Zoom acts on the pane the keyboard is in: the editor or the grid while /// one holds focus, a cell being edited included, and the chrome /// everywhere else. fn zoom_target(&self, window: &Window, cx: &App) -> FontSlot { // The palette floats over the panes, and what is being read then is // it, whichever pane kept focus underneath. The settings panel sits // beside them, and counts only while it holds the keyboard. if self.palette.is_some() || (self.settings_open && self.settings_focus.contains_focused(window, cx)) { return FontSlot::Chrome; } let Some(session) = self.profile().map(|profile| &profile.session) else { return FontSlot::Chrome; }; let holds_focus = |handle: FocusHandle| handle.contains_focused(window, cx); if session .editor(session.active) .is_some_and(|editor| holds_focus(editor.focus_handle(cx))) { FontSlot::Editor } else if session .active_results() .is_some_and(|results| holds_focus(results.focus_handle(cx))) { FontSlot::Grid } else { FontSlot::Chrome } } pub(crate) fn step_font_size(&mut self, slot: FontSlot, delta: f32, cx: &mut Context) { let adjusted = adjusted_font_size(slot, self.settings.font_size(slot), delta); self.set_font_size(slot, adjusted, cx); } /// Written through to disk, because a size that resets on relaunch is a /// setting the user has to make again every morning. pub(crate) fn set_font_size(&mut self, slot: FontSlot, size: f32, cx: &mut Context) { if self.settings.font_size(slot) == size { return; } match slot { // A zoom kept over a new chrome size could carry it past the // titlebar's range, where no step back fits. FontSlot::Chrome => { self.settings.chrome_font_size = size; self.chrome_zoom = 100; self.apply_chrome_size(cx); } FontSlot::Editor => self.settings.editor_font_size = size, FontSlot::Grid => { self.settings.grid_font_size = size; self.apply_grid_size(cx); } } self.remember_profiles(cx); // The whole window, not just this view: the grid is its own entity, // and nothing about its rows changed to make it redraw. cx.refresh_windows(); } /// The default a relation tab opens with. Written through for the same /// reason the zoom is, and deliberately not applied to the tabs already /// open: their row count is a property of those rows, and changing a /// default must never re-run a query nobody asked to re-run. pub(crate) fn set_default_row_limit(&mut self, rows: Option, cx: &mut Context) { if self.settings.row_limit == rows { return; } self.settings.row_limit = rows; self.remember_profiles(cx); cx.notify(); } pub(crate) fn set_check_for_updates(&mut self, check: bool, cx: &mut Context) { if self.settings.check_for_updates == check { return; } self.settings.check_for_updates = check; self.update_checks = check.then(|| Self::check_for_updates(cx)); self.remember_profiles(cx); cx.notify(); } /// At launch and every [`update::RECHECK`] after it. fn check_for_updates(cx: &mut Context) -> gpui::Task<()> { cx.spawn(async move |workspace, cx| { loop { let found = spawn_blocking(cx.background_executor(), update::newer_release).await; let open = workspace.update(cx, |workspace, cx| { // A check that comes back while an update is being // installed must not take its progress away. let running = workspace .update .as_ref() .is_some_and(|update| matches!(update.state, update::State::Running(_))); if let Some(found) = found.filter(|_| !running) { workspace.update = Some(found); cx.notify(); if update::installs_unattended() { workspace.install_update(cx); } } }); if open.is_err() { return; } cx.background_executor().timer(update::RECHECK).await; } }) } /// Update and restart: from [`update::State::Ready`], or again after a /// failure, so a second click while one runs does nothing. pub(crate) fn install_update(&mut self, cx: &mut Context) { let Some(update) = self.update.as_mut() else { return; }; let progress = std::sync::Arc::new(update::Progress::default()); let state = std::mem::replace(&mut update.state, update::State::Running(progress.clone())); let (update::State::Ready(installer) | update::State::Failed(_, installer)) = state else { update.state = state; return; }; cx.notify(); // The pill's percentage moves on this tick alone: the download goes to // a file, never through anything that would redraw. let ticking = progress.clone(); cx.spawn(async move |workspace, cx| { loop { cx.background_executor() .timer(std::time::Duration::from_millis(500)) .await; let running = workspace.update(cx, |workspace, cx| { // This attempt's progress, not any: a retry started // within a tick of a failure brings a ticker of its own. let running = workspace.update.as_ref().is_some_and(|update| { matches!(&update.state, update::State::Running(progress) if std::sync::Arc::ptr_eq(progress, &ticking)) }); if running { cx.notify(); } running }); if !matches!(running, Ok(true)) { break; } } }) .detach(); let install = spawn_blocking(cx.background_executor(), { let installer = installer.clone(); move || update::install(&installer, &progress) }); cx.spawn(async move |workspace, cx| { let installed = install.await; _ = workspace.update(cx, |workspace, cx| match installed { Ok(installed) => { tracing::info!("restarting into the update"); restart_into(installed, cx); } Err(reason) => { if let Some(update) = workspace.update.as_mut() { update.state = update::State::stopped(reason, installer); } cx.notify(); } }); }) .detach(); } /// The newer release at the far end of the titlebar, and its dropdown: /// one click to update where this install can replace itself, the /// release page where it cannot or where that failed. fn render_update_pill(&self, cx: &mut Context) -> Option { let t = *theme(cx); let update = self.update.as_ref()?; let version = update.release.version.clone(); let channel = Channel::current(); let name = channel.display_name(); // A nightly's version is mostly a date stamp, too long for the // titlebar beside the name, which already says nightly. let available = match channel { Channel::Stable => format!("{name} {version} available"), Channel::Nightly => "New nightly available".to_string(), }; let url = update.release.url.clone(); let (label, menu): (String, Rc PopupMenu>) = match &update.state { update::State::Link => ( available, Rc::new(move |menu| { menu.label("Update it with your package manager,") .label("or download it from GitHub.") .separator() .link(format!("Download {version}"), url.clone()) }), ), update::State::Ready(_) => { let workspace = cx.weak_entity(); ( available, Rc::new(move |menu| { let workspace = workspace.clone(); menu.item(PopupMenuItem::new("Update and restart").on_click( move |_, _, cx| { _ = workspace .update(cx, |workspace, cx| workspace.install_update(cx)); }, )) .separator() .link("Release notes", url.clone()) }), ) } update::State::Running(progress) => { let status = match channel { Channel::Stable => { format!("{name} {version} opens once it is installed.") } Channel::Nightly => "The new nightly opens once it is installed.".to_string(), }; ( progress.label(), Rc::new(move |menu| { menu.label(status.clone()) .separator() .link("Release notes", url.clone()) }), ) } &update::State::Failed(reason, _) => { let workspace = cx.weak_entity(); ( available, Rc::new(move |menu| { let workspace = workspace.clone(); menu.label(reason) .item(PopupMenuItem::new("Try again").on_click(move |_, _, cx| { _ = workspace .update(cx, |workspace, cx| workspace.install_update(cx)); })) .separator() .link(format!("Download {version}"), url.clone()) }), ) } update::State::Superseded(installed) => { let installed = installed.clone(); ( "Restart to update".into(), Rc::new(move |menu| { let installed = installed.clone(); menu.label(format!("{name} was updated since it started.")) .item( PopupMenuItem::new(format!("Restart {name}")) .on_click(move |_, _, cx| restart_into(installed.clone(), cx)), ) .separator() .link("Release notes", url.clone()) }), ) } }; // On a wrapper: `dropdown_menu` wraps the button, so a margin on the // button never reaches the titlebar's row. Some( div() .ml_auto() .child(ui::update_pill(t, label).dropdown_menu(move |popup, _, _| menu(popup))) .into_any_element(), ) } pub(crate) fn set_verbose_logging(&mut self, verbose: bool, cx: &mut Context) { if self.settings.verbose_logging == verbose { return; } self.settings.verbose_logging = verbose; crate::logging::set_verbose(verbose); self.remember_profiles(cx); cx.notify(); } pub(crate) fn set_color_titlebar(&mut self, color: bool, cx: &mut Context) { if self.settings.color_titlebar == color { return; } self.settings.color_titlebar = color; self.remember_profiles(cx); cx.notify(); } /// The sorting a new tab starts with. Not applied to the tabs already /// open, for the reason `set_default_row_limit` is not: each holds its own. pub(crate) fn set_client_sort(&mut self, client: bool, cx: &mut Context) { if self.settings.client_sort == client { return; } self.settings.client_sort = client; self.remember_profiles(cx); cx.notify(); } /// The edit mode a new table tab starts in. Not applied to the tabs already /// open, each of which holds its own. pub(crate) fn set_default_edit_mode(&mut self, mode: EditMode, cx: &mut Context) { if self.settings.edit_mode == mode { return; } self.settings.edit_mode = mode; self.remember_profiles(cx); cx.notify(); } pub(crate) fn set_run_unreadable(&mut self, run: bool, cx: &mut Context) { if self.settings.run_unreadable == run { return; } self.settings.run_unreadable = run; self.remember_profiles(cx); cx.notify(); } /// Rebuilt on every profile now rather than at its next catalog load, which /// may be a reconnect away. pub(crate) fn set_qualify_completions(&mut self, qualify: bool, cx: &mut Context) { if self.settings.qualify_completions == qualify { return; } self.settings.qualify_completions = qualify; let ids: Vec = self .profiles .iter() .map(|profile| profile.id.clone()) .collect(); for id in ids { self.install_completions(&id, cx); } self.remember_profiles(cx); cx.notify(); } /// Rebuilt on every profile now rather than at its next catalog load. pub(crate) fn set_alias_completions(&mut self, alias: bool, cx: &mut Context) { if self.settings.alias_completions == alias { return; } self.settings.alias_completions = alias; let ids: Vec = self .profiles .iter() .map(|profile| profile.id.clone()) .collect(); for id in ids { if let Some(profile) = self.profiles.iter_mut().find(|profile| profile.id == id) { // Columns cached while this was off were fetched without the // reverse foreign keys the join conditions need. profile.session.completion_columns = completion::ColumnCache::default(); } self.install_completions(&id, cx); } self.remember_profiles(cx); cx.notify(); } /// Written through for the same reason the zoom is: a font that resets on /// relaunch is a setting the user has to make again every morning. pub(crate) fn set_font(&mut self, slot: FontSlot, family: String, cx: &mut Context) { let mut picked = fonts(cx).clone(); picked.set(slot, family.into()); install_fonts(picked, cx); self.remember_profiles(cx); cx.refresh_windows(); } } /// What `settle_sidebar` should do with the split this frame, decided from /// numbers alone so the decision is testable without a window. #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum SidebarSettle { /// The container changed size: put the sidebar back at its remembered /// width, clamped to whatever room the content panel's minimum leaves. Resize, /// The container didn't move, so nothing but a drag could have changed /// the handle: adopt the new width as the one to remember. Adopt, /// Nothing changed since the last time this settled. Settled, } /// `last_size` is the sidebar's actual width the last time this ran, which /// can differ from `target` (the width to put it back at) when the container /// was too narrow to hold `target` in full -- that squeeze must resolve /// through `Resize`, never `Adopt`, or widening the window again could never /// recover the width the user actually asked for. fn sidebar_settle( container: gpui::Pixels, last_container: gpui::Pixels, sizes_0: gpui::Pixels, last_size: gpui::Pixels, ) -> SidebarSettle { if container != last_container { SidebarSettle::Resize } else if sizes_0 != last_size { SidebarSettle::Adopt } else { SidebarSettle::Settled } } impl Workspace { /// Puts the sidebar back at its width after a window resize, and takes the /// width a drag has left it at. fn settle_sidebar(&self, window: &mut Window, cx: &mut Context) { if self.sidebar_hidden { return; } let (target, last_container, last_size) = ( self.sidebar_width.get(), self.sidebar_container.get(), self.sidebar_last_size.get(), ); self.shell_split.update(cx, |state, cx| { let container = state.container_size(); if container <= px(1.) || state.sizes().len() != 2 { return; } match sidebar_settle(container, last_container, state.sizes()[0], last_size) { SidebarSettle::Resize => { self.sidebar_container.set(container); if (state.sizes()[0] - target).abs() > px(0.5) { state.resize_panel(0, target, window, cx); } self.sidebar_last_size.set(state.sizes()[0]); } SidebarSettle::Adopt => { self.sidebar_width.set(state.sizes()[0]); self.sidebar_last_size.set(state.sizes()[0]); } SidebarSettle::Settled => {} } }); } /// The surface under the titlebar, with the settings panel docked beside /// it while open. Beside rather than over: the surface narrows, so a /// setting is changed with what it changes still in view. The sidebar /// keeps its width through that: its panel is `flex_none`, so the content /// beside it is what gives way, and `settle_sidebar` puts it back at /// `sidebar_width` if a squeeze ever moved it, and on a window too narrow /// for both what does not fit is cut off rather than drawn under the /// panel's frost. fn beside_settings(&self, surface: AnyElement, cx: &mut Context) -> AnyElement { div() .flex_1() .min_h_0() .flex() .child( div() .flex_1() .min_w_0() .h_full() .overflow_hidden() .child(surface), ) .children(self.settings_open.then(|| render_settings_panel(self, cx))) .into_any_element() } /// The agent mark for a titlebar, or nothing while no bridge runs, so a /// window with agent access off draws exactly what it always did. Every /// titlebar asks for it, so no surface hides an agent that is attached. fn render_agent_mark(&self, cx: &mut Context) -> Option { let t = *theme(cx); let mark = self.agent_mark_state()?; // Snapshotted before the closure, as the mode pill's `silenced` is: // the menu is built when it opens, from what was drawn. let waiting = self.agent.calls.len(); // On a wrapper: `dropdown_menu` wraps the button, so a margin on the // button never reaches the titlebar's row. Some( div() .child(ui::agent_mark(t, mark).dropdown_menu(move |menu, _, _| { // The kill switch is the first item that can be selected, so // the keyboard reaches it with one step. The mark is drawn // only while access is on, so turning access on is the // palette's; the item after it reads what agents did. menu.label(match waiting { 0 => "No calls waiting".to_string(), 1 => "1 call waiting for you".to_string(), n => format!("{n} calls waiting for you"), }) .label("Agent access is on") .menu( "Disconnect agents and turn access off", Box::new(DisconnectAgents), ) .menu("Agent activity", Box::new(ShowAgentActivity)) })) .into_any_element(), ) } } /// One line of the agent call log, newest at the top of the menu: how long ago, /// the tool, the connection, and how the call ended. A name the agent gave that /// resolved nothing is quoted as asked for, so its words never read as a /// connection of DBDelve's. fn agent_log_label(entry: &agent::LogEntry, now: u64) -> String { let age = ui::relative_age(now.saturating_sub(entry.at) / 1000); let mut line = format!("{age} ago \u{b7} {}", entry.tool.name()); match (&entry.resolved, &entry.asked) { (Some(name), _) => line.push_str(&format!(" \u{b7} {name}")), (None, Some(asked)) => line.push_str(&format!(" \u{b7} asked for \"{asked}\"")), (None, None) => {} } line.push_str(&format!(" \u{b7} {}", entry.status.as_str())); if entry.requester_gone { line.push_str(" \u{b7} no requester"); } if entry.decision == Some(agent::Decision::Approved) { line.push_str(" \u{b7} approved"); } line } impl Workspace { fn dismiss_cleanup_notice( &mut self, _: &gpui::ClickEvent, window: &mut Window, cx: &mut Context, ) { if self.cleanup_notices.is_empty() { return; } self.cleanup_notices.remove(0); // A mouse click too: a button never takes focus on mouse-down, so one // tabbed to earlier still holds it as the notice unmounts. if self.cleanup_notices.is_empty() { self.focus.focus(window, cx); self.refocus_front(); } cx.notify(); } fn render_cleanup_notice(&self, t: Theme, cx: &mut Context) -> Option { let result = self.cleanup_notices.first()?; let profile = result.profile.as_deref().map_or_else( || "Profile: AWS CLI configuration".to_string(), |profile| format!("Configured profile: {profile}"), ); let profile_selector = format!("cleanup-profile: {profile}"); let region = result.region.as_deref().unwrap_or("AWS CLI configuration"); let session = result.session.clone(); let remaining = self.cleanup_notices.len().saturating_sub(1); Some( div() .flex_shrink_0() .w_full() .px(px(layout::SPACE_MD)) .py(px(layout::SPACE_SM)) .border_b_1() .border_color(t.border) .flex() .flex_col() .gap(px(layout::SPACE_XS)) .text_size(px(layout::chrome(layout::TEXT_SM))) .text_color(t.text_muted) .child("AWS session termination could not be confirmed. Check the session in AWS.") .child( div() .debug_selector(move || profile_selector.clone()) .child(format!( "{profile} · Region: {region} (account and effective region unverified)" )), ) .child(session.as_ref().map_or_else( || "Session ID unavailable".to_string(), |id| format!("Session ID: {id}"), )) .child( div() .flex() .flex_wrap() .items_center() .gap(px(layout::SPACE_SM)) .children(session.map(|id| { div() .rounded(px(layout::RADIUS_CONTROL)) .border_1() .border_color(t.border) .bg(t.element_active) .child( ui::button( ("cleanup-copy", 0usize), "Copy session ID", Tone::Primary, Control::Compact, t, ) .debug_selector(|| "cleanup-copy-0".to_string()) .on_click(cx.listener( move |_, _, _, cx| { cx.write_to_clipboard(ClipboardItem::new_string( id.clone(), )) }, )), ) })) .child( div() .rounded(px(layout::RADIUS_CONTROL)) .border_1() .border_color(t.border) .bg(t.element_active) .child( ui::button( ("cleanup-dismiss", 0usize), "Dismiss", Tone::Primary, Control::Compact, t, ) .debug_selector(|| "cleanup-dismiss-0".to_string()) .on_click(cx.listener(Self::dismiss_cleanup_notice)), ), ) .when(remaining > 0, |row| row.child(format!("{remaining} more"))), ), ) } } impl Render for Workspace { fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let t = *theme(cx); let imports_rows = self.profile().is_some_and(|profile| { profile .session .active_object() .is_some_and(|tab| tab.takes_imports(profile.config.target())) }); if imports_rows != self.menu_imports_rows { self.menu_imports_rows = imports_rows; cx.set_menus(crate::app_menus(imports_rows)); } let edited = self .profiles .iter() .any(|profile| profile.session.queries.iter().any(|tab| tab.dirty)); if edited != self.window_edited { self.window_edited = edited; window.set_window_edited(edited); } self.track_shown_diagram(cx); self.settle_sidebar(window, cx); self.reveal_landed_column(window, cx); if !self.row_panel.on_screen.get() { self.row_panel.revealed.take(); } self.row_panel.on_screen.set(false); self.row_panel.searched.set(false); // The name field is the welcome surface's, and whatever replaces that // surface ends here, so this is the one place it is put away -- // before the focus handoff below. if self.profile().is_some() || self.form.is_some() { self.drop_project_name(); } // Every way the connection form opens ends here too. Its branch below // returns before painting the panel, so one left open would come back // when the form closes, a capture in progress still listening. // Dropped rather than closed: the form takes the keyboard. if self.form.is_some() && self.settings_open { self.drop_settings(window, cx); } // All three deferred to render for the `&mut Window` a background task // does not have: a connect finds the picked database gone, the // catalog that names these tabs resolves, off-thread, and neither a // tab can be closed nor a grid built without a window, and a row send // that landed releases the action it was sent for. self.leave_database_left_behind(window, cx); self.restore_objects(window, cx); self.resume_released(window, cx); self.sync_page_input(window, cx); self.sync_row_panel_filter(window, cx); self.sync_row_panel_inputs(window, cx); self.sync_import_sql(window, cx); // Where a query tab that reached the front without `activate_tab` gets // its snapshot read. `session.active` is written in three places -- // `Session::new`, `activate_tab` and `escape` -- and the first and last // set a `Tab::Query` without hydrating it, so this cannot be narrowed // to the opening tab. // // What keeps it off a live result is `hydrate_tab`'s own `Idle` guard, // which holds only because no reachable state leaves a query tab // `Idle` while its grid holds rows: a run blanks the grid before it // starts, and nothing sets `Idle` back afterwards. A "clear results" // or a cancel that resets state would break that, and this line would // then read a snapshot over rows the user is looking at. // // Gated on a flag rather than on the disk, so every later frame is a // bool test. if let Some(active @ Tab::Query(_)) = self.profile().map(|profile| profile.session.active) { self.hydrate_tab(active, window, cx); } // Here for the reason the snapshot is read here: a tab reaches the // front along more paths than `activate_tab`. let front = self.profile().and_then(|profile| { let id = profile.session.active_query_tab()?.id; Some((profile.id.as_str(), id)) }); if front != self .file_looked_at .as_ref() .map(|(profile, id)| (profile.as_str(), *id)) { self.file_looked_at = front.map(|(profile, id)| (profile.to_string(), id)); self.check_front_file(window, cx); } // Deferred for the same reason plus one: an element has to be mounted // before it can take focus. // // Never while the form is up, which is drawn in the tab's place: the // form's field is focused first, and the tab's focus after it would // take it -- which is what closing the palette asks for just before a // row of it opens the form. The ask waits for the form to close. let form_open = self.form.is_some(); let front_chip = self.front_chip(); let take_focus = self.profile_mut().and_then(|profile| { if form_open { return None; } if !profile.session.editor_needs_focus { return None; } // The chip for whatever just took focus glides into view beside // it, one-shot the same way: a tab just opened or activated off // screen is a tab the strip should show, not one it leaves the // user to go scroll for. if let Some(index) = front_chip { crate::scroller::scroll_to("tab-strip", "", index, cx); } // Whatever the surface in front is: a keystroke reaches the // workspace along the focused element's dispatch path, so a // surface with nothing focused makes every keybinding dead. let focus = match profile.session.active { // Under the import dialog, which only stops the mouse: a // buffer or grid holding focus there would take keys for a // surface nobody can see. _ if profile.session.import_rows.is_some() => Focus::Window, // No tab at all is still a surface: the window holds focus // for the bindings that open one. Tab::Query(id) => match profile.session.query_tab(id) { Some(tab) => Focus::Buffer(tab.editor.clone()), None => Focus::Window, }, Tab::Object(id) => match profile .session .objects .iter() .find(|tab| tab.id == id) .map(|tab| &tab.body) { Some(ObjectBody::Relation { results, .. }) => Focus::Grid(results.clone()), Some(ObjectBody::Structure { grid, .. }) => Focus::Structure(grid.clone()), Some(ObjectBody::Diagram { view, .. }) => { Focus::Diagram(view.read(cx).focus_handle().clone()) } // A routine's tab is read: nothing in it takes a // keystroke. The window still has to hold focus, or the // bindings that leave this tab go with it -- as it does // for the last object tab of all, closed. Some(ObjectBody::Routine(_)) | None => Focus::Window, }, }; profile.session.editor_needs_focus = false; Some(focus) }); // Before the tab's own focus, and separately: the form is a surface of // its own, and a field it just unmounted took the window's only // dispatch path with it. if let Some(input) = self.form.as_mut().and_then(|form| form.needs_focus.take()) { input.focus_handle(cx).focus(window, cx); } // Asked for by name rather than read off what holds focus: that is // checked against the last frame, where the field that just closed // still sat inside this same floor. if self.form.is_none() && self.profile().is_none() && std::mem::take(&mut self.welcome_needs_focus) { self.welcome_url.focus_handle(cx).focus(window, cx); } if std::mem::take(&mut self.custom_limit_needs_focus) && let Some((_, input)) = &self.custom_limit { input.focus_handle(cx).focus(window, cx); } if std::mem::take(&mut self.project_name_needs_focus) && let Some(input) = &self.project_name { input.focus_handle(cx).focus(window, cx); } match take_focus { Some(Focus::Buffer(editor)) => editor.focus_handle(cx).focus(window, cx), Some(Focus::Grid(grid)) => grid.focus_handle(cx).focus(window, cx), Some(Focus::Structure(grid)) => grid.focus_handle(cx).focus(window, cx), Some(Focus::Diagram(handle)) => handle.focus(window, cx), Some(Focus::Window) => self.focus.focus(window, cx), None => {} } // After the tab's own focus, which a context menu closing over the // sidebar can ask for in the same frame the row's field opens. if let Some(profile) = self.profile_mut() && std::mem::take(&mut profile.session.query_rename_needs_focus) && let Some(rename) = &profile.session.query_rename { let input = rename.input.clone(); input.focus_handle(cx).focus(window, cx); input.update(cx, |input, cx| input.select_all(window, cx)); } if std::mem::take(&mut self.settings_search_needs_focus) && self.settings_open { self.settings_search.focus_handle(cx).focus(window, cx); } // Last, and unconditionally: the palette is modal, and it holds the // keyboard against anything above that just claimed it. One a modal // cannot be typed into is one that cannot be dismissed either. if let Some(palette) = &self.palette { let handle = palette.focus_handle(cx); if !handle.is_focused(window) { handle.focus(window, cx); } } if let Some(form) = &mut self.form { // Opened from the welcome surface, whose contours are already up. form.backdrop_shown |= self.welcome_entrance.is_some(); form.sync_placeholders(window, cx); } if self.form.is_some() || self.profile().is_some() { self.welcome_entrance = None; } else { self.begin_welcome(cx); } if self.form.is_some() { return div() .id("connection-form") .size_full() // The floor under the focus, the same one the workspace root // has: without it the form's bindings dispatch nowhere the // moment no field holds focus. .track_focus(&self.focus) .key_context("ConnectionForm") // Chrome, so the form's card is the raised plane on it. .text_color(t.text) .text_size(px(layout::chrome(layout::TEXT_MD))) .flex() .flex_col() .on_action(cx.listener(Self::select_theme)) .on_action(cx.listener(Self::show_editor)) .on_action(cx.listener(Self::submit_connection)) .on_action(cx.listener(Self::disconnect_agents_action)) .on_action(cx.listener(Self::show_agent_activity_action)) .on_action(cx.listener(Self::next_profile)) .on_action(cx.listener(Self::zoom_editor_in)) .on_action(cx.listener(Self::zoom_editor_out)) .on_action(cx.listener(Self::reset_editor_zoom)) .on_action(cx.listener(Self::previous_profile)) .on_action(cx.listener(Self::open_logs_folder)) .on_action(cx.listener(Self::copy_diagnostics)) // Without a titlebar of its own the form has no drag handle at // all, since the platform's is transparent. .child(titlebar( t, None, self.render_agent_mark(cx).into_iter().collect(), Vec::new(), Vec::new(), )) .children(self.render_cleanup_notice(t, cx)) .child( div() .flex_1() .min_h_0() .child(self.render_connection_form(window, cx)), ) .children(self.dialog_layer( [ // First, so it is drawn behind every other dialog: an // agent's unsolicited approval never covers one the user // is already answering. ("agent-approval", self.render_agent_approval(cx)), ("agent-audit", self.render_agent_audit(cx)), ("import-choice", self.render_import_choice(cx)), ("stable-import", self.render_stable_import(cx)), ], window, cx, )) .children(self.palette.clone()); } let Some(profile) = self.profile() else { return div() .id("welcome") // A data file dropped anywhere on the window opens in DuckDB. .on_drop(cx.listener(Self::drop_files)) .size_full() .track_focus(&self.focus) .text_color(t.text) .text_size(px(layout::chrome(layout::TEXT_MD))) .flex() .flex_col() .on_action(cx.listener(Self::select_theme)) .on_action(cx.listener(Self::show_editor)) .on_action(cx.listener(Self::open_connection_form)) .on_action(cx.listener(Self::disconnect_agents_action)) .on_action(cx.listener(Self::show_agent_activity_action)) .on_action(cx.listener(Self::new_project)) .on_action(cx.listener(Self::import_from)) .on_action(cx.listener(Self::open_settings)) .on_action(cx.listener(Self::open_logs_folder)) .on_action(cx.listener(Self::copy_diagnostics)) .on_action(cx.listener(Self::fuzzy_open)) .on_action(cx.listener(Self::command_palette)) .on_action(cx.listener(Self::search_everything)) .on_action(cx.listener(Self::switch_connection)) .on_action(cx.listener(Self::set_default_row_limit_action)) .on_action(cx.listener(Self::custom_row_limit)) .on_action(cx.listener(Self::zoom_editor_in)) .on_action(cx.listener(Self::zoom_editor_out)) .on_action(cx.listener(Self::reset_editor_zoom)) .child(titlebar( t, None, self.render_agent_mark(cx) .into_iter() .chain(self.render_update_pill(cx)) .collect(), Vec::new(), Vec::new(), )) .children(self.render_cleanup_notice(t, cx)) .children(self.render_queries_notice(t, cx)) .child(self.beside_settings(self.render_welcome(window, cx).into_any_element(), cx)) .children(self.dialog_layer( [ // Home lists the connections, so an agent's call on a // visible one and the visibility dialog its row opens // both arrive here as well as in front of a profile. ("agent-approval", self.render_agent_approval(cx)), ("agent-audit", self.render_agent_audit(cx)), ("agent-visibility", self.render_agent_visibility(cx)), ("import-choice", self.render_import_choice(cx)), ("stable-import", self.render_stable_import(cx)), ], window, cx, )) .children(self.palette.clone()); }; let failed = matches!(profile.state, ProfileState::Failed(_)); let status = match &profile.state { ProfileState::Idle => "Connection is idle.".to_string(), ProfileState::Connecting { .. } => { format!("Connecting to {}…", profile.config.endpoint()) } // Connected is the one state worth spending on decoration: every // other one is news, and news beats where the connection points. // Its name is already on the switcher in the titlebar. ProfileState::Connected(_) => { match profile.config.server().map(|server| &server.database) { Some(database) if !database.is_empty() => { format!("{} / {database}", profile.config.endpoint()) } _ => profile.config.endpoint(), } } // Postgres puts its DETAIL and HINT on lines of their own. ProfileState::Failed(message) => one_line(message), }; // The rows the grid actually holds, which is fewer than the result had // whenever a restored snapshot was capped. let showing = profile .session .active_results() .map(|results| results.read(cx).delegate().result().rows.len()); let stopped = profile .session .active_results() .and_then(|results| results.read(cx).delegate().result().stopped); let column_count = profile .session .active_results() .map(|results| results.read(cx).delegate().columns().len()); let snapshot_age = profile .session .active_results() .and_then(|results| results.read(cx).delegate().captured()) .map(|captured| relative_age(store::captured_at().saturating_sub(captured))); let stale_buffer = snapshot_age.is_some() && matches!(profile.session.active, Tab::Query(_)); // Only with the statement to show: a snapshot older than `last_query` // would have the prompt's Refresh run whatever the cursor is on. And // only a read, since a write restored from the last session would // write again. let refreshable_snapshot = stale_buffer && profile.session.active_query_tab().is_some_and(|tab| { tab.last_query .as_deref() .is_some_and(|sql| sql::rerunnable(profile.config.engine(), sql)) }); // A query tab's own slot rather than the result in front: a queue run // in turn can be showing a statement that finished while the next one // runs. Run at once, the slot only holds the run open, and each // statement streams into its own entry, so the one in front is read. let running = match profile.session.active_query_tab() { Some(tab) if tab.queue.as_ref().is_some_and(|queue| queue.at_once()) => { let (state, results) = tab.shown(); views::render_running(state, Some(results), cx) } Some(tab) => views::render_running(&tab.query, Some(&tab.results), cx), None => profile.session.active_query().and_then(|query| { views::render_running(query, profile.session.active_results(), cx) }), }; let paging = running.or_else(|| views::render_paging(profile, self.custom_limit.as_ref(), cx)); let view_sorting = views::render_view_sorting(profile, cx); let edit_mode = views::render_edit_mode(profile, cx); let apply_label = views::apply_label(views::view_edit_mode(profile)); let transaction = views::render_transaction(profile, cx); let hidden_columns = views::render_hidden_columns(profile, cx); let relation = profile .session .active_object() .and_then(|tab| match &tab.body { ObjectBody::Relation { count, filter, query, limit, offset, .. } => Some((tab, count, filter, query, *limit, *offset)), _ => None, }); let engine = profile.config.engine(); let relation_rows = relation.and_then(|(tab, count, filter, query, limit, offset)| { // Read from the catalog of the database the tab is on, which may // hold a relation of the same name with other numbers. let own = profile.active_database(); let database = tab .database .as_deref() .filter(|database| own.as_deref() != Some(*database)); let estimate = profile .catalog_of(database) .and_then(|catalog| catalog_relation(catalog, &tab.schema, &tab.name)) .and_then(|relation| relation.rows); let whole = offset == 0 && matches!( query, QueryState::Complete { rows, .. } if limit.is_none_or(|limit| *rows < limit) ); session::relation_rows( count, filter, estimate, profile.config.target().exact_row_estimates(), whole, ) }); // The way to an exact number, which is never run unasked. Its tooltip // is the statement it runs. let count_control = relation .filter(|_| profile.connection().is_some()) .and_then(|(tab, count, filter, ..)| { let id = tab.id; let workspace = cx.entity().downgrade(); match count { RowCount::Counting { cancelling, .. } => Some( div() .flex_shrink_0() .flex() .items_center() .gap(px(layout::SPACE_SM)) .child(div().whitespace_nowrap().text_color(t.text_faint).child( match cancelling { true => "Cancelling count…", false => "Counting rows…", }, )) .children((!cancelling).then(|| { button("cancel-count", "Cancel", Tone::Quiet, Control::Compact, t) .on_click(move |_, _, cx| { _ = workspace.update(cx, |workspace, cx| { workspace.cancel_count(id, cx); }); }) })) .into_any_element(), ), _ if count.answers(filter) => None, _ => { let sql = explorer::count_sql(engine, &tab.schema, &tab.name, filter); Some( button("count-rows", "Count", Tone::Quiet, Control::Compact, t) .tooltip(sql) .on_click(move |_, _, cx| { _ = workspace.update(cx, |workspace, cx| { workspace.count_rows(id, cx); }); }) .into_any_element(), ) } } }); // Read off the writer's counter, on the half-second tick its start set // going: the rows go to the file, never through anything that redraws. let export_status = profile.session.exporting.as_ref().map(|exporting| { let cancelling = exporting .progress .cancelled .load(std::sync::atomic::Ordering::Relaxed); let rows = exporting .progress .rows .load(std::sync::atomic::Ordering::Relaxed); let workspace = cx.entity().downgrade(); div() .flex_shrink_0() .flex() .items_center() .gap(px(layout::SPACE_SM)) .child(div().whitespace_nowrap().text_color(t.text_faint).child( match cancelling { true => format!("Cancelling the export to {}…", exporting.file), false => format!( "Exporting to {}… {} {}", exporting.file, group_thousands(rows as u64), if rows == 1 { "row" } else { "rows" } ), }, )) .children((!cancelling).then(|| { button("cancel-export", "Cancel", Tone::Quiet, Control::Compact, t) .on_click(move |_, _, cx| { _ = workspace .update(cx, |workspace, cx| workspace.cancel_export(cx)); }) })) }); let query_status = match profile.session.active_query() { Some(QueryState::Complete { rows, bytes, elapsed, .. }) => { // The rows on screen, unless the relation's own count or // estimate is beside the stats already. let count = relation_rows.is_none().then(|| { let count = row_readout(showing.unwrap_or(*rows), *rows); match stopped { Some(db::Stopped::Cancelled) => format!("{count}, cancelled"), Some(db::Stopped::AtLimit) => format!("{count}, stopped at limit"), None => count, } }); let joined = |rest: String| match count { Some(count) => format!("{count} \u{b7} {rest}"), None => rest, }; // A snapshot knows neither how many bytes crossed the wire nor // how long it took, so reporting `0 B · 0.0ns` invents two // numbers. What it does know is when it was taken. // A relation refreshes its own snapshot as soon as it can. A // buffer's statement is the user's to run again, and nothing // else would tell them the rows are waiting on it. Some(match snapshot_age { Some(age) if stale_buffer => joined(format!("from {age} ago")), Some(age) => joined(format!("snapshot from {age} ago")), None => joined(format!( "{} \u{b7} {elapsed:.1?}", human_bytes(*bytes as u64) )), }) } // The plan's own rows are not this tab's result and never reached // the grid, so the count beside them still belongs to whatever ran // last. What the run itself is worth saying is how long the server // spent answering. Some(QueryState::Explained { elapsed, mode, .. }) => { Some(format!("{} · {elapsed:.1?}", mode.label())) } _ => None, }; let left_stats = [ relation_rows, column_count.filter(|columns| *columns > 0).map(|columns| { format!( "{columns} {}", if columns == 1 { "column" } else { "columns" } ) }), ] .into_iter() .flatten() .collect::>(); let left_stats = (!left_stats.is_empty()).then(|| left_stats.join(" \u{b7} ")); // The dot carries the state and the text carries the words. A whole // status line in green shouts about being connected, which is the // least interesting thing dbdelve can tell you. let status_group = div() .flex() .items_center() .gap(px(layout::SPACE_SM)) .min_w_0() .child(ui::status_dot(t, &profile.state)) .child( div() .min_w_0() .overflow_hidden() .text_ellipsis() .whitespace_nowrap() .text_color(if failed { t.danger } else { t.text_muted }) .child(status), ) .when(failed, |group| { group.child( div() .flex_shrink_0() .child(ui::reconnect_button("reconnect", t)), ) }); let (sidebar_status, inline_status) = if self.sidebar_hidden { (None, Some(status_group)) } else { (Some(status_group), None) }; let notice = profile.session.shown_notice().map(str::to_string); let update_pill = self.render_update_pill(cx); let pending_count = self.pending_edit_count(cx); let pending_noun = match (self.draft_holds_rows(cx), pending_count) { (false, 1) => "edit", (false, _) => "edits", (true, 1) => "change", (true, _) => "changes", }; let has_pending = pending_count > 0; let has_results = self.has_results(cx); let show_result_actions = has_results && !has_pending; // Its menu dispatches into the grid, the context `cmd-v` is bound in. let import_menu = profile .session .active_object() .filter(|tab| !has_pending && tab.takes_imports(profile.config.target())) .and_then(|tab| match &tab.body { ObjectBody::Relation { results, .. } => Some(results.focus_handle(cx)), _ => None, }); // A structure tab's in place of the rows' copy and export: the // relation's own definition, and a statement to fill it with. let structure_copies = profile.session.active_object().and_then(|tab| { let ObjectBody::Structure { structure, .. } = &tab.body else { return None; }; let Some(ObjectKind::Relation(kind)) = tab.kind else { return None; }; let connected = matches!(profile.state, ProfileState::Connected(_)); let insert = engine.syntax() == db::Syntax::Sql && matches!(structure, StructureState::Loaded(loaded) if !loaded.columns.is_empty()); Some(( connected.then(|| (tab.schema.clone(), tab.name.clone(), kind, tab.database.clone())), insert, )) }); let apply_workspace = cx.entity().downgrade(); let discard_workspace = apply_workspace.clone(); let previous_workspace = apply_workspace.clone(); let next_workspace = apply_workspace.clone(); let copy_menu_workspace = apply_workspace.clone(); let refresh_workspace = apply_workspace.clone(); let ddl_workspace = apply_workspace.clone(); let insert_workspace = apply_workspace.clone(); // Chrome for content, not a fixture of the window: with no tab open // every field below is empty, and an empty bar is a background and a // hairline with nothing on either side of them. let bar_has_content = inline_status.is_some() || left_stats.is_some() || count_control.is_some() || export_status.is_some() || paging.is_some() || view_sorting.is_some() || edit_mode.is_some() || transaction.is_some() || hidden_columns.is_some() || query_status.is_some() || refreshable_snapshot || has_results || structure_copies.is_some() || has_pending; // On a line of its own above the bar, free to wrap, so no width cuts it // and the bar keeps its room for what a keystroke will do. let notice_line = notice.map(|notice| { div() .id("status-notice") .debug_selector(|| "status-notice".into()) .flex_shrink_0() .min_w_0() .border_t_1() .border_color(t.border) .text_size(px(layout::chrome(layout::TEXT_SM))) .px(px(layout::SPACE_MD)) .py(px(layout::SPACE_XS)) .bg(t.data_glass()) .text_color(t.text_muted) .child(one_line(¬ice)) }); let status_bar = bar_has_content.then(|| { div() .debug_selector(|| "status-bar".into()) .h(px(layout::chrome(layout::STATUS_HEIGHT))) .flex_shrink_0() .border_t_1() .border_color(t.border) .text_size(px(layout::chrome(layout::TEXT_SM))) .min_w_0() .flex() .items_center() .gap(px(layout::SPACE_SM)) .px(px(layout::SPACE_MD)) .bg(t.data_glass()) .children(inline_status) // What a keystroke will do to the database, kept whole outside // the side that gives way, so the bar cuts the Sort menu first. .children(edit_mode) // Clips what it has no room for, so it never draws over what // follows it. .child( div() .debug_selector(|| "status-left".into()) .flex_1() .min_w_0() .overflow_hidden() .flex() .items_center() .gap(px(layout::SPACE_SM)) .children(transaction) .children(view_sorting) .children(hidden_columns) .children(left_stats.map(|stats| { div() .flex_shrink_0() .whitespace_nowrap() .text_color(t.text_faint) .child(stats) })) .children(count_control) .children(export_status), ) // Between two sides that share the free space equally, so // it sits at the middle of the bar whatever either holds. .children(paging) // One right-hand cluster taking the other half of that // space, so the readout stays against the edge. // // Each control appears only when it does something. A pair // of buttons that do nothing is a pair to read past -- // see `apply_edits` for its `cmd+s` binding. .child( div() .flex_1() .min_w_0() .justify_end() .flex() .items_center() .gap(px(layout::SPACE_SM)) .children(query_status.map(|query_status| { div() .text_color(match stale_buffer { true => t.text_muted, false => t.text_faint, }) .child(query_status) })) // Through the stale-rows prompt rather than straight // to a run, so the statement is read before it is // sent. .children(refreshable_snapshot.then(|| { button( "refresh-snapshot", "Refresh…", Tone::Quiet, Control::Compact, t, ) .on_click(move |_, _, cx| { _ = refresh_workspace.update(cx, |workspace, cx| { workspace.ask_refresh_stale(cx); }); }) })) .children(import_menu.map(|grid| { button("import-rows", "Import", Tone::Quiet, Control::Compact, t) .debug_selector(|| "import-rows".into()) .child( icon(icon::CHEVRON_DOWN) .size(px(layout::chrome(layout::ICON_SIZE))) .text_color(t.text_faint), ) .dropdown_menu(move |menu, _, _| { menu.action_context(grid.clone()) .menu("From Clipboard", Box::new(ImportRowsFromClipboard)) .menu("From File…", Box::new(ImportRows)) }) })) // Not beside pending edits: these write the rows as // fetched, not the values on screen, and the review // controls need the room. .children(show_result_actions.then(|| { let export = ExportMenu { workspace: copy_menu_workspace.clone(), sql: engine.syntax() == db::Syntax::Sql, }; button("export-results", "Export", Tone::Quiet, Control::Compact, t) .debug_selector(|| "export-results".into()) .child( icon(icon::CHEVRON_DOWN) .size(px(layout::chrome(layout::ICON_SIZE))) .text_color(t.text_faint), ) .dropdown_menu(move |menu, window, cx| { export.build(menu, window, cx) }) })) .children(structure_copies.map(|(ddl, insert)| { div() .flex() .items_center() .gap(px(layout::SPACE_SM)) .children(ddl.map(|(schema, relation, kind, database)| { button( "copy-create", "Copy CREATE", Tone::Quiet, Control::Compact, t, ) .on_click( move |_, _, cx| { let (schema, relation, database) = ( schema.clone(), relation.clone(), database.clone(), ); _ = ddl_workspace.update(cx, |workspace, cx| { workspace .copy_ddl(database, schema, relation, kind, cx); }); }, ) })) .children(insert.then(|| { button( "copy-insert", "Copy INSERT", Tone::Quiet, Control::Compact, t, ) .on_click( move |_, _, cx| { _ = insert_workspace.update(cx, |workspace, cx| { workspace.copy_insert_template(cx); }); }, ) })) })) // A tinted cell scrolled out of view is an edit // nobody knows is about to be written. .children(has_pending.then(|| { let label = div() .min_w_0() .overflow_hidden() .text_ellipsis() .whitespace_nowrap() .text_color(t.text_muted) .child(format!("{pending_count} pending {pending_noun}")); div() .min_w_0() .flex() .items_center() .child( icon_button( "previous-edit", icon::CHEVRON_LEFT, Tone::Quiet, Control::Compact, t, ) .tooltip("Previous edit") .on_click( move |_, window, cx| { _ = previous_workspace.update(cx, |workspace, cx| { workspace.previous_edit(&PreviousEdit, window, cx); }); }, ), ) .child(label) .child( icon_button( "next-edit", icon::CHEVRON_RIGHT, Tone::Quiet, Control::Compact, t, ) .tooltip("Next edit") .on_click( move |_, window, cx| { _ = next_workspace.update(cx, |workspace, cx| { workspace.next_edit(&NextEdit, window, cx); }); }, ), ) .into_any_element() })), ) // Against the edge and never narrowed: a full bar takes its // room from the status and the two sides above before it // reaches the buttons that apply or drop the pending edits. .children(has_pending.then(|| { div() .debug_selector(|| "status-pending".into()) .flex_shrink_0() .flex() .items_center() .gap(px(layout::SPACE_SM)) .child( button("discard-edits", "Discard", Tone::Quiet, Control::Compact, t) .debug_selector(|| "discard-edits".into()) .on_click(move |_, window, cx| { _ = discard_workspace.update(cx, |workspace, cx| { workspace.discard_edits(&DiscardEdits, window, cx); }); }), ) .child( button( "apply-edits", apply_label, Tone::Primary, Control::Compact, t, ) .debug_selector(|| "apply-edits".into()) .on_click(move |_, window, cx| { _ = apply_workspace.update(cx, |workspace, cx| { workspace.apply_edits(&ApplyEdits, window, cx); }); }), ) })) }); let results_status = (status_bar.is_some() || notice_line.is_some()).then(|| { div() .flex_shrink_0() .min_w_0() .flex() .flex_col() .children(notice_line) .children(status_bar) }); let content = div() // Flush, not a floating card: the split handle already draws the // one seam, and the planes inside separate by tone. .size_full() .min_w_0() .flex() .flex_col() .child(div().flex_1().min_h_0().child(views::render_main_content( profile, &self.profiles, self.view_mode(), self.settings.color_titlebar, self.editor_size(), (self.chrome_zoom, self.editor_zoom, self.grid_zoom), &self.row_panel, self.plan_copied, &self.tab_strip, self.custom_limit.as_ref(), &self.settings.custom_keybindings, cx, ))) .children(results_status); // Only now, with the frame built, is it known whether the panel's // field went away -- folded, closed, or emptied by a run -- and the // handoff above has already run, so it lands on the next frame. if !self.row_panel.searched.get() && (self.row_panel.search.focus_handle(cx).is_focused(window) || self.row_input_focused(window, cx)) { cx.defer_in(window, |workspace, _, cx| { workspace.refocus_front(); cx.notify(); }); } // The strip's chips glide for as long as the render above found one // still on its way. self.tab_strip.shift.drive(window); // With the sidebar folded there is nothing to split, and a split with // one panel still paints the handle it no longer divides anything with. let main_pane = if self.sidebar_hidden { content.into_any_element() } else { h_resizable("workspace-shell-split") .with_state(&self.shell_split) .child( resizable_panel() .size(px(layout::SIDEBAR_DEFAULT_WIDTH)) .flex_none() .size_range(px(layout::SIDEBAR_MIN_WIDTH)..px(layout::SIDEBAR_MAX_WIDTH)) .child( div() .size_full() .flex() .flex_col() .child(div().flex_1().min_h_0().child(match self.view_mode() { ViewMode::Complex => { self.render_connections(cx).into_any_element() } ViewMode::Simple => { self.render_explorer(profile, cx).into_any_element() } })) .child( div() .h(px(layout::chrome(layout::STATUS_HEIGHT))) .flex_shrink_0() .flex() .items_center() .px(px(layout::SPACE_MD)) .border_t_1() .border_color(t.border) .text_size(px(layout::chrome(layout::TEXT_SM))) .overflow_hidden() .children(sidebar_status), ), ), ) .child(resizable_panel().child(content)) .into_any_element() }; div() .id("workspace") .key_context("Workspace") // A data file dropped anywhere on the window opens in DuckDB. .on_drop(cx.listener(Self::drop_files)) .relative() // The floor under the focus, so a surface with nothing focusable // on it still has a dispatch path for the workspace's own // bindings. An inner element that can take focus claims it first // and stops this one from taking it back. .track_focus(&self.focus) .on_action(cx.listener(Self::choose_mode)) .on_action(cx.listener(Self::reset_confirmations)) .on_action(cx.listener(Self::set_default_row_limit_action)) .on_action(cx.listener(Self::refresh_connection)) .on_action(cx.listener(Self::import_rows)) .on_action(cx.listener(Self::import_rows_from_clipboard)) .on_action( cx.listener(|workspace, _: &MenuImportRowsFromClipboard, window, cx| { workspace.import_rows_from_clipboard(&ImportRowsFromClipboard, window, cx) }), ) .on_action(cx.listener(Self::show_editor)) .on_action(cx.listener(Self::select_theme)) .on_action(cx.listener(Self::select_database)) .on_action(cx.listener(Self::new_query)) .on_action(cx.listener(Self::next_profile)) .on_action(cx.listener(Self::previous_profile)) .on_action(cx.listener(Self::next_tab)) .on_action(cx.listener(Self::previous_tab)) .on_action(cx.listener(Self::move_tab_left)) .on_action(cx.listener(Self::move_tab_right)) .on_action(cx.listener(Self::open_connection_form)) .on_action(cx.listener(Self::new_project)) .on_action(cx.listener(Self::import_from)) .on_action(cx.listener(Self::zoom_editor_in)) .on_action(cx.listener(Self::zoom_editor_out)) .on_action(cx.listener(Self::reset_editor_zoom)) .on_action(cx.listener(Self::fuzzy_open)) .on_action(cx.listener(Self::command_palette)) .on_action(cx.listener(Self::search_everything)) .on_action(cx.listener(Self::cycle_mode)) .on_action(cx.listener(Self::toggle_auto_commit)) .on_action(cx.listener(Self::commit_transaction)) .on_action(cx.listener(Self::rollback_transaction)) .on_action(cx.listener(Self::switch_connection)) .on_action(cx.listener(Self::disconnect)) .on_action(cx.listener(Self::toggle_sidebar)) .on_action(cx.listener(Self::disconnect_agents_action)) .on_action(cx.listener(Self::show_agent_activity_action)) .on_action(cx.listener(Self::focus_sidebar)) .on_action(cx.listener(Self::collapse_all_schemas)) .on_action(cx.listener(Self::expand_all_schemas)) .on_action(cx.listener(Self::open_settings)) .on_action(cx.listener(Self::open_logs_folder)) .on_action(cx.listener(Self::copy_diagnostics)) .on_action(cx.listener(Self::open_sql_files_action)) // Unregistered under the import dialog, which stops only the // mouse: these act on the tab it covers, out of sight, and their // menu items grey out with them. .when(profile.session.import_rows.is_none(), |root| { root.on_action(cx.listener(Self::run_query)) .on_action(cx.listener(Self::explain_query)) .on_action(cx.listener(Self::format_query)) .on_action(cx.listener(Self::toggle_comment)) .on_action(cx.listener(Self::cancel_query)) .on_action(cx.listener(Self::apply_edits)) .on_action(cx.listener(Self::discard_edits)) .on_action(cx.listener(Self::next_edit)) .on_action(cx.listener(Self::previous_edit)) .on_action(cx.listener(Self::sort_column)) .on_action(cx.listener(Self::sort_active_column)) .on_action(cx.listener(Self::next_result)) .on_action(cx.listener(Self::previous_result)) .on_action(cx.listener(Self::toggle_messages)) .on_action(cx.listener(Self::copy_plan_action)) .on_action(cx.listener(Self::set_row_limit)) .on_action(cx.listener(Self::set_query_limit)) .on_action(cx.listener(Self::pick_edit_mode)) .on_action(cx.listener(Self::custom_row_limit)) .on_action(cx.listener(Self::refresh_active_relation)) .on_action(cx.listener(Self::next_page)) .on_action(cx.listener(Self::previous_page)) .on_action(cx.listener(Self::clear_filter)) .on_action(cx.listener(Self::add_filter)) .on_action(cx.listener(Self::remove_filter)) .on_action(cx.listener(Self::set_filter_column)) .on_action(cx.listener(Self::set_filter_raw)) .on_action(cx.listener(Self::set_filter_operator)) .on_action(cx.listener(Self::toggle_filter_join)) .on_action(cx.listener(Self::toggle_next_join)) .on_action(cx.listener(Self::new_row)) .on_action(cx.listener(Self::save_query)) .on_action(cx.listener(Self::save_query_as)) .on_action(cx.listener(Self::close_tab)) .on_action(cx.listener(Self::close_all_tabs)) .on_action(cx.listener(Self::go_to_column)) .on_action(cx.listener(Self::toggle_results)) .on_action(cx.listener(Self::toggle_row_panel)) .on_action(cx.listener(Self::toggle_row_edit)) .on_action(cx.listener(Self::toggle_structure)) .on_action(cx.listener(Self::toggle_results_focus)) }) .size_full() // The shell is the frost: titlebar, sidebar and status bar paint // nothing of their own, they are the glass the window root already // laid down. The editor and the results step forward from it by // tone, and by letting less of the desktop through. .text_color(t.text) .text_size(px(layout::chrome(layout::TEXT_MD))) .flex() .flex_col() .child(titlebar( t, profile.color.filter(|_| self.settings.color_titlebar), std::iter::once({ let mode = profile.mode; let silenced = profile .confirmed .iter() .map(|kind| kind.label()) .chain(profile.confirmed_stale.then_some("stale rows")) .collect::>(); ui::mode_pill(t, mode) .dropdown_menu(move |menu, _, _| { let menu = Mode::ALL.into_iter().fold(menu, |menu, option| { menu.menu_with_check( option.label(), option == mode, Box::new(SetMode { mode: option }), ) }); // Absent unless this connection has actually // silenced something: suppression is per // connection, so the way back out belongs on the // connection, and one it never asked to reset is // one entry with nothing to do. if silenced.is_empty() { menu } else { menu.separator().menu( format!( "Reset silenced confirmations ({})", silenced.join(", ") ), Box::new(ResetConfirmations), ) } }) .into_any_element() }) .chain(self.render_agent_mark(cx)) .chain(update_pill) .collect(), [ icon_button( "toggle-sidebar", icon::SIDEBAR, Tone::Quiet, Control::Compact, t, ) .on_click(cx.listener(|workspace, _, window, cx| { workspace.toggle_sidebar(&ToggleSidebar, window, cx); })) .into_any_element(), self.render_connection_name(cx), ] .into_iter() .chain(self.render_breadcrumb(cx)) .collect(), vec![ icon_button( "open-settings", icon::SETTINGS, Tone::Quiet, Control::Compact, t, ) .tooltip("Settings") .on_click(|_, window, cx| { window.dispatch_action(Box::new(OpenSettings), cx); }) .into_any_element(), ], )) .children(self.render_cleanup_notice(t, cx)) .children(self.render_queries_notice(t, cx)) .child(self.beside_settings(main_pane, cx)) .children(self.dialog_layer( [ // First, so it is drawn behind every other dialog: an // agent's unsolicited approval never covers one the user is // already answering, and `escape` reaches it last. ("agent-approval", self.render_agent_approval(cx)), ("agent-audit", self.render_agent_audit(cx)), ("show-ddl", self.render_show_ddl(cx)), ("apply-review", self.render_apply_review(cx)), ("import-rows", self.render_import_rows(window, cx)), ("delete", self.render_delete_confirmation(cx)), ("discard", self.render_discard_confirmation(cx)), ("unsaved", self.render_unsaved_confirmation(cx)), ("overwrite", self.render_overwrite_confirmation(cx)), ("forget-file", self.render_forget_file(cx)), ("schema-export", self.render_schema_export(cx)), ("agent-visibility", self.render_agent_visibility(cx)), ("pending-export", self.render_pending_export(cx)), ("pending-run", self.render_pending_run(cx)), ("queue-failure", self.render_queue_failure(cx)), ("stale-edit", self.render_stale_edit(cx)), ("import-choice", self.render_import_choice(cx)), ("stable-import", self.render_stable_import(cx)), ], window, cx, )) .children(self.palette.clone()) .children(self.render_reference_popup(cx)) } } /// What the `Show DDL` dialog shows, and which object it was asked about: the /// answer lands only while the view still names the same request. pub(crate) struct DdlView { /// The connection the object belongs to, by id; of several, the one acted /// on last. pub(crate) profile: String, pub(crate) name: String, /// One definition for one object, one per object for several. pub(crate) sections: Vec, pub(crate) request: u64, } impl DdlView { /// What the dialog's header says: the object's, or how many it lists. pub(crate) fn heading(&self) -> String { match self.sections.as_slice() { [only] => only.title.clone(), sections => format!("{} definitions", sections.len()), } } } /// One object's definition in the dialog, under its name. pub(crate) struct DdlSection { pub(crate) title: String, pub(crate) text: DdlText, } /// The definition as the dialog has it. pub(crate) enum DdlText { Loading, /// Empty when the server returned no definition. Ready(String), Failed(String), } /// A relation a reference arrow lists, by its index into the structure's /// `referenced_by`: a row was found in it, or its check failed with this error. pub(crate) type ReferenceAnswer = (usize, gpui::SharedString, Result<(), String>); /// The key a reference lookup was asked about: its profile, its tab, its column and value, /// and the references its structure listed, which an answer's indices point /// into. An answer or a pick is acted on only while the grid in front still /// says the same, so neither can land on another tab, key or refreshed /// structure. #[derive(Clone, PartialEq)] pub(crate) struct ReferenceSource { // Tab ids count from zero in every profile, so the tab alone does not say // which connection was asked. profile: String, tab: u64, column: String, value: String, referenced_by: Vec, } /// What a reference arrow opened: where it hangs, and the relations that turned /// out to hold rows for the key, or whose check failed with the error it gave. /// `None` while the lookup is still out. pub(crate) struct ReferencePopup { /// `None` when the keyboard asked, which puts the answer in the palette. pub(crate) at: Option>, pub(crate) source: ReferenceSource, pub(crate) choices: Option>, check: u64, } pub(crate) const EDITOR_FONT_SIZE_DEFAULT: f32 = 14.0; pub(crate) const EDITOR_FONT_SIZE_MIN: f32 = 11.0; pub(crate) const EDITOR_FONT_SIZE_MAX: f32 = 24.0; pub(crate) const FONT_SIZE_STEP: f32 = 1.0; /// Blocking work -- anything that talks to a connection, the network, the /// disk or the Keychain -- on `blocking`'s pool, for the background executor /// to await. It never runs on the executor's own threads: there are only as /// many as cores, and one statement draining on a session with the rest queued /// behind it on the same session's lock would hold every one of them, stalling /// everything else spawned there. /// /// The pool is capped, so calls parked on a busy session cannot start threads /// without end, and a call dropped before a thread takes it never runs. A /// Cancel goes through [`spawn_cancel`] instead, since a full pool would queue /// it behind the very statements it is there to stop. pub(crate) fn spawn_blocking( executor: &gpui::BackgroundExecutor, work: impl FnOnce() -> T + Send + 'static, ) -> gpui::Task { // GPUI's deterministic test scheduler runs every task on the test's own // thread and fails a test woken from any other, so the end-to-end tests // get the work inline, as one blocking task at a time. if executor.is_test() { return executor.spawn(async move { work() }); } executor.spawn(blocking::unblock(work)) } /// A Cancel, on a thread of its own started at once rather than on /// [`spawn_blocking`]'s pool, which the statements it cancels may be filling. /// Where the OS will not start a thread, it runs on the reserve one /// ([`reserve_cancel_thread`]), and only where that never started either does /// it wait its turn on the pool. pub(crate) fn spawn_cancel(executor: &gpui::BackgroundExecutor, work: F) -> gpui::Task where T: Send + 'static, F: FnOnce() -> T + Send + 'static, { spawn_cancel_starting(executor, work, start_cancel_thread) } type CancelJob = Box; fn spawn_cancel_starting( executor: &gpui::BackgroundExecutor, work: F, start: fn(CancelJob) -> Result<(), CancelJob>, ) -> gpui::Task where T: Send + 'static, F: FnOnce() -> T + Send + 'static, { if executor.is_test() { return executor.spawn(async move { work() }); } let reserve = reserve_cancel_thread(); let (sender, receiver) = tokio::sync::oneshot::channel(); let job: CancelJob = Box::new(move || _ = sender.send(work())); if let Err(job) = start(job) && let Err(job) = match reserve { Some(reserve) => reserve .send(job) .map_err(|std::sync::mpsc::SendError(job)| job), None => Err(job), } { spawn_blocking(executor, job).detach(); } executor.spawn(async move { // Dropped unsent only by a panic running it, which is a panic here. receiver .await .expect("the thread running a Cancel panicked") }) } /// The one long-lived thread a Cancel runs on when the OS will not start a /// fresh one, started by the first Cancel so it already exists by the time /// threads run out. Cancels that land on it run one after another. fn reserve_cancel_thread() -> Option> { static RESERVE: std::sync::Mutex>> = std::sync::Mutex::new(None); let mut reserve = RESERVE .lock() .unwrap_or_else(std::sync::PoisonError::into_inner); if reserve.is_none() { let (sender, jobs) = std::sync::mpsc::channel::(); *reserve = std::thread::Builder::new() .name("dbdelve-cancel-reserve".to_owned()) .spawn(move || { for job in jobs { // A panicking Cancel drops its answer unsent, which its // awaiting task reports; the thread stays for the next. _ = std::panic::catch_unwind(std::panic::AssertUnwindSafe(job)); } }) .ok() .map(|_| sender); } reserve.clone() } /// `job` on a fresh thread, or back if the OS will not start one. fn start_cancel_thread(job: CancelJob) -> Result<(), CancelJob> { let (hand_over, take) = std::sync::mpsc::channel::(); // A thread that did not start dropped `take` with it, so the send fails // and hands `job` back. _ = std::thread::Builder::new() .name("dbdelve-cancel".to_owned()) .spawn(move || { if let Ok(job) = take.recv() { job(); } }); hand_over .send(job) .map_err(|std::sync::mpsc::SendError(job)| job) } /// The range the controls offer for a slot, and where Reset puts it. The /// chrome stops at 17 because the titlebar does not grow with it: the window /// buttons are placed against it once, when the window opens, and past 17 the /// controls in it would touch its edges. pub(crate) fn font_size_range(slot: FontSlot) -> (f32, f32, f32) { match slot { FontSlot::Chrome => (11.0, layout::BODY_FONT_SIZE, 17.0), FontSlot::Editor => ( EDITOR_FONT_SIZE_MIN, EDITOR_FONT_SIZE_DEFAULT, EDITOR_FONT_SIZE_MAX, ), FontSlot::Grid => (10.0, layout::BODY_FONT_SIZE, 20.0), } } pub(crate) fn adjusted_font_size(slot: FontSlot, current: f32, delta: f32) -> f32 { let (min, _, max) = font_size_range(slot); (current + delta).clamp(min, max) } /// A size read back from disk. Clamped rather than trusted, because /// `profiles.toml` is a text file: a size outside the range the controls offer /// would otherwise be unreachable by the controls that set it. The finiteness /// check is not decoration -- `clamp` on a NaN returns the NaN. pub(crate) fn restored_font_size(slot: FontSlot, stored: Option) -> f32 { let (min, default, max) = font_size_range(slot); stored .filter(|size| size.is_finite()) .map(|size| size.clamp(min, max)) .unwrap_or(default) } /// The steps a browser zooms through, so ⌘+ and ⌘− land where people expect. pub(crate) const ZOOM_LEVELS: [u32; 11] = [50, 67, 75, 80, 90, 100, 110, 125, 150, 175, 200]; /// The next level in or out from `current`, or `current` itself at either end. pub(crate) fn stepped_zoom(current: u32, zoom_in: bool) -> u32 { let next = if zoom_in { ZOOM_LEVELS.into_iter().find(|&level| level > current) } else { ZOOM_LEVELS.into_iter().rev().find(|&level| level < current) }; next.unwrap_or(current) } pub(crate) fn zoomed(size: f32, percent: u32) -> f32 { size * percent as f32 / 100.0 } pub(crate) fn adjusted_opacity(current: f32, delta: f32) -> f32 { (current + delta).clamp(theme::OPACITY_MIN, theme::OPACITY_MAX) } /// An opacity read back from disk, clamped for the same reason the zoom is: /// `profiles.toml` is a text file, and a value outside the range the controls /// offer is one they cannot walk back. NaN would survive the `clamp`. pub(crate) fn restored_opacity(stored: Option) -> f32 { stored .filter(|opacity| opacity.is_finite()) .map(|opacity| opacity.clamp(theme::OPACITY_MIN, theme::OPACITY_MAX)) .unwrap_or(theme::OPACITY_DEFAULT) } pub(crate) fn opacity_percent(opacity: f32) -> u32 { (opacity * 100.0).round() as u32 } /// A percentage someone typed, back into the fraction the theme wants. /// /// Out of range is clamped rather than refused -- the field is a shortcut past /// the `−` and `+` buttons, and those clamp too. Anything that is not a number /// at all, the empty field included, leaves the setting where it was; so does /// an infinity, which parses happily and would survive `clamp`. /// /// The number already on screen is returned as the very f32 it came from /// rather than recomputed: stepping lands on values like 0.77000004, whose /// percentage divides back to a different f32, and `set_opacity` would take /// that for a change and rewrite `profiles.toml`. pub(crate) fn opacity_from_percent_input(typed: &str, current: f32) -> f32 { let Ok(percent) = typed.trim().trim_end_matches('%').trim().parse::() else { return current; }; if !percent.is_finite() || percent.round() == opacity_percent(current) as f32 { return current; } (percent / 100.0).clamp(theme::OPACITY_MIN, theme::OPACITY_MAX) } /// Through the platform's quit, as Quit goes, so buffers and profiles are /// written on the way out exactly as they are then. fn restart_into(installed: std::path::PathBuf, cx: &mut App) { update::before_restart(); cx.set_restart_path(installed); cx.restart(); } #[cfg(test)] mod tests { use std::time::Duration; use super::*; use crate::db::{CancelToken, Fetch}; /// What `task` came to, awaited from the executor as the workspace awaits /// one, or None when it came to nothing within `limit`. fn landed( executor: &gpui::BackgroundExecutor, task: gpui::Task, limit: Duration, ) -> Option { let (sender, receiver) = std::sync::mpsc::channel(); executor .spawn(async move { _ = sender.send(task.await) }) .detach(); receiver.recv_timeout(limit).ok() } /// `blocking`'s cap when `BLOCKING_MAX_THREADS` does not set one. const BLOCKING_POOL_CAP: usize = 500; /// More statements than either `ThreadedDispatcher`'s pool or /// `blocking`'s, one running and the rest queued behind it on the same /// session, then a Cancel, on a thread of its own and where the OS refuses /// one. #[test] fn statements_parked_on_one_connection_leave_the_background_executor_free() { let refused: fn(CancelJob) -> Result<(), CancelJob> = Err; for start in [start_cancel_thread, refused] { cancel_behind_parked_statements(start); } } fn cancel_behind_parked_statements(start: fn(CancelJob) -> Result<(), CancelJob>) { let executor = gpui::BackgroundExecutor::new(Arc::new(gpui::ThreadedDispatcher::new())); let cores = std::thread::available_parallelism().map_or(2, |cores| cores.get().max(2)); let pool = BLOCKING_POOL_CAP + cores; let connection = db::Connection::open(db::ConnectionConfig::External(db::ExternalConfig { plugin: db::echo::plugin(), speaks: db::Engine::Postgres, connection: "DSN=echo".to_owned(), user: String::new(), password: String::new(), statement_timeout: 0, ssm: None, ssh: None, })) .unwrap(); let run = CancelToken::default(); let sleep = spawn_blocking(&executor, { let (connection, run) = (connection.clone(), run.clone()); move || connection.query("sleep 60000", &run, Fetch::default()) }); std::thread::sleep(Duration::from_millis(200)); let queued: Vec<_> = (1..pool) .map(|_| { let connection = connection.clone(); spawn_blocking(&executor, move || { connection.query("rows 1", &CancelToken::default(), Fetch::default()) }) }) .collect(); std::thread::sleep(Duration::from_millis(200)); let timer = executor.timer(Duration::from_millis(10)); assert!( landed(&executor, timer, Duration::from_secs(1)).is_some(), "a timer did not fire while {pool} statements were parked on one connection" ); let cancel = spawn_cancel_starting( &executor, { let connection = connection.clone(); move || connection.cancel(&run) }, start, ); let cancelled = landed(&executor, cancel, Duration::from_secs(2)); assert!( matches!(cancelled, Some(Ok(()))), "the Cancel did not land behind {pool} parked statements" ); let slept = landed(&executor, sleep, Duration::from_secs(5)).expect("the sleep ended"); let error = slept.expect_err("the sleep was cancelled"); assert!(error.message.starts_with("Cancelled"), "{}", error.message); for statement in queued { let ran = landed(&executor, statement, Duration::from_secs(5)); assert!(matches!(ran, Some(Ok(_))), "a queued statement did not run"); } } #[test] fn a_window_too_narrow_to_hold_the_sidebar_does_not_relabel_the_squeeze() { // 400 wanted, container only leaves room for 350: Resize, not Adopt, // even though the achieved size differs from what was asked for. assert_eq!( sidebar_settle(px(450.), px(1200.), px(350.), px(400.)), SidebarSettle::Resize ); // Settled at the squeezed width: another frame at the same container // size must leave the remembered target alone. assert_eq!( sidebar_settle(px(450.), px(450.), px(350.), px(350.)), SidebarSettle::Settled ); // Widening back out is another container change, so the target gets // another chance to apply in full. assert_eq!( sidebar_settle(px(1200.), px(450.), px(350.), px(350.)), SidebarSettle::Resize ); } #[test] fn a_drag_at_a_fixed_container_size_is_adopted() { assert_eq!( sidebar_settle(px(1200.), px(1200.), px(300.), px(400.)), SidebarSettle::Adopt ); } #[test] fn a_font_size_stays_inside_its_slots_range() { for slot in [FontSlot::Chrome, FontSlot::Editor, FontSlot::Grid] { let (min, default, max) = font_size_range(slot); assert_eq!(adjusted_font_size(slot, max, FONT_SIZE_STEP), max); assert_eq!(adjusted_font_size(slot, min, -FONT_SIZE_STEP), min); assert_eq!( adjusted_font_size(slot, default, FONT_SIZE_STEP), default + FONT_SIZE_STEP ); } } #[test] fn a_restored_font_size_is_clamped_rather_than_trusted() { // `profiles.toml` is a text file. A size outside the range the controls // offer would be one the controls cannot undo, and a NaN would survive // `clamp` and reach the text system. for slot in [FontSlot::Chrome, FontSlot::Editor, FontSlot::Grid] { let (min, default, max) = font_size_range(slot); assert_eq!(restored_font_size(slot, None), default); assert_eq!(restored_font_size(slot, Some(f32::NAN)), default); assert_eq!(restored_font_size(slot, Some(f32::INFINITY)), default); assert_eq!(restored_font_size(slot, Some(900.0)), max); assert_eq!(restored_font_size(slot, Some(0.0)), min); assert_eq!( restored_font_size(slot, Some(default + FONT_SIZE_STEP)), default + FONT_SIZE_STEP ); } } #[test] fn opacity_is_stored_per_theme() { let [first, second, ..] = Theme::all()[..] else { unreachable!() }; let mut settings = Settings::default(); settings.set_opacity_for(&first, 0.9); assert_eq!(settings.opacity_for(&first), 0.9); assert_eq!(settings.opacity_for(&second), settings.opacity); settings.set_opacity_for(&second, 0.6); assert_eq!(settings.opacity_for(&first), 0.9); assert_eq!(settings.opacity_for(&second), 0.6); } #[test] fn matching_the_system_wears_the_theme_picked_for_its_side() { use theme::Appearance::{Dark, Light}; let mut settings = Settings::default(); settings.set_theme_for(Light, "GitHub Light"); settings.set_theme_for(Dark, "Dracula"); let worn = |settings: &Settings, side| settings.system_theme(side).map(|theme| theme.name); assert_eq!(worn(&settings, Light), Some("GitHub Light")); assert_eq!(worn(&settings, Dark), Some("Dracula")); settings.set_theme_for(Dark, "Deleted Since"); assert_eq!(worn(&settings, Dark), Some("DBDelve Black")); settings.match_system_appearance = false; assert!(settings.system_theme(Dark).is_none()); } #[test] fn a_list_that_outlived_a_change_to_matching_still_takes_effect() { use theme::Appearance::{Dark, Light}; let mut settings = Settings { match_system_appearance: false, ..Settings::default() }; assert_eq!(settings.list_side(Some(Dark), Light), None); assert_eq!(settings.pick_target(Some(Dark), Light), (Some(Dark), true)); assert_eq!(settings.pick_target(None, Light), (None, true)); settings.match_system_appearance = true; assert_eq!(settings.list_side(None, Light), Some(Light)); assert_eq!(settings.list_side(Some(Dark), Light), Some(Dark)); assert_eq!(settings.pick_target(None, Light), (Some(Light), true)); assert_eq!(settings.pick_target(Some(Dark), Light), (Some(Dark), false)); assert_eq!( settings.pick_target(Some(Light), Light), (Some(Light), true) ); } #[test] fn light_glass_without_an_entry_starts_at_its_default_not_the_shared_fallback() { let settings = Settings { opacity: 0.6, ..Settings::default() }; let light = Theme::all() .into_iter() .find(|t| t.is_glass && t.appearance == theme::Appearance::Light) .unwrap(); assert_eq!(settings.opacity_for(&light), 0.79); assert_eq!(settings.opacity_for(&Theme::glass()), 0.6); let mut settings = settings; settings.set_opacity_for(&light, 0.5); assert_eq!(settings.opacity_for(&light), 0.5); } #[test] fn a_restored_opacity_is_clamped_rather_than_trusted() { assert_eq!(restored_opacity(None), theme::OPACITY_DEFAULT); assert_eq!(restored_opacity(Some(f32::NAN)), theme::OPACITY_DEFAULT); assert_eq!(restored_opacity(Some(2.0)), theme::OPACITY_MAX); assert_eq!(restored_opacity(Some(-1.0)), theme::OPACITY_MIN); assert_eq!(restored_opacity(Some(0.8)), 0.8); } #[test] fn a_typed_opacity_is_clamped_rather_than_refused() { assert_eq!(opacity_from_percent_input("80", 0.72), 0.8); assert_eq!(opacity_from_percent_input("85%", 0.72), 0.85); assert_eq!(opacity_from_percent_input(" 85 % ", 0.72), 0.85); assert_eq!(opacity_from_percent_input("120", 0.72), theme::OPACITY_MAX); assert_eq!(opacity_from_percent_input("10", 0.72), theme::OPACITY_MIN); // Nothing to read is not a reason to change anything. assert_eq!(opacity_from_percent_input("", 0.72), 0.72); assert_eq!(opacity_from_percent_input("dark", 0.72), 0.72); assert_eq!(opacity_from_percent_input("inf", 0.72), 0.72); // Retyping what the readout says must be the same f32 it was showing, // not the one the division would have produced. let stepped = adjusted_opacity(theme::OPACITY_DEFAULT, theme::OPACITY_STEP); assert_eq!( opacity_from_percent_input(&opacity_percent(stepped).to_string(), stepped), stepped ); } #[test] fn zoom_steps_through_the_levels_and_stops_at_either_end() { assert_eq!(stepped_zoom(100, true), 110); assert_eq!(stepped_zoom(100, false), 90); assert_eq!(stepped_zoom(200, true), 200); assert_eq!(stepped_zoom(50, false), 50); let mut zoom = 50; for level in ZOOM_LEVELS.into_iter().skip(1) { zoom = stepped_zoom(zoom, true); assert_eq!(zoom, level); } } }