Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
cli: Always open new window when `cli_default_open_behavior=new_window` (#59415)
Bennet Bo Fennerdf33d7866100
diff --git a/assets/settings/default.json b/assets/settings/default.jsonindex c1ca00ee0ac..74560dd49bb 100644--- a/assets/settings/default.json+++ b/assets/settings/default.json@@ -162,8 +162,7 @@// May take 2 values:// 1. Open directories as a new workspace in the current Zed window's sidebar// "cli_default_open_behavior": "existing_window"- // 2. Open directories in a new window (reuse existing windows for files- // that are already part of an open project)+ // 2. Open paths in a new window, unless they are subpaths of an existing project// "cli_default_open_behavior": "new_window""cli_default_open_behavior": "existing_window",// The default behavior when opening projects from the UI.diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rsindex 0823f1fafee..d7ad0b347ed 100644--- a/crates/cli/src/cli.rs+++ b/crates/cli/src/cli.rs@@ -16,13 +16,14 @@ pub struct IpcHandshake {#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]#[serde(rename_all = "snake_case")]pub enum OpenBehavior {- /// Consult the user's `cli_default_open_behavior` setting to choose between- /// `ExistingWindow` or `Classic`.+ /// Consult the user's `cli_default_open_behavior` setting.#[default]Default,/// Always create a new window. No matching against existing worktrees./// Corresponds to `zed -n`.AlwaysNew,+ /// Create a new window unless opening a subpath of an existing project.+ PreferNewWindow,/// Match broadly including subdirectories, and fall back to any existing/// window if no worktree matched. Corresponds to `zed -a`.Add,@@ -47,9 +48,7 @@ pub enum OpenBehavior {pub enum CliBehaviorSetting {/// Open directories as a new workspace in the current Zed window's sidebar.ExistingWindow,- /// Classic behavior: open directories in a new window, but reuse an- /// existing window when opening files that are already part of an open- /// project.+ /// Open paths in a new window unless they are subpaths of an existing project.NewWindow,}diff --git a/crates/project/src/project.rs b/crates/project/src/project.rsindex 2864313d8d7..90b4a6a5997 100644--- a/crates/project/src/project.rs+++ b/crates/project/src/project.rs@@ -2535,6 +2535,30 @@ impl Project {.max()}+ pub fn visibility_for_subpaths(&self, paths: &[PathBuf], cx: &App) -> Option<bool> {+ paths+ .iter()+ .map(|path| self.visibility_for_subpath(path, cx))+ .max()+ .flatten()+ }++ fn visibility_for_subpath(&self, path: &Path, cx: &App) -> Option<bool> {+ let path = SanitizedPath::new(path).as_path();+ let path_style = self.path_style(cx);+ self.worktrees(cx)+ .filter_map(|worktree| {+ let worktree = worktree.read(cx);+ let abs_path = worktree.abs_path();+ let relative_path = path_style.strip_prefix(path, abs_path.as_ref());+ let is_subpath = relative_path+ .as_ref()+ .is_some_and(|p| !p.as_ref().as_unix_str().is_empty());+ is_subpath.then(|| worktree.is_visible())+ })+ .max()+ }+pub fn create_entry(&mut self,project_path: impl Into<ProjectPath>,diff --git a/crates/settings_content/src/workspace.rs b/crates/settings_content/src/workspace.rsindex 780fc1dc542..c52cda911d4 100644--- a/crates/settings_content/src/workspace.rs+++ b/crates/settings_content/src/workspace.rs@@ -408,8 +408,7 @@ pub enum CliDefaultOpenBehavior {#[default]#[strum(serialize = "Add to Existing Window")]ExistingWindow,- /// Open directories in a new window, but reuse an existing window when- /// opening files that are already part of an open project.+ /// Open paths in a new window unless they are subpaths of an existing project.#[strum(serialize = "Open a New Window")]NewWindow,}diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rsindex cef5ece31b0..161f65974c4 100644--- a/crates/workspace/src/workspace.rs+++ b/crates/workspace/src/workspace.rs@@ -9794,11 +9794,18 @@ pub async fn find_existing_workspace(if let Ok(multi_workspace) = window.read(cx) {for workspace in multi_workspace.workspaces() {let project = workspace.read(cx).project.read(cx);- let m = project.visibility_for_paths(- abs_paths,- open_options.workspace_matching != WorkspaceMatching::MatchSubdirectory,- cx,- );+ let m = match open_options.workspace_matching {+ WorkspaceMatching::None => None,+ WorkspaceMatching::MatchExact => {+ project.visibility_for_paths(abs_paths, true, cx)+ }+ WorkspaceMatching::MatchSubpaths => {+ project.visibility_for_subpaths(abs_paths, cx)+ }+ WorkspaceMatching::MatchSubdirectory => {+ project.visibility_for_paths(abs_paths, false, cx)+ }+ };if m > best_match {existing = Some((window, workspace.clone()));best_match = m;@@ -9865,6 +9872,9 @@ pub enum WorkspaceMatching {/// Match paths against existing worktree roots and files within them.#[default]MatchExact,+ /// Match files and directories inside existing worktrees, excluding the+ /// worktree roots themselves.+ MatchSubpaths,/// Match paths against existing worktrees including subdirectories, and/// fall back to any existing window if no worktree matched.///@@ -9907,7 +9917,10 @@ impl Default for OpenOptions {impl OpenOptions {fn should_reuse_existing_window(&self) -> bool {- self.workspace_matching != WorkspaceMatching::None && self.open_mode != OpenMode::NewWindow+ !matches!(+ self.workspace_matching,+ WorkspaceMatching::None | WorkspaceMatching::MatchSubpaths+ ) && self.open_mode != OpenMode::NewWindow}}diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rsindex 80a851571b8..a992dfe4fd9 100644--- a/crates/zed/src/zed/open_listener.rs+++ b/crates/zed/src/zed/open_listener.rs@@ -612,12 +612,16 @@ pub async fn handle_cli_connection(open_behavior = cli::OpenBehavior::ExistingWindow;}Some(settings::CliDefaultOpenBehavior::NewWindow) => {- open_behavior = cli::OpenBehavior::Classic;+ open_behavior = cli::OpenBehavior::PreferNewWindow;}None => {}}}+ if open_behavior == cli::OpenBehavior::Default {+ open_behavior = cx.update(|cx| open_behavior_for_default_setting(cx));+ }+cx.update(|cx| cx.activate(true));let open_workspace_result = open_workspaces(@@ -647,8 +651,8 @@ pub async fn handle_cli_connection(}}-/// Resolves the CLI open behavior when no explicit flag (`-n`, `-e`, `--reuse`)-/// was given. May prompt the user interactively on first run.+/// Resolves the CLI open behavior when no explicit open behavior flag was given.+/// May prompt the user interactively on first run.////// Returns `Some(behavior)` to override the default, or `None` if no override/// is needed (e.g. no existing windows, paths already in a workspace, or the@@ -756,6 +760,12 @@ pub(crate) fn open_options_for_behavior(location: &SerializedWorkspaceLocation,cx: &App,) -> workspace::OpenOptions {+ let open_behavior = if open_behavior == cli::OpenBehavior::Default {+ open_behavior_for_default_setting(cx)+ } else {+ open_behavior+ };+// If reuse flag is passed, open a new workspace in an existing window.let requesting_window = if open_behavior == cli::OpenBehavior::Reuse {workspace::workspace_windows_for_location(location, cx)@@ -769,17 +779,12 @@ pub(crate) fn open_options_for_behavior(cli::OpenBehavior::AlwaysNew | cli::OpenBehavior::Reuse => {workspace::WorkspaceMatching::None}+ cli::OpenBehavior::PreferNewWindow => workspace::WorkspaceMatching::MatchSubpaths,cli::OpenBehavior::Add => workspace::WorkspaceMatching::MatchSubdirectory,_ => workspace::WorkspaceMatching::MatchExact,},add_dirs_to_sidebar: match open_behavior {cli::OpenBehavior::ExistingWindow => true,- // For the default value, we consult the settings to decide- // whether to open in a new window or existing window.- cli::OpenBehavior::Default => {- workspace::WorkspaceSettings::get_global(cx).cli_default_open_behavior- == settings::CliDefaultOpenBehavior::ExistingWindow- }_ => false,},requesting_window,@@ -787,6 +792,13 @@ pub(crate) fn open_options_for_behavior(}}+fn open_behavior_for_default_setting(cx: &App) -> cli::OpenBehavior {+ match workspace::WorkspaceSettings::get_global(cx).cli_default_open_behavior {+ settings::CliDefaultOpenBehavior::ExistingWindow => cli::OpenBehavior::ExistingWindow,+ settings::CliDefaultOpenBehavior::NewWindow => cli::OpenBehavior::PreferNewWindow,+ }+}+async fn open_workspaces(paths: Vec<String>,diff_paths: Vec<[String; 2]>,@@ -800,7 +812,13 @@ async fn open_workspaces(cwd: Option<PathBuf>,cx: &mut AsyncApp,) -> Result<()> {- if paths.is_empty() && diff_paths.is_empty() && open_behavior != cli::OpenBehavior::AlwaysNew {+ if paths.is_empty()+ && diff_paths.is_empty()+ && !matches!(+ open_behavior,+ cli::OpenBehavior::AlwaysNew | cli::OpenBehavior::PreferNewWindow+ )+ {return restore_or_create_workspace(app_state, cx).await;}@@ -1082,7 +1100,7 @@ mod tests {use cli::CliResponse;use editor::Editor;use futures::poll;- use gpui::{AppContext as _, TestAppContext};+ use gpui::{AppContext as _, TestAppContext, UpdateGlobal as _};use language::LineEnding;use remote::SshConnectionOptions;use rope::Rope;@@ -2589,6 +2607,135 @@ mod tests {);}+ #[gpui::test]+ async fn test_e2e_new_window_setting_opens_project_root_in_new_window(cx: &mut TestAppContext) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(path!("/project"), json!({ "file.txt": "content" }))+ .await;++ app_state+ .fs+ .as_fake()+ .insert_tree(+ paths::config_dir(),+ json!({+ "settings.json": r#"{"cli_default_open_behavior": "new_window"}"#+ }),+ )+ .await;++ cx.update(|cx| {+ settings::SettingsStore::update_global(cx, |store, cx| {+ store.update_user_settings(cx, |settings| {+ settings.workspace.cli_default_open_behavior =+ Some(settings::CliDefaultOpenBehavior::NewWindow);+ });+ });+ });++ open_workspace_file(path!("/project"), Default::default(), app_state.clone(), cx).await;+ assert_eq!(cx.windows().len(), 1);++ let (status, prompt_shown) = run_cli_with_zed_handler(+ cx,+ app_state,+ make_cli_open_request(+ vec![path!("/project").to_string()],+ cli::OpenBehavior::Default,+ ),+ None,+ );++ assert_eq!(status, 0);+ assert!(+ !prompt_shown,+ "no prompt should be shown when setting already configured"+ );+ assert_eq!(cx.windows().len(), 2);+ }++ #[gpui::test]+ async fn test_e2e_new_window_setting_focuses_existing_window_for_subpaths(+ cx: &mut TestAppContext,+ ) {+ let app_state = init_test(cx);++ app_state+ .fs+ .as_fake()+ .insert_tree(+ path!("/project"),+ json!({+ "file.txt": "content",+ "src": {+ "main.rs": "fn main() {}",+ },+ }),+ )+ .await;++ app_state+ .fs+ .as_fake()+ .insert_tree(+ paths::config_dir(),+ json!({+ "settings.json": r#"{"cli_default_open_behavior": "new_window"}"#+ }),+ )+ .await;++ cx.update(|cx| {+ settings::SettingsStore::update_global(cx, |store, cx| {+ store.update_user_settings(cx, |settings| {+ settings.workspace.cli_default_open_behavior =+ Some(settings::CliDefaultOpenBehavior::NewWindow);+ });+ });+ });++ open_workspace_file(path!("/project"), Default::default(), app_state.clone(), cx).await;+ assert_eq!(cx.windows().len(), 1);++ let (status, prompt_shown) = run_cli_with_zed_handler(+ cx,+ app_state.clone(),+ make_cli_open_request(+ vec![path!("/project/src").to_string()],+ cli::OpenBehavior::Default,+ ),+ None,+ );++ assert_eq!(status, 0);+ assert!(+ !prompt_shown,+ "no prompt should be shown when setting already configured"+ );+ assert_eq!(cx.windows().len(), 1);++ let (status, prompt_shown) = run_cli_with_zed_handler(+ cx,+ app_state,+ make_cli_open_request(+ vec![path!("/project/file.txt").to_string()],+ cli::OpenBehavior::Default,+ ),+ None,+ );++ assert_eq!(status, 0);+ assert!(+ !prompt_shown,+ "no prompt should be shown when setting already configured"+ );+ assert_eq!(cx.windows().len(), 1);+ }+#[gpui::test]async fn test_e2e_explicit_existing_flag_no_prompt(cx: &mut TestAppContext) {let app_state = init_test(cx);