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 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 lsp_store = workspace.update(cx, |workspace, cx| {
837 workspace
838 .project()
839 .update(cx, |project, _| project.lsp_store())
840 })?;
841 let json_schema_content =
842 json_schema_store::resolve_schema_request_inner(
843 &app_state.languages,
844 lsp_store,
845 &schema_path,
846 cx,
847 )
848 .await?;
849 let json_schema_content =
850 serde_json::to_string_pretty(&json_schema_content)
851 .context("Failed to serialize JSON Schema as JSON")?;
852 let buffer_task = workspace.update(cx, |workspace, cx| {
853 workspace
854 .project()
855 .update(cx, |project, cx| project.create_buffer(false, cx))
856 })?;
857
858 let buffer = buffer_task.await?;
859
860 workspace.update_in(cx, |workspace, window, cx| {
861 buffer.update(cx, |buffer, cx| {
862 buffer.set_language(json, cx);
863 buffer.edit([(0..0, json_schema_content)], None, cx);
864 buffer.edit(
865 [(0..0, format!("// {} JSON Schema\n", schema_path))],
866 None,
867 cx,
868 );
869 });
870
871 workspace.add_item_to_active_pane(
872 Box::new(cx.new(|cx| {
873 let mut editor =
874 editor::Editor::for_buffer(buffer, None, window, cx);
875 editor.set_read_only(true);
876 editor
877 })),
878 None,
879 true,
880 window,
881 cx,
882 );
883 })
884 }
885 .await;
886 res.context("Failed to open builtin JSON Schema").log_err();
887 })
888 .detach();
889 });
890 }
891 OpenRequestKind::Setting { setting_path } => {
892 // zed://settings/languages/$(language)/tab_size - DONT SUPPORT
893 // zed://settings/languages/Rust/tab_size - SUPPORT
894 // languages.$(language).tab_size
895 // [ languages $(language) tab_size]
896 cx.spawn(async move |cx| {
897 let workspace =
898 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
899
900 workspace.update(cx, |_, window, cx| match setting_path {
901 None => window.dispatch_action(Box::new(zed_actions::OpenSettings), cx),
902 Some(setting_path) => window.dispatch_action(
903 Box::new(zed_actions::OpenSettingsAt { path: setting_path }),
904 cx,
905 ),
906 })
907 })
908 .detach_and_log_err(cx);
909 }
910 OpenRequestKind::GitClone { repo_url } => {
911 workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
912 if window.is_window_active() {
913 clone_and_open(
914 repo_url,
915 cx.weak_entity(),
916 window,
917 cx,
918 Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
919 workspace.focus_panel::<ProjectPanel>(window, cx);
920 }),
921 );
922 return;
923 }
924
925 let subscription = Rc::new(RefCell::new(None));
926 subscription.replace(Some(cx.observe_in(&cx.entity(), window, {
927 let subscription = subscription.clone();
928 let repo_url = repo_url;
929 move |_, workspace_entity, window, cx| {
930 if window.is_window_active() && subscription.take().is_some() {
931 clone_and_open(
932 repo_url.clone(),
933 workspace_entity.downgrade(),
934 window,
935 cx,
936 Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
937 workspace.focus_panel::<ProjectPanel>(window, cx);
938 }),
939 );
940 }
941 }
942 })));
943 });
944 }
945 OpenRequestKind::GitCommit { sha } => {
946 cx.spawn(async move |cx| {
947 let paths_with_position =
948 derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
949 let (workspace, _results) = open_paths_with_positions(
950 &paths_with_position,
951 &[],
952 app_state,
953 workspace::OpenOptions::default(),
954 cx,
955 )
956 .await?;
957
958 workspace
959 .update(cx, |workspace, window, cx| {
960 let Some(repo) = workspace.project().read(cx).active_repository(cx)
961 else {
962 log::error!("no active repository found for commit view");
963 return Err(anyhow::anyhow!("no active repository found"));
964 };
965
966 git_ui::commit_view::CommitView::open(
967 sha,
968 repo.downgrade(),
969 workspace.weak_handle(),
970 None,
971 None,
972 window,
973 cx,
974 );
975 Ok(())
976 })
977 .log_err();
978
979 anyhow::Ok(())
980 })
981 .detach_and_log_err(cx);
982 }
983 }
984
985 return;
986 }
987
988 if let Some(connection_options) = request.remote_connection {
989 cx.spawn(async move |cx| {
990 let paths: Vec<PathBuf> = request.open_paths.into_iter().map(PathBuf::from).collect();
991 open_remote_project(
992 connection_options,
993 paths,
994 app_state,
995 workspace::OpenOptions::default(),
996 cx,
997 )
998 .await
999 })
1000 .detach_and_log_err(cx);
1001 return;
1002 }
1003
1004 let mut task = None;
1005 if !request.open_paths.is_empty() || !request.diff_paths.is_empty() {
1006 let app_state = app_state.clone();
1007 task = Some(cx.spawn(async move |cx| {
1008 let paths_with_position =
1009 derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
1010 let (_window, results) = open_paths_with_positions(
1011 &paths_with_position,
1012 &request.diff_paths,
1013 app_state,
1014 workspace::OpenOptions::default(),
1015 cx,
1016 )
1017 .await?;
1018 for result in results.into_iter().flatten() {
1019 if let Err(err) = result {
1020 log::error!("Error opening path: {err}",);
1021 }
1022 }
1023 anyhow::Ok(())
1024 }));
1025 }
1026
1027 if !request.open_channel_notes.is_empty() || request.join_channel.is_some() {
1028 cx.spawn(async move |cx| {
1029 let result = maybe!(async {
1030 if let Some(task) = task {
1031 task.await?;
1032 }
1033 let client = app_state.client.clone();
1034 // we continue even if authentication fails as join_channel/ open channel notes will
1035 // show a visible error message.
1036 authenticate(client, cx).await.log_err();
1037
1038 if let Some(channel_id) = request.join_channel {
1039 cx.update(|cx| {
1040 workspace::join_channel(
1041 client::ChannelId(channel_id),
1042 app_state.clone(),
1043 None,
1044 cx,
1045 )
1046 })?
1047 .await?;
1048 }
1049
1050 let workspace_window =
1051 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
1052 let workspace = workspace_window.entity(cx)?;
1053
1054 let mut promises = Vec::new();
1055 for (channel_id, heading) in request.open_channel_notes {
1056 promises.push(cx.update_window(workspace_window.into(), |_, window, cx| {
1057 ChannelView::open(
1058 client::ChannelId(channel_id),
1059 heading,
1060 workspace.clone(),
1061 window,
1062 cx,
1063 )
1064 .log_err()
1065 })?)
1066 }
1067 future::join_all(promises).await;
1068 anyhow::Ok(())
1069 })
1070 .await;
1071 if let Err(err) = result {
1072 fail_to_open_window_async(err, cx);
1073 }
1074 })
1075 .detach()
1076 } else if let Some(task) = task {
1077 cx.spawn(async move |cx| {
1078 if let Err(err) = task.await {
1079 fail_to_open_window_async(err, cx);
1080 }
1081 })
1082 .detach();
1083 }
1084}
1085
1086async fn authenticate(client: Arc<Client>, cx: &AsyncApp) -> Result<()> {
1087 if stdout_is_a_pty() {
1088 if client::IMPERSONATE_LOGIN.is_some() {
1089 client.sign_in_with_optional_connect(false, cx).await?;
1090 } else if client.has_credentials(cx).await {
1091 client.sign_in_with_optional_connect(true, cx).await?;
1092 }
1093 } else if client.has_credentials(cx).await {
1094 client.sign_in_with_optional_connect(true, cx).await?;
1095 }
1096
1097 Ok(())
1098}
1099
1100async fn system_id() -> Result<IdType> {
1101 let key_name = "system_id".to_string();
1102
1103 if let Ok(Some(system_id)) = GLOBAL_KEY_VALUE_STORE.read_kvp(&key_name) {
1104 return Ok(IdType::Existing(system_id));
1105 }
1106
1107 let system_id = Uuid::new_v4().to_string();
1108
1109 GLOBAL_KEY_VALUE_STORE
1110 .write_kvp(key_name, system_id.clone())
1111 .await?;
1112
1113 Ok(IdType::New(system_id))
1114}
1115
1116async fn installation_id() -> Result<IdType> {
1117 let legacy_key_name = "device_id".to_string();
1118 let key_name = "installation_id".to_string();
1119
1120 // Migrate legacy key to new key
1121 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&legacy_key_name) {
1122 KEY_VALUE_STORE
1123 .write_kvp(key_name, installation_id.clone())
1124 .await?;
1125 KEY_VALUE_STORE.delete_kvp(legacy_key_name).await?;
1126 return Ok(IdType::Existing(installation_id));
1127 }
1128
1129 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&key_name) {
1130 return Ok(IdType::Existing(installation_id));
1131 }
1132
1133 let installation_id = Uuid::new_v4().to_string();
1134
1135 KEY_VALUE_STORE
1136 .write_kvp(key_name, installation_id.clone())
1137 .await?;
1138
1139 Ok(IdType::New(installation_id))
1140}
1141
1142async fn restore_or_create_workspace(app_state: Arc<AppState>, cx: &mut AsyncApp) -> Result<()> {
1143 if let Some(locations) = restorable_workspace_locations(cx, &app_state).await {
1144 let use_system_window_tabs = cx
1145 .update(|cx| WorkspaceSettings::get_global(cx).use_system_window_tabs)
1146 .unwrap_or(false);
1147 let mut results: Vec<Result<(), Error>> = Vec::new();
1148 let mut tasks = Vec::new();
1149
1150 for (index, (location, paths)) in locations.into_iter().enumerate() {
1151 match location {
1152 SerializedWorkspaceLocation::Local => {
1153 let app_state = app_state.clone();
1154 let task = cx.spawn(async move |cx| {
1155 let open_task = cx.update(|cx| {
1156 workspace::open_paths(
1157 &paths.paths(),
1158 app_state,
1159 workspace::OpenOptions::default(),
1160 cx,
1161 )
1162 })?;
1163 open_task.await.map(|_| ())
1164 });
1165
1166 // If we're using system window tabs and this is the first workspace,
1167 // wait for it to finish so that the other windows can be added as tabs.
1168 if use_system_window_tabs && index == 0 {
1169 results.push(task.await);
1170 } else {
1171 tasks.push(task);
1172 }
1173 }
1174 SerializedWorkspaceLocation::Remote(mut connection_options) => {
1175 let app_state = app_state.clone();
1176 if let RemoteConnectionOptions::Ssh(options) = &mut connection_options {
1177 cx.update(|cx| {
1178 SshSettings::get_global(cx)
1179 .fill_connection_options_from_settings(options)
1180 })?;
1181 }
1182 let task = cx.spawn(async move |cx| {
1183 recent_projects::open_remote_project(
1184 connection_options,
1185 paths.paths().into_iter().map(PathBuf::from).collect(),
1186 app_state,
1187 workspace::OpenOptions::default(),
1188 cx,
1189 )
1190 .await
1191 .map_err(|e| anyhow::anyhow!(e))
1192 });
1193 tasks.push(task);
1194 }
1195 }
1196 }
1197
1198 // Wait for all workspaces to open concurrently
1199 results.extend(future::join_all(tasks).await);
1200
1201 // Show notifications for any errors that occurred
1202 let mut error_count = 0;
1203 for result in results {
1204 if let Err(e) = result {
1205 log::error!("Failed to restore workspace: {}", e);
1206 error_count += 1;
1207 }
1208 }
1209
1210 if error_count > 0 {
1211 let message = if error_count == 1 {
1212 "Failed to restore 1 workspace. Check logs for details.".to_string()
1213 } else {
1214 format!(
1215 "Failed to restore {} workspaces. Check logs for details.",
1216 error_count
1217 )
1218 };
1219
1220 // Try to find an active workspace to show the toast
1221 let toast_shown = cx
1222 .update(|cx| {
1223 if let Some(window) = cx.active_window()
1224 && let Some(workspace) = window.downcast::<Workspace>()
1225 {
1226 workspace
1227 .update(cx, |workspace, _, cx| {
1228 workspace.show_toast(
1229 Toast::new(NotificationId::unique::<()>(), message),
1230 cx,
1231 )
1232 })
1233 .ok();
1234 return true;
1235 }
1236 false
1237 })
1238 .unwrap_or(false);
1239
1240 // If we couldn't show a toast (no windows opened successfully),
1241 // we've already logged the errors above, so the user can check logs
1242 if !toast_shown {
1243 log::error!(
1244 "Failed to show notification for window restoration errors, because no workspace windows were available."
1245 );
1246 }
1247 }
1248 } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
1249 cx.update(|cx| show_onboarding_view(app_state, cx))?.await?;
1250 } else {
1251 cx.update(|cx| {
1252 workspace::open_new(
1253 Default::default(),
1254 app_state,
1255 cx,
1256 |workspace, window, cx| {
1257 let restore_on_startup = WorkspaceSettings::get_global(cx).restore_on_startup;
1258 match restore_on_startup {
1259 workspace::RestoreOnStartupBehavior::Launchpad => {}
1260 _ => {
1261 Editor::new_file(workspace, &Default::default(), window, cx);
1262 }
1263 }
1264 },
1265 )
1266 })?
1267 .await?;
1268 }
1269
1270 Ok(())
1271}
1272
1273pub(crate) async fn restorable_workspace_locations(
1274 cx: &mut AsyncApp,
1275 app_state: &Arc<AppState>,
1276) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
1277 let mut restore_behavior = cx
1278 .update(|cx| WorkspaceSettings::get(None, cx).restore_on_startup)
1279 .ok()?;
1280
1281 let session_handle = app_state.session.clone();
1282 let (last_session_id, last_session_window_stack) = cx
1283 .update(|cx| {
1284 let session = session_handle.read(cx);
1285
1286 (
1287 session.last_session_id().map(|id| id.to_string()),
1288 session.last_session_window_stack(),
1289 )
1290 })
1291 .ok()?;
1292
1293 if last_session_id.is_none()
1294 && matches!(
1295 restore_behavior,
1296 workspace::RestoreOnStartupBehavior::LastSession
1297 )
1298 {
1299 restore_behavior = workspace::RestoreOnStartupBehavior::LastWorkspace;
1300 }
1301
1302 match restore_behavior {
1303 workspace::RestoreOnStartupBehavior::LastWorkspace => {
1304 workspace::last_opened_workspace_location()
1305 .await
1306 .map(|location| vec![location])
1307 }
1308 workspace::RestoreOnStartupBehavior::LastSession => {
1309 if let Some(last_session_id) = last_session_id {
1310 let ordered = last_session_window_stack.is_some();
1311
1312 let mut locations = workspace::last_session_workspace_locations(
1313 &last_session_id,
1314 last_session_window_stack,
1315 )
1316 .filter(|locations| !locations.is_empty());
1317
1318 // Since last_session_window_order returns the windows ordered front-to-back
1319 // we need to open the window that was frontmost last.
1320 if ordered && let Some(locations) = locations.as_mut() {
1321 locations.reverse();
1322 }
1323
1324 locations
1325 } else {
1326 None
1327 }
1328 }
1329 _ => None,
1330 }
1331}
1332
1333fn init_paths() -> HashMap<io::ErrorKind, Vec<&'static Path>> {
1334 [
1335 paths::config_dir(),
1336 paths::extensions_dir(),
1337 paths::languages_dir(),
1338 paths::debug_adapters_dir(),
1339 paths::database_dir(),
1340 paths::logs_dir(),
1341 paths::temp_dir(),
1342 paths::hang_traces_dir(),
1343 ]
1344 .into_iter()
1345 .fold(HashMap::default(), |mut errors, path| {
1346 if let Err(e) = std::fs::create_dir_all(path) {
1347 errors.entry(e.kind()).or_insert_with(Vec::new).push(path);
1348 }
1349 errors
1350 })
1351}
1352
1353fn stdout_is_a_pty() -> bool {
1354 std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && io::stdout().is_terminal()
1355}
1356
1357#[derive(Parser, Debug)]
1358#[command(name = "zed", disable_version_flag = true, max_term_width = 100)]
1359struct Args {
1360 /// A sequence of space-separated paths or urls that you want to open.
1361 ///
1362 /// Use `path:line:row` syntax to open a file at a specific location.
1363 /// Non-existing paths and directories will ignore `:line:row` suffix.
1364 ///
1365 /// URLs can either be `file://` or `zed://` scheme, or relative to <https://zed.dev>.
1366 paths_or_urls: Vec<String>,
1367
1368 /// Pairs of file paths to diff. Can be specified multiple times.
1369 #[arg(long, action = clap::ArgAction::Append, num_args = 2, value_names = ["OLD_PATH", "NEW_PATH"])]
1370 diff: Vec<String>,
1371
1372 /// Sets a custom directory for all user data (e.g., database, extensions, logs).
1373 ///
1374 /// This overrides the default platform-specific data directory location.
1375 /// On macOS, the default is `~/Library/Application Support/Zed`.
1376 /// On Linux/FreeBSD, the default is `$XDG_DATA_HOME/zed`.
1377 /// On Windows, the default is `%LOCALAPPDATA%\Zed`.
1378 #[arg(long, value_name = "DIR", verbatim_doc_comment)]
1379 user_data_dir: Option<String>,
1380
1381 /// The username and WSL distribution to use when opening paths. If not specified,
1382 /// Zed will attempt to open the paths directly.
1383 ///
1384 /// The username is optional, and if not specified, the default user for the distribution
1385 /// will be used.
1386 ///
1387 /// Example: `me@Ubuntu` or `Ubuntu`.
1388 ///
1389 /// WARN: You should not fill in this field by hand.
1390 #[cfg(target_os = "windows")]
1391 #[arg(long, value_name = "USER@DISTRO")]
1392 wsl: Option<String>,
1393
1394 /// Instructs zed to run as a dev server on this machine. (not implemented)
1395 #[arg(long)]
1396 dev_server_token: Option<String>,
1397
1398 /// Prints system specs.
1399 ///
1400 /// Useful for submitting issues on GitHub when encountering a bug that
1401 /// prevents Zed from starting, so you can't run `zed: copy system specs to
1402 /// clipboard`
1403 #[arg(long)]
1404 system_specs: bool,
1405
1406 /// Used for the MCP Server, to remove the need for netcat as a dependency,
1407 /// by having Zed act like netcat communicating over a Unix socket.
1408 #[arg(long, hide = true)]
1409 nc: Option<String>,
1410
1411 /// Used for recording minidumps on crashes by having Zed run a separate
1412 /// process communicating over a socket.
1413 #[arg(long, hide = true)]
1414 crash_handler: Option<PathBuf>,
1415
1416 /// Run zed in the foreground, only used on Windows, to match the behavior on macOS.
1417 #[arg(long)]
1418 #[cfg(target_os = "windows")]
1419 #[arg(hide = true)]
1420 foreground: bool,
1421
1422 /// The dock action to perform. This is used on Windows only.
1423 #[arg(long)]
1424 #[cfg(target_os = "windows")]
1425 #[arg(hide = true)]
1426 dock_action: Option<usize>,
1427
1428 /// Used for SSH/Git password authentication, to remove the need for netcat as a dependency,
1429 /// by having Zed act like netcat communicating over a Unix socket.
1430 #[arg(long)]
1431 #[cfg(not(target_os = "windows"))]
1432 #[arg(hide = true)]
1433 askpass: Option<String>,
1434
1435 #[arg(long, hide = true)]
1436 dump_all_actions: bool,
1437
1438 /// Output current environment variables as JSON to stdout
1439 #[arg(long, hide = true)]
1440 printenv: bool,
1441}
1442
1443#[derive(Clone, Debug)]
1444enum IdType {
1445 New(String),
1446 Existing(String),
1447}
1448
1449impl ToString for IdType {
1450 fn to_string(&self) -> String {
1451 match self {
1452 IdType::New(id) | IdType::Existing(id) => id.clone(),
1453 }
1454 }
1455}
1456
1457fn parse_url_arg(arg: &str, cx: &App) -> String {
1458 match std::fs::canonicalize(Path::new(&arg)) {
1459 Ok(path) => format!("file://{}", path.display()),
1460 Err(_) => {
1461 if arg.starts_with("file://")
1462 || arg.starts_with("zed-cli://")
1463 || arg.starts_with("ssh://")
1464 || parse_zed_link(arg, cx).is_some()
1465 {
1466 arg.into()
1467 } else {
1468 format!("file://{arg}")
1469 }
1470 }
1471 }
1472}
1473
1474fn load_embedded_fonts(cx: &App) {
1475 let asset_source = cx.asset_source();
1476 let font_paths = asset_source.list("fonts").unwrap();
1477 let embedded_fonts = Mutex::new(Vec::new());
1478 let executor = cx.background_executor();
1479
1480 executor.block(executor.scoped(|scope| {
1481 for font_path in &font_paths {
1482 if !font_path.ends_with(".ttf") {
1483 continue;
1484 }
1485
1486 scope.spawn(async {
1487 let font_bytes = asset_source.load(font_path).unwrap().unwrap();
1488 embedded_fonts.lock().push(font_bytes);
1489 });
1490 }
1491 }));
1492
1493 cx.text_system()
1494 .add_fonts(embedded_fonts.into_inner())
1495 .unwrap();
1496}
1497
1498/// Spawns a background task to load the user themes from the themes directory.
1499fn load_user_themes_in_background(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1500 cx.spawn({
1501 let fs = fs.clone();
1502 async move |cx| {
1503 if let Some(theme_registry) = cx.update(|cx| ThemeRegistry::global(cx)).log_err() {
1504 let themes_dir = paths::themes_dir().as_ref();
1505 match fs
1506 .metadata(themes_dir)
1507 .await
1508 .ok()
1509 .flatten()
1510 .map(|m| m.is_dir)
1511 {
1512 Some(is_dir) => {
1513 anyhow::ensure!(is_dir, "Themes dir path {themes_dir:?} is not a directory")
1514 }
1515 None => {
1516 fs.create_dir(themes_dir).await.with_context(|| {
1517 format!("Failed to create themes dir at path {themes_dir:?}")
1518 })?;
1519 }
1520 }
1521 theme_registry.load_user_themes(themes_dir, fs).await?;
1522 cx.update(GlobalTheme::reload_theme)?;
1523 }
1524 anyhow::Ok(())
1525 }
1526 })
1527 .detach_and_log_err(cx);
1528}
1529
1530/// Spawns a background task to watch the themes directory for changes.
1531fn watch_themes(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1532 use std::time::Duration;
1533 cx.spawn(async move |cx| {
1534 let (mut events, _) = fs
1535 .watch(paths::themes_dir(), Duration::from_millis(100))
1536 .await;
1537
1538 while let Some(paths) = events.next().await {
1539 for event in paths {
1540 if fs.metadata(&event.path).await.ok().flatten().is_some()
1541 && let Some(theme_registry) =
1542 cx.update(|cx| ThemeRegistry::global(cx)).log_err()
1543 && let Some(()) = theme_registry
1544 .load_user_theme(&event.path, fs.clone())
1545 .await
1546 .log_err()
1547 {
1548 cx.update(GlobalTheme::reload_theme).log_err();
1549 }
1550 }
1551 }
1552 })
1553 .detach()
1554}
1555
1556#[cfg(debug_assertions)]
1557fn watch_languages(fs: Arc<dyn fs::Fs>, languages: Arc<LanguageRegistry>, cx: &mut App) {
1558 use std::time::Duration;
1559
1560 cx.background_spawn(async move {
1561 let languages_src = Path::new("crates/languages/src");
1562 let Some(languages_src) = fs.canonicalize(languages_src).await.log_err() else {
1563 return;
1564 };
1565
1566 let (mut events, watcher) = fs.watch(&languages_src, Duration::from_millis(100)).await;
1567
1568 // add subdirectories since fs.watch is not recursive on Linux
1569 if let Some(mut paths) = fs.read_dir(&languages_src).await.log_err() {
1570 while let Some(path) = paths.next().await {
1571 if let Some(path) = path.log_err()
1572 && fs.is_dir(&path).await
1573 {
1574 watcher.add(&path).log_err();
1575 }
1576 }
1577 }
1578
1579 while let Some(event) = events.next().await {
1580 let has_language_file = event
1581 .iter()
1582 .any(|event| event.path.extension().is_some_and(|ext| ext == "scm"));
1583 if has_language_file {
1584 languages.reload();
1585 }
1586 }
1587 })
1588 .detach();
1589}
1590
1591#[cfg(not(debug_assertions))]
1592fn watch_languages(_fs: Arc<dyn fs::Fs>, _languages: Arc<LanguageRegistry>, _cx: &mut App) {}
1593
1594fn dump_all_gpui_actions() {
1595 #[derive(Debug, serde::Serialize)]
1596 struct ActionDef {
1597 name: &'static str,
1598 human_name: String,
1599 deprecated_aliases: &'static [&'static str],
1600 documentation: Option<&'static str>,
1601 }
1602 let mut actions = gpui::generate_list_of_all_registered_actions()
1603 .map(|action| ActionDef {
1604 name: action.name,
1605 human_name: command_palette::humanize_action_name(action.name),
1606 deprecated_aliases: action.deprecated_aliases,
1607 documentation: action.documentation,
1608 })
1609 .collect::<Vec<ActionDef>>();
1610
1611 actions.sort_by_key(|a| a.name);
1612
1613 io::Write::write(
1614 &mut std::io::stdout(),
1615 serde_json::to_string_pretty(&actions).unwrap().as_bytes(),
1616 )
1617 .unwrap();
1618}
1619
1620#[cfg(target_os = "windows")]
1621fn check_for_conpty_dll() {
1622 use windows::{
1623 Win32::{Foundation::FreeLibrary, System::LibraryLoader::LoadLibraryW},
1624 core::w,
1625 };
1626
1627 if let Ok(hmodule) = unsafe { LoadLibraryW(w!("conpty.dll")) } {
1628 unsafe {
1629 FreeLibrary(hmodule)
1630 .context("Failed to free conpty.dll")
1631 .log_err();
1632 }
1633 } else {
1634 log::warn!("Failed to load conpty.dll. Terminal will work with reduced functionality.");
1635 }
1636}