main.rs

   1// Disable command line from opening on release mode
   2#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
   3
   4mod reliability;
   5mod zed;
   6
   7use agent_ui::AgentPanel;
   8use anyhow::{Context as _, Error, Result};
   9use clap::Parser;
  10use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
  11use client::{Client, ProxySettings, UserStore, parse_zed_link};
  12use collab_ui::channel_view::ChannelView;
  13use collections::HashMap;
  14use crashes::InitCrashHandler;
  15use db::kvp::{GLOBAL_KEY_VALUE_STORE, KEY_VALUE_STORE};
  16use editor::Editor;
  17use extension::ExtensionHostProxy;
  18use fs::{Fs, RealFs};
  19use futures::{StreamExt, channel::oneshot, future};
  20use git::GitHostingProviderRegistry;
  21use git_ui::clone::clone_and_open;
  22use gpui::{App, AppContext, Application, AsyncApp, Focusable as _, QuitMode, UpdateGlobal as _};
  23
  24use gpui_tokio::Tokio;
  25use language::LanguageRegistry;
  26use onboarding::{FIRST_OPEN, show_onboarding_view};
  27use project_panel::ProjectPanel;
  28use prompt_store::PromptBuilder;
  29use remote::RemoteConnectionOptions;
  30use reqwest_client::ReqwestClient;
  31
  32use assets::Assets;
  33use node_runtime::{NodeBinaryOptions, NodeRuntime};
  34use parking_lot::Mutex;
  35use project::{project_settings::ProjectSettings, trusted_worktrees};
  36use recent_projects::{SshSettings, open_remote_project};
  37use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
  38use session::{AppSession, Session};
  39use settings::{BaseKeymap, Settings, SettingsStore, watch_config_file};
  40use std::{
  41    cell::RefCell,
  42    env,
  43    io::{self, IsTerminal},
  44    path::{Path, PathBuf},
  45    process,
  46    rc::Rc,
  47    sync::{Arc, OnceLock},
  48    time::Instant,
  49};
  50use theme::{ActiveTheme, GlobalTheme, ThemeRegistry};
  51use util::{ResultExt, TryFutureExt, maybe};
  52use uuid::Uuid;
  53use workspace::{
  54    AppState, PathList, SerializedWorkspaceLocation, Toast, Workspace, WorkspaceSettings,
  55    WorkspaceStore, notifications::NotificationId,
  56};
  57use zed::{
  58    OpenListener, OpenRequest, RawOpenRequest, app_menus, build_window_options,
  59    derive_paths_with_position, edit_prediction_registry, handle_cli_connection,
  60    handle_keymap_file_changes, handle_settings_file_changes, initialize_workspace,
  61    open_paths_with_positions,
  62};
  63
  64use crate::zed::{OpenRequestKind, eager_load_active_theme_and_icon_theme};
  65
  66#[cfg(feature = "mimalloc")]
  67#[global_allocator]
  68static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
  69
  70fn files_not_created_on_launch(errors: HashMap<io::ErrorKind, Vec<&Path>>) {
  71    let message = "Zed failed to launch";
  72    let error_details = errors
  73        .into_iter()
  74        .flat_map(|(kind, paths)| {
  75            #[allow(unused_mut)] // for non-unix platforms
  76            let mut error_kind_details = match paths.len() {
  77                0 => return None,
  78                1 => format!(
  79                    "{kind} when creating directory {:?}",
  80                    paths.first().expect("match arm checks for a single entry")
  81                ),
  82                _many => format!("{kind} when creating directories {paths:?}"),
  83            };
  84
  85            #[cfg(unix)]
  86            {
  87                if kind == io::ErrorKind::PermissionDenied {
  88                    error_kind_details.push_str("\n\nConsider using chown and chmod tools for altering the directories permissions if your user has corresponding rights.\
  89                        \nFor example, `sudo chown $(whoami):staff ~/.config` and `chmod +uwrx ~/.config`");
  90                }
  91            }
  92
  93            Some(error_kind_details)
  94        })
  95        .collect::<Vec<_>>().join("\n\n");
  96
  97    eprintln!("{message}: {error_details}");
  98    Application::new()
  99        .with_quit_mode(QuitMode::Explicit)
 100        .run(move |cx| {
 101            if let Ok(window) = cx.open_window(gpui::WindowOptions::default(), |_, cx| {
 102                cx.new(|_| gpui::Empty)
 103            }) {
 104                window
 105                    .update(cx, |_, window, cx| {
 106                        let response = window.prompt(
 107                            gpui::PromptLevel::Critical,
 108                            message,
 109                            Some(&error_details),
 110                            &["Exit"],
 111                            cx,
 112                        );
 113
 114                        cx.spawn_in(window, async move |_, cx| {
 115                            response.await?;
 116                            cx.update(|_, cx| cx.quit())
 117                        })
 118                        .detach_and_log_err(cx);
 119                    })
 120                    .log_err();
 121            } else {
 122                fail_to_open_window(anyhow::anyhow!("{message}: {error_details}"), cx)
 123            }
 124        })
 125}
 126
 127fn fail_to_open_window_async(e: anyhow::Error, cx: &mut AsyncApp) {
 128    cx.update(|cx| fail_to_open_window(e, cx)).log_err();
 129}
 130
 131fn fail_to_open_window(e: anyhow::Error, _cx: &mut App) {
 132    eprintln!(
 133        "Zed failed to open a window: {e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
 134    );
 135    #[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
 136    {
 137        process::exit(1);
 138    }
 139
 140    // Maybe unify this with gpui::platform::linux::platform::ResultExt::notify_err(..)?
 141    #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 142    {
 143        use ashpd::desktop::notification::{Notification, NotificationProxy, Priority};
 144        _cx.spawn(async move |_cx| {
 145            let Ok(proxy) = NotificationProxy::new().await else {
 146                process::exit(1);
 147            };
 148
 149            let notification_id = "dev.zed.Oops";
 150            proxy
 151                .add_notification(
 152                    notification_id,
 153                    Notification::new("Zed failed to launch")
 154                        .body(Some(
 155                            format!(
 156                                "{e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
 157                            )
 158                            .as_str(),
 159                        ))
 160                        .priority(Priority::High)
 161                        .icon(ashpd::desktop::Icon::with_names(&[
 162                            "dialog-question-symbolic",
 163                        ])),
 164                )
 165                .await
 166                .ok();
 167
 168            process::exit(1);
 169        })
 170        .detach();
 171    }
 172}
 173static STARTUP_TIME: OnceLock<Instant> = OnceLock::new();
 174
 175fn main() {
 176    STARTUP_TIME.get_or_init(|| Instant::now());
 177
 178    #[cfg(unix)]
 179    util::prevent_root_execution();
 180
 181    let args = Args::parse();
 182
 183    // `zed --askpass` Makes zed operate in nc/netcat mode for use with askpass
 184    #[cfg(not(target_os = "windows"))]
 185    if let Some(socket) = &args.askpass {
 186        askpass::main(socket);
 187        return;
 188    }
 189
 190    // `zed --crash-handler` Makes zed operate in minidump crash handler mode
 191    if let Some(socket) = &args.crash_handler {
 192        crashes::crash_server(socket.as_path());
 193        return;
 194    }
 195
 196    // `zed --nc` Makes zed operate in nc/netcat mode for use with MCP
 197    if let Some(socket) = &args.nc {
 198        match nc::main(socket) {
 199            Ok(()) => return,
 200            Err(err) => {
 201                eprintln!("Error: {}", err);
 202                process::exit(1);
 203            }
 204        }
 205    }
 206
 207    #[cfg(all(not(debug_assertions), target_os = "windows"))]
 208    unsafe {
 209        use windows::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole};
 210
 211        if args.foreground {
 212            let _ = AttachConsole(ATTACH_PARENT_PROCESS);
 213        }
 214    }
 215
 216    // `zed --printenv` Outputs environment variables as JSON to stdout
 217    if args.printenv {
 218        util::shell_env::print_env();
 219        return;
 220    }
 221
 222    if args.dump_all_actions {
 223        dump_all_gpui_actions();
 224        return;
 225    }
 226
 227    // Set custom data directory.
 228    if let Some(dir) = &args.user_data_dir {
 229        paths::set_custom_data_dir(dir);
 230    }
 231
 232    #[cfg(target_os = "windows")]
 233    match util::get_zed_cli_path() {
 234        Ok(path) => askpass::set_askpass_program(path),
 235        Err(err) => {
 236            eprintln!("Error: {}", err);
 237            if std::option_env!("ZED_BUNDLE").is_some() {
 238                process::exit(1);
 239            }
 240        }
 241    }
 242
 243    let file_errors = init_paths();
 244    if !file_errors.is_empty() {
 245        files_not_created_on_launch(file_errors);
 246        return;
 247    }
 248
 249    zlog::init();
 250
 251    if stdout_is_a_pty() {
 252        zlog::init_output_stdout();
 253    } else {
 254        let result = zlog::init_output_file(paths::log_file(), Some(paths::old_log_file()));
 255        if let Err(err) = result {
 256            eprintln!("Could not open log file: {}... Defaulting to stdout", err);
 257            zlog::init_output_stdout();
 258        };
 259    }
 260    ztracing::init();
 261
 262    let version = option_env!("ZED_BUILD_ID");
 263    let app_commit_sha =
 264        option_env!("ZED_COMMIT_SHA").map(|commit_sha| AppCommitSha::new(commit_sha.to_string()));
 265    let app_version = AppVersion::load(env!("CARGO_PKG_VERSION"), version, app_commit_sha.clone());
 266
 267    if args.system_specs {
 268        let system_specs = system_specs::SystemSpecs::new_stateless(
 269            app_version,
 270            app_commit_sha,
 271            *release_channel::RELEASE_CHANNEL,
 272        );
 273        println!("Zed System Specs (from CLI):\n{}", system_specs);
 274        return;
 275    }
 276
 277    rayon::ThreadPoolBuilder::new()
 278        .num_threads(std::thread::available_parallelism().map_or(1, |n| n.get().div_ceil(2)))
 279        .stack_size(10 * 1024 * 1024)
 280        .thread_name(|ix| format!("RayonWorker{}", ix))
 281        .build_global()
 282        .unwrap();
 283
 284    log::info!(
 285        "========== starting zed version {}, sha {} ==========",
 286        app_version,
 287        app_commit_sha
 288            .as_ref()
 289            .map(|sha| sha.short())
 290            .as_deref()
 291            .unwrap_or("unknown"),
 292    );
 293
 294    #[cfg(windows)]
 295    check_for_conpty_dll();
 296
 297    let app = Application::new().with_assets(Assets);
 298
 299    let system_id = app.background_executor().spawn(system_id());
 300    let installation_id = app.background_executor().spawn(installation_id());
 301    let session_id = Uuid::new_v4().to_string();
 302    let session = app
 303        .background_executor()
 304        .spawn(Session::new(session_id.clone()));
 305
 306    app.background_executor()
 307        .spawn(crashes::init(InitCrashHandler {
 308            session_id,
 309            zed_version: app_version.to_string(),
 310            binary: "zed".to_string(),
 311            release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
 312            commit_sha: app_commit_sha
 313                .as_ref()
 314                .map(|sha| sha.full())
 315                .unwrap_or_else(|| "no sha".to_owned()),
 316        }))
 317        .detach();
 318
 319    let (open_listener, mut open_rx) = OpenListener::new();
 320
 321    let failed_single_instance_check = if *zed_env_vars::ZED_STATELESS
 322        || *release_channel::RELEASE_CHANNEL == ReleaseChannel::Dev
 323    {
 324        false
 325    } else {
 326        #[cfg(any(target_os = "linux", target_os = "freebsd"))]
 327        {
 328            crate::zed::listen_for_cli_connections(open_listener.clone()).is_err()
 329        }
 330
 331        #[cfg(target_os = "windows")]
 332        {
 333            !crate::zed::windows_only_instance::handle_single_instance(open_listener.clone(), &args)
 334        }
 335
 336        #[cfg(target_os = "macos")]
 337        {
 338            use zed::mac_only_instance::*;
 339            ensure_only_instance() != IsOnlyInstance::Yes
 340        }
 341    };
 342    if failed_single_instance_check {
 343        println!("zed is already running");
 344        return;
 345    }
 346
 347    let git_hosting_provider_registry = Arc::new(GitHostingProviderRegistry::new());
 348    let git_binary_path =
 349        if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
 350            app.path_for_auxiliary_executable("git")
 351                .context("could not find git binary path")
 352                .log_err()
 353        } else {
 354            None
 355        };
 356    if let Some(git_binary_path) = &git_binary_path {
 357        log::info!("Using git binary path: {:?}", git_binary_path);
 358    }
 359
 360    let fs = Arc::new(RealFs::new(git_binary_path, app.background_executor()));
 361    let user_settings_file_rx = watch_config_file(
 362        &app.background_executor(),
 363        fs.clone(),
 364        paths::settings_file().clone(),
 365    );
 366    let global_settings_file_rx = watch_config_file(
 367        &app.background_executor(),
 368        fs.clone(),
 369        paths::global_settings_file().clone(),
 370    );
 371    let user_keymap_file_rx = watch_config_file(
 372        &app.background_executor(),
 373        fs.clone(),
 374        paths::keymap_file().clone(),
 375    );
 376
 377    let (shell_env_loaded_tx, shell_env_loaded_rx) = oneshot::channel();
 378    if !stdout_is_a_pty() {
 379        app.background_executor()
 380            .spawn(async {
 381                #[cfg(unix)]
 382                util::load_login_shell_environment().await.log_err();
 383                shell_env_loaded_tx.send(()).ok();
 384            })
 385            .detach()
 386    } else {
 387        drop(shell_env_loaded_tx)
 388    }
 389
 390    app.on_open_urls({
 391        let open_listener = open_listener.clone();
 392        move |urls| {
 393            open_listener.open(RawOpenRequest {
 394                urls,
 395                diff_paths: Vec::new(),
 396                ..Default::default()
 397            })
 398        }
 399    });
 400    app.on_reopen(move |cx| {
 401        if let Some(app_state) = AppState::try_global(cx).and_then(|app_state| app_state.upgrade())
 402        {
 403            cx.spawn({
 404                let app_state = app_state;
 405                async move |cx| {
 406                    if let Err(e) = restore_or_create_workspace(app_state, cx).await {
 407                        fail_to_open_window_async(e, cx)
 408                    }
 409                }
 410            })
 411            .detach();
 412        }
 413    });
 414
 415    app.run(move |cx| {
 416        let trusted_paths = match workspace::WORKSPACE_DB.fetch_trusted_worktrees(None, None, cx) {
 417            Ok(trusted_paths) => trusted_paths,
 418            Err(e) => {
 419                log::error!("Failed to do initial trusted worktrees fetch: {e:#}");
 420                HashMap::default()
 421            }
 422        };
 423        trusted_worktrees::init(trusted_paths, None, None, cx);
 424        menu::init();
 425        zed_actions::init();
 426
 427        release_channel::init(app_version, cx);
 428        gpui_tokio::init(cx);
 429        if let Some(app_commit_sha) = app_commit_sha {
 430            AppCommitSha::set_global(app_commit_sha, cx);
 431        }
 432        settings::init(cx);
 433        zlog_settings::init(cx);
 434        handle_settings_file_changes(user_settings_file_rx, global_settings_file_rx, cx);
 435        handle_keymap_file_changes(user_keymap_file_rx, cx);
 436
 437        let user_agent = format!(
 438            "Zed/{} ({}; {})",
 439            AppVersion::global(cx),
 440            std::env::consts::OS,
 441            std::env::consts::ARCH
 442        );
 443        let proxy_url = ProxySettings::get_global(cx).proxy_url();
 444        let http = {
 445            let _guard = Tokio::handle(cx).enter();
 446
 447            ReqwestClient::proxy_and_user_agent(proxy_url, &user_agent)
 448                .expect("could not start HTTP client")
 449        };
 450        cx.set_http_client(Arc::new(http));
 451
 452        <dyn Fs>::set_global(fs.clone(), cx);
 453
 454        GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
 455        git_hosting_providers::init(cx);
 456
 457        OpenListener::set_global(cx, open_listener.clone());
 458
 459        extension::init(cx);
 460        let extension_host_proxy = ExtensionHostProxy::global(cx);
 461
 462        let client = Client::production(cx);
 463        cx.set_http_client(client.http_client());
 464        let mut languages = LanguageRegistry::new(cx.background_executor().clone());
 465        languages.set_language_server_download_dir(paths::languages_dir().clone());
 466        let languages = Arc::new(languages);
 467        let (mut tx, rx) = watch::channel(None);
 468        cx.observe_global::<SettingsStore>(move |cx| {
 469            let settings = &ProjectSettings::get_global(cx).node;
 470            let options = NodeBinaryOptions {
 471                allow_path_lookup: !settings.ignore_system_version,
 472                // TODO: Expose this setting
 473                allow_binary_download: true,
 474                use_paths: settings.path.as_ref().map(|node_path| {
 475                    let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
 476                    let npm_path = settings
 477                        .npm_path
 478                        .as_ref()
 479                        .map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
 480                    (
 481                        node_path.clone(),
 482                        npm_path.unwrap_or_else(|| {
 483                            let base_path = PathBuf::new();
 484                            node_path.parent().unwrap_or(&base_path).join("npm")
 485                        }),
 486                    )
 487                }),
 488            };
 489            tx.send(Some(options)).log_err();
 490        })
 491        .detach();
 492
 493        let node_runtime = NodeRuntime::new(client.http_client(), Some(shell_env_loaded_rx), rx);
 494
 495        debug_adapter_extension::init(extension_host_proxy.clone(), cx);
 496        languages::init(languages.clone(), fs.clone(), node_runtime.clone(), cx);
 497        let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
 498        let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
 499
 500        language_extension::init(
 501            language_extension::LspAccess::ViaWorkspaces({
 502                let workspace_store = workspace_store.clone();
 503                Arc::new(move |cx: &mut App| {
 504                    workspace_store.update(cx, |workspace_store, cx| {
 505                        workspace_store
 506                            .workspaces()
 507                            .iter()
 508                            .map(|workspace| {
 509                                workspace.update(cx, |workspace, _, cx| {
 510                                    workspace.project().read(cx).lsp_store()
 511                                })
 512                            })
 513                            .collect()
 514                    })
 515                })
 516            }),
 517            extension_host_proxy.clone(),
 518            languages.clone(),
 519        );
 520
 521        Client::set_global(client.clone(), cx);
 522
 523        zed::init(cx);
 524        project::Project::init(&client, cx);
 525        debugger_ui::init(cx);
 526        debugger_tools::init(cx);
 527        client::init(&client, cx);
 528
 529        let system_id = cx.background_executor().block(system_id).ok();
 530        let installation_id = cx.background_executor().block(installation_id).ok();
 531        let session = cx.background_executor().block(session);
 532
 533        let telemetry = client.telemetry();
 534        telemetry.start(
 535            system_id.as_ref().map(|id| id.to_string()),
 536            installation_id.as_ref().map(|id| id.to_string()),
 537            session.id().to_owned(),
 538            cx,
 539        );
 540
 541        // We should rename these in the future to `first app open`, `first app open for release channel`, and `app open`
 542        if let (Some(system_id), Some(installation_id)) = (&system_id, &installation_id) {
 543            match (&system_id, &installation_id) {
 544                (IdType::New(_), IdType::New(_)) => {
 545                    telemetry::event!("App First Opened");
 546                    telemetry::event!("App First Opened For Release Channel");
 547                }
 548                (IdType::Existing(_), IdType::New(_)) => {
 549                    telemetry::event!("App First Opened For Release Channel");
 550                }
 551                (_, IdType::Existing(_)) => {
 552                    telemetry::event!("App Opened");
 553                }
 554            }
 555        }
 556        let app_session = cx.new(|cx| AppSession::new(session, cx));
 557
 558        let app_state = Arc::new(AppState {
 559            languages,
 560            client: client.clone(),
 561            user_store,
 562            fs: fs.clone(),
 563            build_window_options,
 564            workspace_store,
 565            node_runtime,
 566            session: app_session,
 567        });
 568        AppState::set_global(Arc::downgrade(&app_state), cx);
 569
 570        auto_update::init(client.clone(), cx);
 571        dap_adapters::init(cx);
 572        auto_update_ui::init(cx);
 573        reliability::init(client.clone(), cx);
 574        extension_host::init(
 575            extension_host_proxy.clone(),
 576            app_state.fs.clone(),
 577            app_state.client.clone(),
 578            app_state.node_runtime.clone(),
 579            cx,
 580        );
 581
 582        theme::init(theme::LoadThemes::All(Box::new(Assets)), cx);
 583        eager_load_active_theme_and_icon_theme(fs.clone(), cx);
 584        theme_extension::init(
 585            extension_host_proxy,
 586            ThemeRegistry::global(cx),
 587            cx.background_executor().clone(),
 588        );
 589        command_palette::init(cx);
 590        let copilot_language_server_id = app_state.languages.next_language_server_id();
 591        copilot::init(
 592            copilot_language_server_id,
 593            app_state.fs.clone(),
 594            app_state.client.http_client(),
 595            app_state.node_runtime.clone(),
 596            cx,
 597        );
 598        supermaven::init(app_state.client.clone(), cx);
 599        language_model::init(app_state.client.clone(), cx);
 600        language_models::init(app_state.user_store.clone(), app_state.client.clone(), cx);
 601        acp_tools::init(cx);
 602        edit_prediction_ui::init(cx);
 603        web_search::init(cx);
 604        web_search_providers::init(app_state.client.clone(), cx);
 605        snippet_provider::init(cx);
 606        edit_prediction_registry::init(app_state.client.clone(), app_state.user_store.clone(), cx);
 607        let prompt_builder = PromptBuilder::load(app_state.fs.clone(), stdout_is_a_pty(), cx);
 608        agent_ui::init(
 609            app_state.fs.clone(),
 610            app_state.client.clone(),
 611            prompt_builder.clone(),
 612            app_state.languages.clone(),
 613            false,
 614            cx,
 615        );
 616        agent_ui_v2::agents_panel::init(cx);
 617        repl::init(app_state.fs.clone(), cx);
 618        recent_projects::init(cx);
 619
 620        load_embedded_fonts(cx);
 621
 622        editor::init(cx);
 623        image_viewer::init(cx);
 624        repl::notebook::init(cx);
 625        diagnostics::init(cx);
 626
 627        audio::init(cx);
 628        workspace::init(app_state.clone(), cx);
 629        ui_prompt::init(cx);
 630
 631        go_to_line::init(cx);
 632        file_finder::init(cx);
 633        tab_switcher::init(cx);
 634        outline::init(cx);
 635        project_symbols::init(cx);
 636        project_panel::init(cx);
 637        outline_panel::init(cx);
 638        tasks_ui::init(cx);
 639        snippets_ui::init(cx);
 640        channel::init(&app_state.client.clone(), app_state.user_store.clone(), cx);
 641        search::init(cx);
 642        vim::init(cx);
 643        terminal_view::init(cx);
 644        journal::init(app_state.clone(), cx);
 645        language_selector::init(cx);
 646        line_ending_selector::init(cx);
 647        toolchain_selector::init(cx);
 648        theme_selector::init(cx);
 649        settings_profile_selector::init(cx);
 650        language_tools::init(cx);
 651        call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
 652        notifications::init(app_state.client.clone(), app_state.user_store.clone(), cx);
 653        collab_ui::init(&app_state, cx);
 654        git_ui::init(cx);
 655        feedback::init(cx);
 656        markdown_preview::init(cx);
 657        svg_preview::init(cx);
 658        onboarding::init(cx);
 659        settings_ui::init(cx);
 660        keymap_editor::init(cx);
 661        extensions_ui::init(cx);
 662        edit_prediction::init(cx);
 663        inspector_ui::init(app_state.clone(), cx);
 664        json_schema_store::init(cx);
 665        miniprofiler_ui::init(*STARTUP_TIME.get().unwrap(), cx);
 666        which_key::init(cx);
 667
 668        cx.observe_global::<SettingsStore>({
 669            let http = app_state.client.http_client();
 670            let client = app_state.client.clone();
 671            move |cx| {
 672                for &mut window in cx.windows().iter_mut() {
 673                    let background_appearance = cx.theme().window_background_appearance();
 674                    window
 675                        .update(cx, |_, window, _| {
 676                            window.set_background_appearance(background_appearance)
 677                        })
 678                        .ok();
 679                }
 680
 681                let new_host = &client::ClientSettings::get_global(cx).server_url;
 682                if &http.base_url() != new_host {
 683                    http.set_base_url(new_host);
 684                    if client.status().borrow().is_connected() {
 685                        client.reconnect(&cx.to_async());
 686                    }
 687                }
 688            }
 689        })
 690        .detach();
 691        app_state.languages.set_theme(cx.theme().clone());
 692        cx.observe_global::<GlobalTheme>({
 693            let languages = app_state.languages.clone();
 694            move |cx| {
 695                languages.set_theme(cx.theme().clone());
 696            }
 697        })
 698        .detach();
 699        telemetry::event!(
 700            "Settings Changed",
 701            setting = "theme",
 702            value = cx.theme().name.to_string()
 703        );
 704        telemetry::event!(
 705            "Settings Changed",
 706            setting = "keymap",
 707            value = BaseKeymap::get_global(cx).to_string()
 708        );
 709        telemetry.flush_events().detach();
 710
 711        let fs = app_state.fs.clone();
 712        load_user_themes_in_background(fs.clone(), cx);
 713        watch_themes(fs.clone(), cx);
 714        watch_languages(fs.clone(), app_state.languages.clone(), cx);
 715
 716        let menus = app_menus(cx);
 717        cx.set_menus(menus);
 718        initialize_workspace(app_state.clone(), prompt_builder, cx);
 719
 720        cx.activate(true);
 721
 722        cx.spawn({
 723            let client = app_state.client.clone();
 724            async move |cx| authenticate(client, cx).await
 725        })
 726        .detach_and_log_err(cx);
 727
 728        let urls: Vec<_> = args
 729            .paths_or_urls
 730            .iter()
 731            .map(|arg| parse_url_arg(arg, cx))
 732            .collect();
 733
 734        let diff_paths: Vec<[String; 2]> = args
 735            .diff
 736            .chunks(2)
 737            .map(|chunk| [chunk[0].clone(), chunk[1].clone()])
 738            .collect();
 739
 740        #[cfg(target_os = "windows")]
 741        let wsl = args.wsl;
 742        #[cfg(not(target_os = "windows"))]
 743        let wsl = None;
 744
 745        if !urls.is_empty() || !diff_paths.is_empty() {
 746            open_listener.open(RawOpenRequest {
 747                urls,
 748                diff_paths,
 749                wsl,
 750            })
 751        }
 752
 753        match open_rx
 754            .try_next()
 755            .ok()
 756            .flatten()
 757            .and_then(|request| OpenRequest::parse(request, cx).log_err())
 758        {
 759            Some(request) => {
 760                handle_open_request(request, app_state.clone(), cx);
 761            }
 762            None => {
 763                cx.spawn({
 764                    let app_state = app_state.clone();
 765                    async move |cx| {
 766                        if let Err(e) = restore_or_create_workspace(app_state, cx).await {
 767                            fail_to_open_window_async(e, cx)
 768                        }
 769                    }
 770                })
 771                .detach();
 772            }
 773        }
 774
 775        let app_state = app_state.clone();
 776
 777        crate::zed::component_preview::init(app_state.clone(), cx);
 778
 779        cx.spawn(async move |cx| {
 780            while let Some(urls) = open_rx.next().await {
 781                cx.update(|cx| {
 782                    if let Some(request) = OpenRequest::parse(urls, cx).log_err() {
 783                        handle_open_request(request, app_state.clone(), cx);
 784                    }
 785                })
 786                .ok();
 787            }
 788        })
 789        .detach();
 790    });
 791}
 792
 793fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut App) {
 794    if let Some(kind) = request.kind {
 795        match kind {
 796            OpenRequestKind::CliConnection(connection) => {
 797                cx.spawn(async move |cx| handle_cli_connection(connection, app_state, cx).await)
 798                    .detach();
 799            }
 800            OpenRequestKind::Extension { extension_id } => {
 801                cx.spawn(async move |cx| {
 802                    let workspace =
 803                        workspace::get_any_active_workspace(app_state, cx.clone()).await?;
 804                    workspace.update(cx, |_, window, cx| {
 805                        window.dispatch_action(
 806                            Box::new(zed_actions::Extensions {
 807                                category_filter: None,
 808                                id: Some(extension_id),
 809                            }),
 810                            cx,
 811                        );
 812                    })
 813                })
 814                .detach_and_log_err(cx);
 815            }
 816            OpenRequestKind::AgentPanel => {
 817                cx.spawn(async move |cx| {
 818                    let workspace =
 819                        workspace::get_any_active_workspace(app_state, cx.clone()).await?;
 820                    workspace.update(cx, |workspace, window, cx| {
 821                        if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
 822                            panel.focus_handle(cx).focus(window, cx);
 823                        }
 824                    })
 825                })
 826                .detach_and_log_err(cx);
 827            }
 828            OpenRequestKind::DockMenuAction { index } => {
 829                cx.perform_dock_menu_action(index);
 830            }
 831            OpenRequestKind::BuiltinJsonSchema { schema_path } => {
 832                workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
 833                    cx.spawn_in(window, async move |workspace, cx| {
 834                        let res = async move {
 835                            let json = app_state.languages.language_for_name("JSONC").await.ok();
 836                            let json_schema_content =
 837                                json_schema_store::resolve_schema_request_inner(
 838                                    &app_state.languages,
 839                                    &schema_path,
 840                                    cx,
 841                                )?;
 842                            let json_schema_content =
 843                                serde_json::to_string_pretty(&json_schema_content)
 844                                    .context("Failed to serialize JSON Schema as JSON")?;
 845                            let buffer_task = workspace.update(cx, |workspace, cx| {
 846                                workspace
 847                                    .project()
 848                                    .update(cx, |project, cx| project.create_buffer(false, cx))
 849                            })?;
 850
 851                            let buffer = buffer_task.await?;
 852
 853                            workspace.update_in(cx, |workspace, window, cx| {
 854                                buffer.update(cx, |buffer, cx| {
 855                                    buffer.set_language(json, cx);
 856                                    buffer.edit([(0..0, json_schema_content)], None, cx);
 857                                    buffer.edit(
 858                                        [(0..0, format!("// {} JSON Schema\n", schema_path))],
 859                                        None,
 860                                        cx,
 861                                    );
 862                                });
 863
 864                                workspace.add_item_to_active_pane(
 865                                    Box::new(cx.new(|cx| {
 866                                        let mut editor =
 867                                            editor::Editor::for_buffer(buffer, None, window, cx);
 868                                        editor.set_read_only(true);
 869                                        editor
 870                                    })),
 871                                    None,
 872                                    true,
 873                                    window,
 874                                    cx,
 875                                );
 876                            })
 877                        }
 878                        .await;
 879                        res.context("Failed to open builtin JSON Schema").log_err();
 880                    })
 881                    .detach();
 882                });
 883            }
 884            OpenRequestKind::Setting { setting_path } => {
 885                // zed://settings/languages/$(language)/tab_size  - DONT SUPPORT
 886                // zed://settings/languages/Rust/tab_size  - SUPPORT
 887                // languages.$(language).tab_size
 888                // [ languages $(language) tab_size]
 889                cx.spawn(async move |cx| {
 890                    let workspace =
 891                        workspace::get_any_active_workspace(app_state, cx.clone()).await?;
 892
 893                    workspace.update(cx, |_, window, cx| match setting_path {
 894                        None => window.dispatch_action(Box::new(zed_actions::OpenSettings), cx),
 895                        Some(setting_path) => window.dispatch_action(
 896                            Box::new(zed_actions::OpenSettingsAt { path: setting_path }),
 897                            cx,
 898                        ),
 899                    })
 900                })
 901                .detach_and_log_err(cx);
 902            }
 903            OpenRequestKind::GitClone { repo_url } => {
 904                workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
 905                    if window.is_window_active() {
 906                        clone_and_open(
 907                            repo_url,
 908                            cx.weak_entity(),
 909                            window,
 910                            cx,
 911                            Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
 912                                workspace.focus_panel::<ProjectPanel>(window, cx);
 913                            }),
 914                        );
 915                        return;
 916                    }
 917
 918                    let subscription = Rc::new(RefCell::new(None));
 919                    subscription.replace(Some(cx.observe_in(&cx.entity(), window, {
 920                        let subscription = subscription.clone();
 921                        let repo_url = repo_url;
 922                        move |_, workspace_entity, window, cx| {
 923                            if window.is_window_active() && subscription.take().is_some() {
 924                                clone_and_open(
 925                                    repo_url.clone(),
 926                                    workspace_entity.downgrade(),
 927                                    window,
 928                                    cx,
 929                                    Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
 930                                        workspace.focus_panel::<ProjectPanel>(window, cx);
 931                                    }),
 932                                );
 933                            }
 934                        }
 935                    })));
 936                });
 937            }
 938            OpenRequestKind::GitCommit { sha } => {
 939                cx.spawn(async move |cx| {
 940                    let paths_with_position =
 941                        derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
 942                    let (workspace, _results) = open_paths_with_positions(
 943                        &paths_with_position,
 944                        &[],
 945                        app_state,
 946                        workspace::OpenOptions::default(),
 947                        cx,
 948                    )
 949                    .await?;
 950
 951                    workspace
 952                        .update(cx, |workspace, window, cx| {
 953                            let Some(repo) = workspace.project().read(cx).active_repository(cx)
 954                            else {
 955                                log::error!("no active repository found for commit view");
 956                                return Err(anyhow::anyhow!("no active repository found"));
 957                            };
 958
 959                            git_ui::commit_view::CommitView::open(
 960                                sha,
 961                                repo.downgrade(),
 962                                workspace.weak_handle(),
 963                                None,
 964                                None,
 965                                window,
 966                                cx,
 967                            );
 968                            Ok(())
 969                        })
 970                        .log_err();
 971
 972                    anyhow::Ok(())
 973                })
 974                .detach_and_log_err(cx);
 975            }
 976        }
 977
 978        return;
 979    }
 980
 981    if let Some(connection_options) = request.remote_connection {
 982        cx.spawn(async move |cx| {
 983            let paths: Vec<PathBuf> = request.open_paths.into_iter().map(PathBuf::from).collect();
 984            open_remote_project(
 985                connection_options,
 986                paths,
 987                app_state,
 988                workspace::OpenOptions::default(),
 989                cx,
 990            )
 991            .await
 992        })
 993        .detach_and_log_err(cx);
 994        return;
 995    }
 996
 997    let mut task = None;
 998    if !request.open_paths.is_empty() || !request.diff_paths.is_empty() {
 999        let app_state = app_state.clone();
1000        task = Some(cx.spawn(async move |cx| {
1001            let paths_with_position =
1002                derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
1003            let (_window, results) = open_paths_with_positions(
1004                &paths_with_position,
1005                &request.diff_paths,
1006                app_state,
1007                workspace::OpenOptions::default(),
1008                cx,
1009            )
1010            .await?;
1011            for result in results.into_iter().flatten() {
1012                if let Err(err) = result {
1013                    log::error!("Error opening path: {err}",);
1014                }
1015            }
1016            anyhow::Ok(())
1017        }));
1018    }
1019
1020    if !request.open_channel_notes.is_empty() || request.join_channel.is_some() {
1021        cx.spawn(async move |cx| {
1022            let result = maybe!(async {
1023                if let Some(task) = task {
1024                    task.await?;
1025                }
1026                let client = app_state.client.clone();
1027                // we continue even if authentication fails as join_channel/ open channel notes will
1028                // show a visible error message.
1029                authenticate(client, cx).await.log_err();
1030
1031                if let Some(channel_id) = request.join_channel {
1032                    cx.update(|cx| {
1033                        workspace::join_channel(
1034                            client::ChannelId(channel_id),
1035                            app_state.clone(),
1036                            None,
1037                            cx,
1038                        )
1039                    })?
1040                    .await?;
1041                }
1042
1043                let workspace_window =
1044                    workspace::get_any_active_workspace(app_state, cx.clone()).await?;
1045                let workspace = workspace_window.entity(cx)?;
1046
1047                let mut promises = Vec::new();
1048                for (channel_id, heading) in request.open_channel_notes {
1049                    promises.push(cx.update_window(workspace_window.into(), |_, window, cx| {
1050                        ChannelView::open(
1051                            client::ChannelId(channel_id),
1052                            heading,
1053                            workspace.clone(),
1054                            window,
1055                            cx,
1056                        )
1057                        .log_err()
1058                    })?)
1059                }
1060                future::join_all(promises).await;
1061                anyhow::Ok(())
1062            })
1063            .await;
1064            if let Err(err) = result {
1065                fail_to_open_window_async(err, cx);
1066            }
1067        })
1068        .detach()
1069    } else if let Some(task) = task {
1070        cx.spawn(async move |cx| {
1071            if let Err(err) = task.await {
1072                fail_to_open_window_async(err, cx);
1073            }
1074        })
1075        .detach();
1076    }
1077}
1078
1079async fn authenticate(client: Arc<Client>, cx: &AsyncApp) -> Result<()> {
1080    if stdout_is_a_pty() {
1081        if client::IMPERSONATE_LOGIN.is_some() {
1082            client.sign_in_with_optional_connect(false, cx).await?;
1083        } else if client.has_credentials(cx).await {
1084            client.sign_in_with_optional_connect(true, cx).await?;
1085        }
1086    } else if client.has_credentials(cx).await {
1087        client.sign_in_with_optional_connect(true, cx).await?;
1088    }
1089
1090    Ok(())
1091}
1092
1093async fn system_id() -> Result<IdType> {
1094    let key_name = "system_id".to_string();
1095
1096    if let Ok(Some(system_id)) = GLOBAL_KEY_VALUE_STORE.read_kvp(&key_name) {
1097        return Ok(IdType::Existing(system_id));
1098    }
1099
1100    let system_id = Uuid::new_v4().to_string();
1101
1102    GLOBAL_KEY_VALUE_STORE
1103        .write_kvp(key_name, system_id.clone())
1104        .await?;
1105
1106    Ok(IdType::New(system_id))
1107}
1108
1109async fn installation_id() -> Result<IdType> {
1110    let legacy_key_name = "device_id".to_string();
1111    let key_name = "installation_id".to_string();
1112
1113    // Migrate legacy key to new key
1114    if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&legacy_key_name) {
1115        KEY_VALUE_STORE
1116            .write_kvp(key_name, installation_id.clone())
1117            .await?;
1118        KEY_VALUE_STORE.delete_kvp(legacy_key_name).await?;
1119        return Ok(IdType::Existing(installation_id));
1120    }
1121
1122    if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&key_name) {
1123        return Ok(IdType::Existing(installation_id));
1124    }
1125
1126    let installation_id = Uuid::new_v4().to_string();
1127
1128    KEY_VALUE_STORE
1129        .write_kvp(key_name, installation_id.clone())
1130        .await?;
1131
1132    Ok(IdType::New(installation_id))
1133}
1134
1135async fn restore_or_create_workspace(app_state: Arc<AppState>, cx: &mut AsyncApp) -> Result<()> {
1136    if let Some(locations) = restorable_workspace_locations(cx, &app_state).await {
1137        let use_system_window_tabs = cx
1138            .update(|cx| WorkspaceSettings::get_global(cx).use_system_window_tabs)
1139            .unwrap_or(false);
1140        let mut results: Vec<Result<(), Error>> = Vec::new();
1141        let mut tasks = Vec::new();
1142
1143        for (index, (location, paths)) in locations.into_iter().enumerate() {
1144            match location {
1145                SerializedWorkspaceLocation::Local => {
1146                    let app_state = app_state.clone();
1147                    let task = cx.spawn(async move |cx| {
1148                        let open_task = cx.update(|cx| {
1149                            workspace::open_paths(
1150                                &paths.paths(),
1151                                app_state,
1152                                workspace::OpenOptions::default(),
1153                                cx,
1154                            )
1155                        })?;
1156                        open_task.await.map(|_| ())
1157                    });
1158
1159                    // If we're using system window tabs and this is the first workspace,
1160                    // wait for it to finish so that the other windows can be added as tabs.
1161                    if use_system_window_tabs && index == 0 {
1162                        results.push(task.await);
1163                    } else {
1164                        tasks.push(task);
1165                    }
1166                }
1167                SerializedWorkspaceLocation::Remote(mut connection_options) => {
1168                    let app_state = app_state.clone();
1169                    if let RemoteConnectionOptions::Ssh(options) = &mut connection_options {
1170                        cx.update(|cx| {
1171                            SshSettings::get_global(cx)
1172                                .fill_connection_options_from_settings(options)
1173                        })?;
1174                    }
1175                    let task = cx.spawn(async move |cx| {
1176                        recent_projects::open_remote_project(
1177                            connection_options,
1178                            paths.paths().into_iter().map(PathBuf::from).collect(),
1179                            app_state,
1180                            workspace::OpenOptions::default(),
1181                            cx,
1182                        )
1183                        .await
1184                        .map_err(|e| anyhow::anyhow!(e))
1185                    });
1186                    tasks.push(task);
1187                }
1188            }
1189        }
1190
1191        // Wait for all workspaces to open concurrently
1192        results.extend(future::join_all(tasks).await);
1193
1194        // Show notifications for any errors that occurred
1195        let mut error_count = 0;
1196        for result in results {
1197            if let Err(e) = result {
1198                log::error!("Failed to restore workspace: {}", e);
1199                error_count += 1;
1200            }
1201        }
1202
1203        if error_count > 0 {
1204            let message = if error_count == 1 {
1205                "Failed to restore 1 workspace. Check logs for details.".to_string()
1206            } else {
1207                format!(
1208                    "Failed to restore {} workspaces. Check logs for details.",
1209                    error_count
1210                )
1211            };
1212
1213            // Try to find an active workspace to show the toast
1214            let toast_shown = cx
1215                .update(|cx| {
1216                    if let Some(window) = cx.active_window()
1217                        && let Some(workspace) = window.downcast::<Workspace>()
1218                    {
1219                        workspace
1220                            .update(cx, |workspace, _, cx| {
1221                                workspace.show_toast(
1222                                    Toast::new(NotificationId::unique::<()>(), message),
1223                                    cx,
1224                                )
1225                            })
1226                            .ok();
1227                        return true;
1228                    }
1229                    false
1230                })
1231                .unwrap_or(false);
1232
1233            // If we couldn't show a toast (no windows opened successfully),
1234            // we've already logged the errors above, so the user can check logs
1235            if !toast_shown {
1236                log::error!(
1237                    "Failed to show notification for window restoration errors, because no workspace windows were available."
1238                );
1239            }
1240        }
1241    } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
1242        cx.update(|cx| show_onboarding_view(app_state, cx))?.await?;
1243    } else {
1244        cx.update(|cx| {
1245            workspace::open_new(
1246                Default::default(),
1247                app_state,
1248                cx,
1249                |workspace, window, cx| {
1250                    let restore_on_startup = WorkspaceSettings::get_global(cx).restore_on_startup;
1251                    match restore_on_startup {
1252                        workspace::RestoreOnStartupBehavior::Launchpad => {}
1253                        _ => {
1254                            Editor::new_file(workspace, &Default::default(), window, cx);
1255                        }
1256                    }
1257                },
1258            )
1259        })?
1260        .await?;
1261    }
1262
1263    Ok(())
1264}
1265
1266pub(crate) async fn restorable_workspace_locations(
1267    cx: &mut AsyncApp,
1268    app_state: &Arc<AppState>,
1269) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
1270    let mut restore_behavior = cx
1271        .update(|cx| WorkspaceSettings::get(None, cx).restore_on_startup)
1272        .ok()?;
1273
1274    let session_handle = app_state.session.clone();
1275    let (last_session_id, last_session_window_stack) = cx
1276        .update(|cx| {
1277            let session = session_handle.read(cx);
1278
1279            (
1280                session.last_session_id().map(|id| id.to_string()),
1281                session.last_session_window_stack(),
1282            )
1283        })
1284        .ok()?;
1285
1286    if last_session_id.is_none()
1287        && matches!(
1288            restore_behavior,
1289            workspace::RestoreOnStartupBehavior::LastSession
1290        )
1291    {
1292        restore_behavior = workspace::RestoreOnStartupBehavior::LastWorkspace;
1293    }
1294
1295    match restore_behavior {
1296        workspace::RestoreOnStartupBehavior::LastWorkspace => {
1297            workspace::last_opened_workspace_location()
1298                .await
1299                .map(|location| vec![location])
1300        }
1301        workspace::RestoreOnStartupBehavior::LastSession => {
1302            if let Some(last_session_id) = last_session_id {
1303                let ordered = last_session_window_stack.is_some();
1304
1305                let mut locations = workspace::last_session_workspace_locations(
1306                    &last_session_id,
1307                    last_session_window_stack,
1308                )
1309                .filter(|locations| !locations.is_empty());
1310
1311                // Since last_session_window_order returns the windows ordered front-to-back
1312                // we need to open the window that was frontmost last.
1313                if ordered && let Some(locations) = locations.as_mut() {
1314                    locations.reverse();
1315                }
1316
1317                locations
1318            } else {
1319                None
1320            }
1321        }
1322        _ => None,
1323    }
1324}
1325
1326fn init_paths() -> HashMap<io::ErrorKind, Vec<&'static Path>> {
1327    [
1328        paths::config_dir(),
1329        paths::extensions_dir(),
1330        paths::languages_dir(),
1331        paths::debug_adapters_dir(),
1332        paths::database_dir(),
1333        paths::logs_dir(),
1334        paths::temp_dir(),
1335        paths::hang_traces_dir(),
1336    ]
1337    .into_iter()
1338    .fold(HashMap::default(), |mut errors, path| {
1339        if let Err(e) = std::fs::create_dir_all(path) {
1340            errors.entry(e.kind()).or_insert_with(Vec::new).push(path);
1341        }
1342        errors
1343    })
1344}
1345
1346fn stdout_is_a_pty() -> bool {
1347    std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && io::stdout().is_terminal()
1348}
1349
1350#[derive(Parser, Debug)]
1351#[command(name = "zed", disable_version_flag = true, max_term_width = 100)]
1352struct Args {
1353    /// A sequence of space-separated paths or urls that you want to open.
1354    ///
1355    /// Use `path:line:row` syntax to open a file at a specific location.
1356    /// Non-existing paths and directories will ignore `:line:row` suffix.
1357    ///
1358    /// URLs can either be `file://` or `zed://` scheme, or relative to <https://zed.dev>.
1359    paths_or_urls: Vec<String>,
1360
1361    /// Pairs of file paths to diff. Can be specified multiple times.
1362    #[arg(long, action = clap::ArgAction::Append, num_args = 2, value_names = ["OLD_PATH", "NEW_PATH"])]
1363    diff: Vec<String>,
1364
1365    /// Sets a custom directory for all user data (e.g., database, extensions, logs).
1366    ///
1367    /// This overrides the default platform-specific data directory location.
1368    /// On macOS, the default is `~/Library/Application Support/Zed`.
1369    /// On Linux/FreeBSD, the default is `$XDG_DATA_HOME/zed`.
1370    /// On Windows, the default is `%LOCALAPPDATA%\Zed`.
1371    #[arg(long, value_name = "DIR", verbatim_doc_comment)]
1372    user_data_dir: Option<String>,
1373
1374    /// The username and WSL distribution to use when opening paths. If not specified,
1375    /// Zed will attempt to open the paths directly.
1376    ///
1377    /// The username is optional, and if not specified, the default user for the distribution
1378    /// will be used.
1379    ///
1380    /// Example: `me@Ubuntu` or `Ubuntu`.
1381    ///
1382    /// WARN: You should not fill in this field by hand.
1383    #[cfg(target_os = "windows")]
1384    #[arg(long, value_name = "USER@DISTRO")]
1385    wsl: Option<String>,
1386
1387    /// Instructs zed to run as a dev server on this machine. (not implemented)
1388    #[arg(long)]
1389    dev_server_token: Option<String>,
1390
1391    /// Prints system specs.
1392    ///
1393    /// Useful for submitting issues on GitHub when encountering a bug that
1394    /// prevents Zed from starting, so you can't run `zed: copy system specs to
1395    /// clipboard`
1396    #[arg(long)]
1397    system_specs: bool,
1398
1399    /// Used for the MCP Server, to remove the need for netcat as a dependency,
1400    /// by having Zed act like netcat communicating over a Unix socket.
1401    #[arg(long, hide = true)]
1402    nc: Option<String>,
1403
1404    /// Used for recording minidumps on crashes by having Zed run a separate
1405    /// process communicating over a socket.
1406    #[arg(long, hide = true)]
1407    crash_handler: Option<PathBuf>,
1408
1409    /// Run zed in the foreground, only used on Windows, to match the behavior on macOS.
1410    #[arg(long)]
1411    #[cfg(target_os = "windows")]
1412    #[arg(hide = true)]
1413    foreground: bool,
1414
1415    /// The dock action to perform. This is used on Windows only.
1416    #[arg(long)]
1417    #[cfg(target_os = "windows")]
1418    #[arg(hide = true)]
1419    dock_action: Option<usize>,
1420
1421    /// Used for SSH/Git password authentication, to remove the need for netcat as a dependency,
1422    /// by having Zed act like netcat communicating over a Unix socket.
1423    #[arg(long)]
1424    #[cfg(not(target_os = "windows"))]
1425    #[arg(hide = true)]
1426    askpass: Option<String>,
1427
1428    #[arg(long, hide = true)]
1429    dump_all_actions: bool,
1430
1431    /// Output current environment variables as JSON to stdout
1432    #[arg(long, hide = true)]
1433    printenv: bool,
1434}
1435
1436#[derive(Clone, Debug)]
1437enum IdType {
1438    New(String),
1439    Existing(String),
1440}
1441
1442impl ToString for IdType {
1443    fn to_string(&self) -> String {
1444        match self {
1445            IdType::New(id) | IdType::Existing(id) => id.clone(),
1446        }
1447    }
1448}
1449
1450fn parse_url_arg(arg: &str, cx: &App) -> String {
1451    match std::fs::canonicalize(Path::new(&arg)) {
1452        Ok(path) => format!("file://{}", path.display()),
1453        Err(_) => {
1454            if arg.starts_with("file://")
1455                || arg.starts_with("zed-cli://")
1456                || arg.starts_with("ssh://")
1457                || parse_zed_link(arg, cx).is_some()
1458            {
1459                arg.into()
1460            } else {
1461                format!("file://{arg}")
1462            }
1463        }
1464    }
1465}
1466
1467fn load_embedded_fonts(cx: &App) {
1468    let asset_source = cx.asset_source();
1469    let font_paths = asset_source.list("fonts").unwrap();
1470    let embedded_fonts = Mutex::new(Vec::new());
1471    let executor = cx.background_executor();
1472
1473    executor.block(executor.scoped(|scope| {
1474        for font_path in &font_paths {
1475            if !font_path.ends_with(".ttf") {
1476                continue;
1477            }
1478
1479            scope.spawn(async {
1480                let font_bytes = asset_source.load(font_path).unwrap().unwrap();
1481                embedded_fonts.lock().push(font_bytes);
1482            });
1483        }
1484    }));
1485
1486    cx.text_system()
1487        .add_fonts(embedded_fonts.into_inner())
1488        .unwrap();
1489}
1490
1491/// Spawns a background task to load the user themes from the themes directory.
1492fn load_user_themes_in_background(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1493    cx.spawn({
1494        let fs = fs.clone();
1495        async move |cx| {
1496            if let Some(theme_registry) = cx.update(|cx| ThemeRegistry::global(cx)).log_err() {
1497                let themes_dir = paths::themes_dir().as_ref();
1498                match fs
1499                    .metadata(themes_dir)
1500                    .await
1501                    .ok()
1502                    .flatten()
1503                    .map(|m| m.is_dir)
1504                {
1505                    Some(is_dir) => {
1506                        anyhow::ensure!(is_dir, "Themes dir path {themes_dir:?} is not a directory")
1507                    }
1508                    None => {
1509                        fs.create_dir(themes_dir).await.with_context(|| {
1510                            format!("Failed to create themes dir at path {themes_dir:?}")
1511                        })?;
1512                    }
1513                }
1514                theme_registry.load_user_themes(themes_dir, fs).await?;
1515                cx.update(GlobalTheme::reload_theme)?;
1516            }
1517            anyhow::Ok(())
1518        }
1519    })
1520    .detach_and_log_err(cx);
1521}
1522
1523/// Spawns a background task to watch the themes directory for changes.
1524fn watch_themes(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1525    use std::time::Duration;
1526    cx.spawn(async move |cx| {
1527        let (mut events, _) = fs
1528            .watch(paths::themes_dir(), Duration::from_millis(100))
1529            .await;
1530
1531        while let Some(paths) = events.next().await {
1532            for event in paths {
1533                if fs.metadata(&event.path).await.ok().flatten().is_some()
1534                    && let Some(theme_registry) =
1535                        cx.update(|cx| ThemeRegistry::global(cx)).log_err()
1536                    && let Some(()) = theme_registry
1537                        .load_user_theme(&event.path, fs.clone())
1538                        .await
1539                        .log_err()
1540                {
1541                    cx.update(GlobalTheme::reload_theme).log_err();
1542                }
1543            }
1544        }
1545    })
1546    .detach()
1547}
1548
1549#[cfg(debug_assertions)]
1550fn watch_languages(fs: Arc<dyn fs::Fs>, languages: Arc<LanguageRegistry>, cx: &mut App) {
1551    use std::time::Duration;
1552
1553    cx.background_spawn(async move {
1554        let languages_src = Path::new("crates/languages/src");
1555        let Some(languages_src) = fs.canonicalize(languages_src).await.log_err() else {
1556            return;
1557        };
1558
1559        let (mut events, watcher) = fs.watch(&languages_src, Duration::from_millis(100)).await;
1560
1561        // add subdirectories since fs.watch is not recursive on Linux
1562        if let Some(mut paths) = fs.read_dir(&languages_src).await.log_err() {
1563            while let Some(path) = paths.next().await {
1564                if let Some(path) = path.log_err()
1565                    && fs.is_dir(&path).await
1566                {
1567                    watcher.add(&path).log_err();
1568                }
1569            }
1570        }
1571
1572        while let Some(event) = events.next().await {
1573            let has_language_file = event
1574                .iter()
1575                .any(|event| event.path.extension().is_some_and(|ext| ext == "scm"));
1576            if has_language_file {
1577                languages.reload();
1578            }
1579        }
1580    })
1581    .detach();
1582}
1583
1584#[cfg(not(debug_assertions))]
1585fn watch_languages(_fs: Arc<dyn fs::Fs>, _languages: Arc<LanguageRegistry>, _cx: &mut App) {}
1586
1587fn dump_all_gpui_actions() {
1588    #[derive(Debug, serde::Serialize)]
1589    struct ActionDef {
1590        name: &'static str,
1591        human_name: String,
1592        deprecated_aliases: &'static [&'static str],
1593        documentation: Option<&'static str>,
1594    }
1595    let mut actions = gpui::generate_list_of_all_registered_actions()
1596        .map(|action| ActionDef {
1597            name: action.name,
1598            human_name: command_palette::humanize_action_name(action.name),
1599            deprecated_aliases: action.deprecated_aliases,
1600            documentation: action.documentation,
1601        })
1602        .collect::<Vec<ActionDef>>();
1603
1604    actions.sort_by_key(|a| a.name);
1605
1606    io::Write::write(
1607        &mut std::io::stdout(),
1608        serde_json::to_string_pretty(&actions).unwrap().as_bytes(),
1609    )
1610    .unwrap();
1611}
1612
1613#[cfg(target_os = "windows")]
1614fn check_for_conpty_dll() {
1615    use windows::{
1616        Win32::{Foundation::FreeLibrary, System::LibraryLoader::LoadLibraryW},
1617        core::w,
1618    };
1619
1620    if let Ok(hmodule) = unsafe { LoadLibraryW(w!("conpty.dll")) } {
1621        unsafe {
1622            FreeLibrary(hmodule)
1623                .context("Failed to free conpty.dll")
1624                .log_err();
1625        }
1626    } else {
1627        log::warn!("Failed to load conpty.dll. Terminal will work with reduced functionality.");
1628    }
1629}