workspace_settings.rs

  1use std::num::NonZeroUsize;
  2
  3use crate::DockPosition;
  4use anyhow::Result;
  5use collections::HashMap;
  6use gpui::App;
  7use schemars::JsonSchema;
  8use serde::{Deserialize, Serialize};
  9use settings::{Settings, SettingsSources, SettingsUi};
 10
 11#[derive(Deserialize, SettingsUi)]
 12pub struct WorkspaceSettings {
 13    pub active_pane_modifiers: ActivePanelModifiers,
 14    pub bottom_dock_layout: BottomDockLayout,
 15    pub pane_split_direction_horizontal: PaneSplitDirectionHorizontal,
 16    pub pane_split_direction_vertical: PaneSplitDirectionVertical,
 17    pub centered_layout: CenteredLayoutSettings,
 18    pub confirm_quit: bool,
 19    pub show_call_status_icon: bool,
 20    pub autosave: AutosaveSetting,
 21    pub restore_on_startup: RestoreOnStartupBehavior,
 22    pub restore_on_file_reopen: bool,
 23    pub drop_target_size: f32,
 24    pub use_system_path_prompts: bool,
 25    pub use_system_prompts: bool,
 26    pub command_aliases: HashMap<String, String>,
 27    pub max_tabs: Option<NonZeroUsize>,
 28    pub when_closing_with_no_tabs: CloseWindowWhenNoItems,
 29    pub on_last_window_closed: OnLastWindowClosed,
 30    pub resize_all_panels_in_dock: Vec<DockPosition>,
 31    pub close_on_file_delete: bool,
 32    pub use_system_window_tabs: bool,
 33    pub zoomed_padding: bool,
 34}
 35
 36#[derive(Copy, Clone, Default, Serialize, Deserialize, JsonSchema)]
 37#[serde(rename_all = "snake_case")]
 38pub enum OnLastWindowClosed {
 39    /// Match platform conventions by default, so don't quit on macOS, and quit on other platforms
 40    #[default]
 41    PlatformDefault,
 42    /// Quit the application the last window is closed
 43    QuitApp,
 44}
 45
 46impl OnLastWindowClosed {
 47    pub fn is_quit_app(&self) -> bool {
 48        match self {
 49            OnLastWindowClosed::PlatformDefault => false,
 50            OnLastWindowClosed::QuitApp => true,
 51        }
 52    }
 53}
 54
 55#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, JsonSchema)]
 56#[serde(rename_all = "snake_case")]
 57pub struct ActivePanelModifiers {
 58    /// Size of the border surrounding the active pane.
 59    /// When set to 0, the active pane doesn't have any border.
 60    /// The border is drawn inset.
 61    ///
 62    /// Default: `0.0`
 63    pub border_size: Option<f32>,
 64    /// Opacity of inactive panels.
 65    /// When set to 1.0, the inactive panes have the same opacity as the active one.
 66    /// If set to 0, the inactive panes content will not be visible at all.
 67    /// Values are clamped to the [0.0, 1.0] range.
 68    ///
 69    /// Default: `1.0`
 70    pub inactive_opacity: Option<f32>,
 71}
 72
 73#[derive(Copy, Clone, Debug, Default, Serialize, Deserialize, PartialEq, JsonSchema)]
 74#[serde(rename_all = "snake_case")]
 75pub enum BottomDockLayout {
 76    /// Contained between the left and right docks
 77    #[default]
 78    Contained,
 79    /// Takes up the full width of the window
 80    Full,
 81    /// Extends under the left dock while snapping to the right dock
 82    LeftAligned,
 83    /// Extends under the right dock while snapping to the left dock
 84    RightAligned,
 85}
 86
 87#[derive(Copy, Clone, Default, Serialize, Deserialize, JsonSchema)]
 88#[serde(rename_all = "snake_case")]
 89pub enum CloseWindowWhenNoItems {
 90    /// Match platform conventions by default, so "on" on macOS and "off" everywhere else
 91    #[default]
 92    PlatformDefault,
 93    /// Close the window when there are no tabs
 94    CloseWindow,
 95    /// Leave the window open when there are no tabs
 96    KeepWindowOpen,
 97}
 98
 99impl CloseWindowWhenNoItems {
100    pub fn should_close(&self) -> bool {
101        match self {
102            CloseWindowWhenNoItems::PlatformDefault => cfg!(target_os = "macos"),
103            CloseWindowWhenNoItems::CloseWindow => true,
104            CloseWindowWhenNoItems::KeepWindowOpen => false,
105        }
106    }
107}
108
109#[derive(Copy, Clone, PartialEq, Eq, Default, Serialize, Deserialize, JsonSchema)]
110#[serde(rename_all = "snake_case")]
111pub enum RestoreOnStartupBehavior {
112    /// Always start with an empty editor
113    None,
114    /// Restore the workspace that was closed last.
115    LastWorkspace,
116    /// Restore all workspaces that were open when quitting Zed.
117    #[default]
118    LastSession,
119}
120
121#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
122pub struct WorkspaceSettingsContent {
123    /// Active pane styling settings.
124    pub active_pane_modifiers: Option<ActivePanelModifiers>,
125    /// Layout mode for the bottom dock
126    ///
127    /// Default: contained
128    pub bottom_dock_layout: Option<BottomDockLayout>,
129    /// Direction to split horizontally.
130    ///
131    /// Default: "up"
132    pub pane_split_direction_horizontal: Option<PaneSplitDirectionHorizontal>,
133    /// Direction to split vertically.
134    ///
135    /// Default: "left"
136    pub pane_split_direction_vertical: Option<PaneSplitDirectionVertical>,
137    /// Centered layout related settings.
138    pub centered_layout: Option<CenteredLayoutSettings>,
139    /// Whether or not to prompt the user to confirm before closing the application.
140    ///
141    /// Default: false
142    pub confirm_quit: Option<bool>,
143    /// Whether or not to show the call status icon in the status bar.
144    ///
145    /// Default: true
146    pub show_call_status_icon: Option<bool>,
147    /// When to automatically save edited buffers.
148    ///
149    /// Default: off
150    pub autosave: Option<AutosaveSetting>,
151    /// Controls previous session restoration in freshly launched Zed instance.
152    /// Values: none, last_workspace, last_session
153    /// Default: last_session
154    pub restore_on_startup: Option<RestoreOnStartupBehavior>,
155    /// Whether to attempt to restore previous file's state when opening it again.
156    /// The state is stored per pane.
157    /// When disabled, defaults are applied instead of the state restoration.
158    ///
159    /// E.g. for editors, selections, folds and scroll positions are restored, if the same file is closed and, later, opened again in the same pane.
160    /// When disabled, a single selection in the very beginning of the file, zero scroll position and no folds state is used as a default.
161    ///
162    /// Default: true
163    pub restore_on_file_reopen: Option<bool>,
164    /// The size of the workspace split drop targets on the outer edges.
165    /// Given as a fraction that will be multiplied by the smaller dimension of the workspace.
166    ///
167    /// Default: `0.2` (20% of the smaller dimension of the workspace)
168    pub drop_target_size: Option<f32>,
169    /// Whether to close the window when using 'close active item' on a workspace with no tabs
170    ///
171    /// Default: auto ("on" on macOS, "off" otherwise)
172    pub when_closing_with_no_tabs: Option<CloseWindowWhenNoItems>,
173    /// Whether to use the system provided dialogs for Open and Save As.
174    /// When set to false, Zed will use the built-in keyboard-first pickers.
175    ///
176    /// Default: true
177    pub use_system_path_prompts: Option<bool>,
178    /// Whether to use the system provided prompts.
179    /// When set to false, Zed will use the built-in prompts.
180    /// Note that this setting has no effect on Linux, where Zed will always
181    /// use the built-in prompts.
182    ///
183    /// Default: true
184    pub use_system_prompts: Option<bool>,
185    /// Aliases for the command palette. When you type a key in this map,
186    /// it will be assumed to equal the value.
187    ///
188    /// Default: true
189    pub command_aliases: Option<HashMap<String, String>>,
190    /// Maximum open tabs in a pane. Will not close an unsaved
191    /// tab. Set to `None` for unlimited tabs.
192    ///
193    /// Default: none
194    pub max_tabs: Option<NonZeroUsize>,
195    /// What to do when the last window is closed
196    ///
197    /// Default: auto (nothing on macOS, "app quit" otherwise)
198    pub on_last_window_closed: Option<OnLastWindowClosed>,
199    /// Whether to resize all the panels in a dock when resizing the dock.
200    ///
201    /// Default: ["left"]
202    pub resize_all_panels_in_dock: Option<Vec<DockPosition>>,
203    /// Whether to automatically close files that have been deleted on disk.
204    ///
205    /// Default: false
206    pub close_on_file_delete: Option<bool>,
207    /// Whether to allow windows to tab together based on the user’s tabbing preference (macOS only).
208    ///
209    /// Default: false
210    pub use_system_window_tabs: Option<bool>,
211    /// Whether to show padding for zoomed panels.
212    /// When enabled, zoomed bottom panels will have some top padding,
213    /// while zoomed left/right panels will have padding to the right/left (respectively).
214    ///
215    /// Default: true
216    pub zoomed_padding: Option<bool>,
217}
218
219#[derive(Deserialize, SettingsUi)]
220pub struct TabBarSettings {
221    pub show: bool,
222    pub show_nav_history_buttons: bool,
223    pub show_tab_bar_buttons: bool,
224}
225
226#[derive(Clone, Default, Serialize, Deserialize, JsonSchema)]
227pub struct TabBarSettingsContent {
228    /// Whether or not to show the tab bar in the editor.
229    ///
230    /// Default: true
231    pub show: Option<bool>,
232    /// Whether or not to show the navigation history buttons in the tab bar.
233    ///
234    /// Default: true
235    pub show_nav_history_buttons: Option<bool>,
236    /// Whether or not to show the tab bar buttons.
237    ///
238    /// Default: true
239    pub show_tab_bar_buttons: Option<bool>,
240}
241
242#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
243#[serde(rename_all = "snake_case")]
244pub enum AutosaveSetting {
245    /// Disable autosave.
246    Off,
247    /// Save after inactivity period of `milliseconds`.
248    AfterDelay { milliseconds: u64 },
249    /// Autosave when focus changes.
250    OnFocusChange,
251    /// Autosave when the active window changes.
252    OnWindowChange,
253}
254
255#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
256#[serde(rename_all = "snake_case")]
257pub enum PaneSplitDirectionHorizontal {
258    Up,
259    Down,
260}
261
262#[derive(Copy, Clone, Debug, Serialize, Deserialize, PartialEq, Eq, JsonSchema)]
263#[serde(rename_all = "snake_case")]
264pub enum PaneSplitDirectionVertical {
265    Left,
266    Right,
267}
268
269#[derive(Copy, Clone, Debug, Serialize, Deserialize, JsonSchema)]
270#[serde(rename_all = "snake_case")]
271pub struct CenteredLayoutSettings {
272    /// The relative width of the left padding of the central pane from the
273    /// workspace when the centered layout is used.
274    ///
275    /// Default: 0.2
276    pub left_padding: Option<f32>,
277    // The relative width of the right padding of the central pane from the
278    // workspace when the centered layout is used.
279    ///
280    /// Default: 0.2
281    pub right_padding: Option<f32>,
282}
283
284impl Settings for WorkspaceSettings {
285    const KEY: Option<&'static str> = None;
286
287    type FileContent = WorkspaceSettingsContent;
288
289    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
290        sources.json_merge()
291    }
292
293    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
294        if vscode
295            .read_bool("accessibility.dimUnfocused.enabled")
296            .unwrap_or_default()
297            && let Some(opacity) = vscode
298                .read_value("accessibility.dimUnfocused.opacity")
299                .and_then(|v| v.as_f64())
300        {
301            if let Some(settings) = current.active_pane_modifiers.as_mut() {
302                settings.inactive_opacity = Some(opacity as f32)
303            } else {
304                current.active_pane_modifiers = Some(ActivePanelModifiers {
305                    inactive_opacity: Some(opacity as f32),
306                    ..Default::default()
307                })
308            }
309        }
310
311        vscode.enum_setting(
312            "window.confirmBeforeClose",
313            &mut current.confirm_quit,
314            |s| match s {
315                "always" | "keyboardOnly" => Some(true),
316                "never" => Some(false),
317                _ => None,
318            },
319        );
320
321        vscode.bool_setting(
322            "workbench.editor.restoreViewState",
323            &mut current.restore_on_file_reopen,
324        );
325
326        if let Some(b) = vscode.read_bool("window.closeWhenEmpty") {
327            current.when_closing_with_no_tabs = Some(if b {
328                CloseWindowWhenNoItems::CloseWindow
329            } else {
330                CloseWindowWhenNoItems::KeepWindowOpen
331            })
332        }
333
334        if let Some(b) = vscode.read_bool("files.simpleDialog.enable") {
335            current.use_system_path_prompts = Some(!b);
336        }
337
338        vscode.enum_setting("files.autoSave", &mut current.autosave, |s| match s {
339            "off" => Some(AutosaveSetting::Off),
340            "afterDelay" => Some(AutosaveSetting::AfterDelay {
341                milliseconds: vscode
342                    .read_value("files.autoSaveDelay")
343                    .and_then(|v| v.as_u64())
344                    .unwrap_or(1000),
345            }),
346            "onFocusChange" => Some(AutosaveSetting::OnFocusChange),
347            "onWindowChange" => Some(AutosaveSetting::OnWindowChange),
348            _ => None,
349        });
350
351        // workbench.editor.limit contains "enabled", "value", and "perEditorGroup"
352        // our semantics match if those are set to true, some N, and true respectively.
353        // we'll ignore "perEditorGroup" for now since we only support a global max
354        if let Some(n) = vscode
355            .read_value("workbench.editor.limit.value")
356            .and_then(|v| v.as_u64())
357            .and_then(|n| NonZeroUsize::new(n as usize))
358            && vscode
359                .read_bool("workbench.editor.limit.enabled")
360                .unwrap_or_default()
361        {
362            current.max_tabs = Some(n)
363        }
364
365        vscode.bool_setting("window.nativeTabs", &mut current.use_system_window_tabs);
366
367        // some combination of "window.restoreWindows" and "workbench.startupEditor" might
368        // map to our "restore_on_startup"
369
370        // there doesn't seem to be a way to read whether the bottom dock's "justified"
371        // setting is enabled in vscode. that'd be our equivalent to "bottom_dock_layout"
372    }
373}
374
375impl Settings for TabBarSettings {
376    const KEY: Option<&'static str> = Some("tab_bar");
377
378    type FileContent = TabBarSettingsContent;
379
380    fn load(sources: SettingsSources<Self::FileContent>, _: &mut App) -> Result<Self> {
381        sources.json_merge()
382    }
383
384    fn import_from_vscode(vscode: &settings::VsCodeSettings, current: &mut Self::FileContent) {
385        vscode.enum_setting(
386            "workbench.editor.showTabs",
387            &mut current.show,
388            |s| match s {
389                "multiple" => Some(true),
390                "single" | "none" => Some(false),
391                _ => None,
392            },
393        );
394        if Some("hidden") == vscode.read_string("workbench.editor.editorActionsLocation") {
395            current.show_tab_bar_buttons = Some(false)
396        }
397    }
398}