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 // Initialize the language model registry first, then set up the extension proxy
575 // BEFORE extension_host::init so that extensions can register their LLM providers
576 // when they load.
577 language_model::init(app_state.client.clone(), cx);
578 language_models::init_extension_proxy(cx);
579 extension_host::init(
580 extension_host_proxy.clone(),
581 app_state.fs.clone(),
582 app_state.client.clone(),
583 app_state.node_runtime.clone(),
584 cx,
585 );
586
587 theme::init(theme::LoadThemes::All(Box::new(Assets)), cx);
588 eager_load_active_theme_and_icon_theme(fs.clone(), cx);
589 theme_extension::init(
590 extension_host_proxy,
591 ThemeRegistry::global(cx),
592 cx.background_executor().clone(),
593 );
594 command_palette::init(cx);
595 let copilot_language_server_id = app_state.languages.next_language_server_id();
596 copilot::init(
597 copilot_language_server_id,
598 app_state.fs.clone(),
599 app_state.client.http_client(),
600 app_state.node_runtime.clone(),
601 cx,
602 );
603 supermaven::init(app_state.client.clone(), cx);
604 language_models::init(app_state.user_store.clone(), app_state.client.clone(), cx);
605 acp_tools::init(cx);
606 edit_prediction_ui::init(cx);
607 web_search::init(cx);
608 web_search_providers::init(app_state.client.clone(), cx);
609 snippet_provider::init(cx);
610 edit_prediction_registry::init(app_state.client.clone(), app_state.user_store.clone(), cx);
611 let prompt_builder = PromptBuilder::load(app_state.fs.clone(), stdout_is_a_pty(), cx);
612 agent_ui::init(
613 app_state.fs.clone(),
614 app_state.client.clone(),
615 prompt_builder.clone(),
616 app_state.languages.clone(),
617 false,
618 cx,
619 );
620 agent_ui_v2::agents_panel::init(cx);
621 repl::init(app_state.fs.clone(), cx);
622 recent_projects::init(cx);
623
624 load_embedded_fonts(cx);
625
626 editor::init(cx);
627 image_viewer::init(cx);
628 repl::notebook::init(cx);
629 diagnostics::init(cx);
630
631 audio::init(cx);
632 workspace::init(app_state.clone(), cx);
633 ui_prompt::init(cx);
634
635 go_to_line::init(cx);
636 file_finder::init(cx);
637 tab_switcher::init(cx);
638 outline::init(cx);
639 project_symbols::init(cx);
640 project_panel::init(cx);
641 outline_panel::init(cx);
642 tasks_ui::init(cx);
643 snippets_ui::init(cx);
644 channel::init(&app_state.client.clone(), app_state.user_store.clone(), cx);
645 search::init(cx);
646 vim::init(cx);
647 terminal_view::init(cx);
648 journal::init(app_state.clone(), cx);
649 language_selector::init(cx);
650 line_ending_selector::init(cx);
651 toolchain_selector::init(cx);
652 theme_selector::init(cx);
653 settings_profile_selector::init(cx);
654 language_tools::init(cx);
655 call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
656 notifications::init(app_state.client.clone(), app_state.user_store.clone(), cx);
657 collab_ui::init(&app_state, cx);
658 git_ui::init(cx);
659 feedback::init(cx);
660 markdown_preview::init(cx);
661 svg_preview::init(cx);
662 onboarding::init(cx);
663 settings_ui::init(cx);
664 keymap_editor::init(cx);
665 extensions_ui::init(cx);
666 edit_prediction::init(cx);
667 inspector_ui::init(app_state.clone(), cx);
668 json_schema_store::init(cx);
669 miniprofiler_ui::init(*STARTUP_TIME.get().unwrap(), cx);
670 which_key::init(cx);
671
672 cx.observe_global::<SettingsStore>({
673 let http = app_state.client.http_client();
674 let client = app_state.client.clone();
675 move |cx| {
676 for &mut window in cx.windows().iter_mut() {
677 let background_appearance = cx.theme().window_background_appearance();
678 window
679 .update(cx, |_, window, _| {
680 window.set_background_appearance(background_appearance)
681 })
682 .ok();
683 }
684
685 let new_host = &client::ClientSettings::get_global(cx).server_url;
686 if &http.base_url() != new_host {
687 http.set_base_url(new_host);
688 if client.status().borrow().is_connected() {
689 client.reconnect(&cx.to_async());
690 }
691 }
692 }
693 })
694 .detach();
695 app_state.languages.set_theme(cx.theme().clone());
696 cx.observe_global::<GlobalTheme>({
697 let languages = app_state.languages.clone();
698 move |cx| {
699 languages.set_theme(cx.theme().clone());
700 }
701 })
702 .detach();
703 telemetry::event!(
704 "Settings Changed",
705 setting = "theme",
706 value = cx.theme().name.to_string()
707 );
708 telemetry::event!(
709 "Settings Changed",
710 setting = "keymap",
711 value = BaseKeymap::get_global(cx).to_string()
712 );
713 telemetry.flush_events().detach();
714
715 let fs = app_state.fs.clone();
716 load_user_themes_in_background(fs.clone(), cx);
717 watch_themes(fs.clone(), cx);
718 watch_languages(fs.clone(), app_state.languages.clone(), cx);
719
720 let menus = app_menus(cx);
721 cx.set_menus(menus);
722 initialize_workspace(app_state.clone(), prompt_builder, cx);
723
724 cx.activate(true);
725
726 cx.spawn({
727 let client = app_state.client.clone();
728 async move |cx| authenticate(client, cx).await
729 })
730 .detach_and_log_err(cx);
731
732 let urls: Vec<_> = args
733 .paths_or_urls
734 .iter()
735 .map(|arg| parse_url_arg(arg, cx))
736 .collect();
737
738 let diff_paths: Vec<[String; 2]> = args
739 .diff
740 .chunks(2)
741 .map(|chunk| [chunk[0].clone(), chunk[1].clone()])
742 .collect();
743
744 #[cfg(target_os = "windows")]
745 let wsl = args.wsl;
746 #[cfg(not(target_os = "windows"))]
747 let wsl = None;
748
749 if !urls.is_empty() || !diff_paths.is_empty() {
750 open_listener.open(RawOpenRequest {
751 urls,
752 diff_paths,
753 wsl,
754 })
755 }
756
757 match open_rx
758 .try_next()
759 .ok()
760 .flatten()
761 .and_then(|request| OpenRequest::parse(request, cx).log_err())
762 {
763 Some(request) => {
764 handle_open_request(request, app_state.clone(), cx);
765 }
766 None => {
767 cx.spawn({
768 let app_state = app_state.clone();
769 async move |cx| {
770 if let Err(e) = restore_or_create_workspace(app_state, cx).await {
771 fail_to_open_window_async(e, cx)
772 }
773 }
774 })
775 .detach();
776 }
777 }
778
779 let app_state = app_state.clone();
780
781 crate::zed::component_preview::init(app_state.clone(), cx);
782
783 cx.spawn(async move |cx| {
784 while let Some(urls) = open_rx.next().await {
785 cx.update(|cx| {
786 if let Some(request) = OpenRequest::parse(urls, cx).log_err() {
787 handle_open_request(request, app_state.clone(), cx);
788 }
789 })
790 .ok();
791 }
792 })
793 .detach();
794 });
795}
796
797fn handle_open_request(request: OpenRequest, app_state: Arc<AppState>, cx: &mut App) {
798 if let Some(kind) = request.kind {
799 match kind {
800 OpenRequestKind::CliConnection(connection) => {
801 cx.spawn(async move |cx| handle_cli_connection(connection, app_state, cx).await)
802 .detach();
803 }
804 OpenRequestKind::Extension { extension_id } => {
805 cx.spawn(async move |cx| {
806 let workspace =
807 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
808 workspace.update(cx, |_, window, cx| {
809 window.dispatch_action(
810 Box::new(zed_actions::Extensions {
811 category_filter: None,
812 id: Some(extension_id),
813 }),
814 cx,
815 );
816 })
817 })
818 .detach_and_log_err(cx);
819 }
820 OpenRequestKind::AgentPanel => {
821 cx.spawn(async move |cx| {
822 let workspace =
823 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
824 workspace.update(cx, |workspace, window, cx| {
825 if let Some(panel) = workspace.panel::<AgentPanel>(cx) {
826 panel.focus_handle(cx).focus(window, cx);
827 }
828 })
829 })
830 .detach_and_log_err(cx);
831 }
832 OpenRequestKind::DockMenuAction { index } => {
833 cx.perform_dock_menu_action(index);
834 }
835 OpenRequestKind::BuiltinJsonSchema { schema_path } => {
836 workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
837 cx.spawn_in(window, async move |workspace, cx| {
838 let res = async move {
839 let json = app_state.languages.language_for_name("JSONC").await.ok();
840 let json_schema_content =
841 json_schema_store::resolve_schema_request_inner(
842 &app_state.languages,
843 &schema_path,
844 cx,
845 )?;
846 let json_schema_content =
847 serde_json::to_string_pretty(&json_schema_content)
848 .context("Failed to serialize JSON Schema as JSON")?;
849 let buffer_task = workspace.update(cx, |workspace, cx| {
850 workspace
851 .project()
852 .update(cx, |project, cx| project.create_buffer(false, cx))
853 })?;
854
855 let buffer = buffer_task.await?;
856
857 workspace.update_in(cx, |workspace, window, cx| {
858 buffer.update(cx, |buffer, cx| {
859 buffer.set_language(json, cx);
860 buffer.edit([(0..0, json_schema_content)], None, cx);
861 buffer.edit(
862 [(0..0, format!("// {} JSON Schema\n", schema_path))],
863 None,
864 cx,
865 );
866 });
867
868 workspace.add_item_to_active_pane(
869 Box::new(cx.new(|cx| {
870 let mut editor =
871 editor::Editor::for_buffer(buffer, None, window, cx);
872 editor.set_read_only(true);
873 editor
874 })),
875 None,
876 true,
877 window,
878 cx,
879 );
880 })
881 }
882 .await;
883 res.context("Failed to open builtin JSON Schema").log_err();
884 })
885 .detach();
886 });
887 }
888 OpenRequestKind::Setting { setting_path } => {
889 // zed://settings/languages/$(language)/tab_size - DONT SUPPORT
890 // zed://settings/languages/Rust/tab_size - SUPPORT
891 // languages.$(language).tab_size
892 // [ languages $(language) tab_size]
893 cx.spawn(async move |cx| {
894 let workspace =
895 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
896
897 workspace.update(cx, |_, window, cx| match setting_path {
898 None => window.dispatch_action(Box::new(zed_actions::OpenSettings), cx),
899 Some(setting_path) => window.dispatch_action(
900 Box::new(zed_actions::OpenSettingsAt { path: setting_path }),
901 cx,
902 ),
903 })
904 })
905 .detach_and_log_err(cx);
906 }
907 OpenRequestKind::GitClone { repo_url } => {
908 workspace::with_active_or_new_workspace(cx, |_workspace, window, cx| {
909 if window.is_window_active() {
910 clone_and_open(
911 repo_url,
912 cx.weak_entity(),
913 window,
914 cx,
915 Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
916 workspace.focus_panel::<ProjectPanel>(window, cx);
917 }),
918 );
919 return;
920 }
921
922 let subscription = Rc::new(RefCell::new(None));
923 subscription.replace(Some(cx.observe_in(&cx.entity(), window, {
924 let subscription = subscription.clone();
925 let repo_url = repo_url;
926 move |_, workspace_entity, window, cx| {
927 if window.is_window_active() && subscription.take().is_some() {
928 clone_and_open(
929 repo_url.clone(),
930 workspace_entity.downgrade(),
931 window,
932 cx,
933 Arc::new(|workspace: &mut workspace::Workspace, window, cx| {
934 workspace.focus_panel::<ProjectPanel>(window, cx);
935 }),
936 );
937 }
938 }
939 })));
940 });
941 }
942 OpenRequestKind::GitCommit { sha } => {
943 cx.spawn(async move |cx| {
944 let paths_with_position =
945 derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
946 let (workspace, _results) = open_paths_with_positions(
947 &paths_with_position,
948 &[],
949 app_state,
950 workspace::OpenOptions::default(),
951 cx,
952 )
953 .await?;
954
955 workspace
956 .update(cx, |workspace, window, cx| {
957 let Some(repo) = workspace.project().read(cx).active_repository(cx)
958 else {
959 log::error!("no active repository found for commit view");
960 return Err(anyhow::anyhow!("no active repository found"));
961 };
962
963 git_ui::commit_view::CommitView::open(
964 sha,
965 repo.downgrade(),
966 workspace.weak_handle(),
967 None,
968 None,
969 window,
970 cx,
971 );
972 Ok(())
973 })
974 .log_err();
975
976 anyhow::Ok(())
977 })
978 .detach_and_log_err(cx);
979 }
980 }
981
982 return;
983 }
984
985 if let Some(connection_options) = request.remote_connection {
986 cx.spawn(async move |cx| {
987 let paths: Vec<PathBuf> = request.open_paths.into_iter().map(PathBuf::from).collect();
988 open_remote_project(
989 connection_options,
990 paths,
991 app_state,
992 workspace::OpenOptions::default(),
993 cx,
994 )
995 .await
996 })
997 .detach_and_log_err(cx);
998 return;
999 }
1000
1001 let mut task = None;
1002 if !request.open_paths.is_empty() || !request.diff_paths.is_empty() {
1003 let app_state = app_state.clone();
1004 task = Some(cx.spawn(async move |cx| {
1005 let paths_with_position =
1006 derive_paths_with_position(app_state.fs.as_ref(), request.open_paths).await;
1007 let (_window, results) = open_paths_with_positions(
1008 &paths_with_position,
1009 &request.diff_paths,
1010 app_state,
1011 workspace::OpenOptions::default(),
1012 cx,
1013 )
1014 .await?;
1015 for result in results.into_iter().flatten() {
1016 if let Err(err) = result {
1017 log::error!("Error opening path: {err}",);
1018 }
1019 }
1020 anyhow::Ok(())
1021 }));
1022 }
1023
1024 if !request.open_channel_notes.is_empty() || request.join_channel.is_some() {
1025 cx.spawn(async move |cx| {
1026 let result = maybe!(async {
1027 if let Some(task) = task {
1028 task.await?;
1029 }
1030 let client = app_state.client.clone();
1031 // we continue even if authentication fails as join_channel/ open channel notes will
1032 // show a visible error message.
1033 authenticate(client, cx).await.log_err();
1034
1035 if let Some(channel_id) = request.join_channel {
1036 cx.update(|cx| {
1037 workspace::join_channel(
1038 client::ChannelId(channel_id),
1039 app_state.clone(),
1040 None,
1041 cx,
1042 )
1043 })?
1044 .await?;
1045 }
1046
1047 let workspace_window =
1048 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
1049 let workspace = workspace_window.entity(cx)?;
1050
1051 let mut promises = Vec::new();
1052 for (channel_id, heading) in request.open_channel_notes {
1053 promises.push(cx.update_window(workspace_window.into(), |_, window, cx| {
1054 ChannelView::open(
1055 client::ChannelId(channel_id),
1056 heading,
1057 workspace.clone(),
1058 window,
1059 cx,
1060 )
1061 .log_err()
1062 })?)
1063 }
1064 future::join_all(promises).await;
1065 anyhow::Ok(())
1066 })
1067 .await;
1068 if let Err(err) = result {
1069 fail_to_open_window_async(err, cx);
1070 }
1071 })
1072 .detach()
1073 } else if let Some(task) = task {
1074 cx.spawn(async move |cx| {
1075 if let Err(err) = task.await {
1076 fail_to_open_window_async(err, cx);
1077 }
1078 })
1079 .detach();
1080 }
1081}
1082
1083async fn authenticate(client: Arc<Client>, cx: &AsyncApp) -> Result<()> {
1084 if stdout_is_a_pty() {
1085 if client::IMPERSONATE_LOGIN.is_some() {
1086 client.sign_in_with_optional_connect(false, cx).await?;
1087 } else if client.has_credentials(cx).await {
1088 client.sign_in_with_optional_connect(true, cx).await?;
1089 }
1090 } else if client.has_credentials(cx).await {
1091 client.sign_in_with_optional_connect(true, cx).await?;
1092 }
1093
1094 Ok(())
1095}
1096
1097async fn system_id() -> Result<IdType> {
1098 let key_name = "system_id".to_string();
1099
1100 if let Ok(Some(system_id)) = GLOBAL_KEY_VALUE_STORE.read_kvp(&key_name) {
1101 return Ok(IdType::Existing(system_id));
1102 }
1103
1104 let system_id = Uuid::new_v4().to_string();
1105
1106 GLOBAL_KEY_VALUE_STORE
1107 .write_kvp(key_name, system_id.clone())
1108 .await?;
1109
1110 Ok(IdType::New(system_id))
1111}
1112
1113async fn installation_id() -> Result<IdType> {
1114 let legacy_key_name = "device_id".to_string();
1115 let key_name = "installation_id".to_string();
1116
1117 // Migrate legacy key to new key
1118 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&legacy_key_name) {
1119 KEY_VALUE_STORE
1120 .write_kvp(key_name, installation_id.clone())
1121 .await?;
1122 KEY_VALUE_STORE.delete_kvp(legacy_key_name).await?;
1123 return Ok(IdType::Existing(installation_id));
1124 }
1125
1126 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&key_name) {
1127 return Ok(IdType::Existing(installation_id));
1128 }
1129
1130 let installation_id = Uuid::new_v4().to_string();
1131
1132 KEY_VALUE_STORE
1133 .write_kvp(key_name, installation_id.clone())
1134 .await?;
1135
1136 Ok(IdType::New(installation_id))
1137}
1138
1139async fn restore_or_create_workspace(app_state: Arc<AppState>, cx: &mut AsyncApp) -> Result<()> {
1140 if let Some(locations) = restorable_workspace_locations(cx, &app_state).await {
1141 let use_system_window_tabs = cx
1142 .update(|cx| WorkspaceSettings::get_global(cx).use_system_window_tabs)
1143 .unwrap_or(false);
1144 let mut results: Vec<Result<(), Error>> = Vec::new();
1145 let mut tasks = Vec::new();
1146
1147 for (index, (location, paths)) in locations.into_iter().enumerate() {
1148 match location {
1149 SerializedWorkspaceLocation::Local => {
1150 let app_state = app_state.clone();
1151 let task = cx.spawn(async move |cx| {
1152 let open_task = cx.update(|cx| {
1153 workspace::open_paths(
1154 &paths.paths(),
1155 app_state,
1156 workspace::OpenOptions::default(),
1157 cx,
1158 )
1159 })?;
1160 open_task.await.map(|_| ())
1161 });
1162
1163 // If we're using system window tabs and this is the first workspace,
1164 // wait for it to finish so that the other windows can be added as tabs.
1165 if use_system_window_tabs && index == 0 {
1166 results.push(task.await);
1167 } else {
1168 tasks.push(task);
1169 }
1170 }
1171 SerializedWorkspaceLocation::Remote(mut connection_options) => {
1172 let app_state = app_state.clone();
1173 if let RemoteConnectionOptions::Ssh(options) = &mut connection_options {
1174 cx.update(|cx| {
1175 SshSettings::get_global(cx)
1176 .fill_connection_options_from_settings(options)
1177 })?;
1178 }
1179 let task = cx.spawn(async move |cx| {
1180 recent_projects::open_remote_project(
1181 connection_options,
1182 paths.paths().into_iter().map(PathBuf::from).collect(),
1183 app_state,
1184 workspace::OpenOptions::default(),
1185 cx,
1186 )
1187 .await
1188 .map_err(|e| anyhow::anyhow!(e))
1189 });
1190 tasks.push(task);
1191 }
1192 }
1193 }
1194
1195 // Wait for all workspaces to open concurrently
1196 results.extend(future::join_all(tasks).await);
1197
1198 // Show notifications for any errors that occurred
1199 let mut error_count = 0;
1200 for result in results {
1201 if let Err(e) = result {
1202 log::error!("Failed to restore workspace: {}", e);
1203 error_count += 1;
1204 }
1205 }
1206
1207 if error_count > 0 {
1208 let message = if error_count == 1 {
1209 "Failed to restore 1 workspace. Check logs for details.".to_string()
1210 } else {
1211 format!(
1212 "Failed to restore {} workspaces. Check logs for details.",
1213 error_count
1214 )
1215 };
1216
1217 // Try to find an active workspace to show the toast
1218 let toast_shown = cx
1219 .update(|cx| {
1220 if let Some(window) = cx.active_window()
1221 && let Some(workspace) = window.downcast::<Workspace>()
1222 {
1223 workspace
1224 .update(cx, |workspace, _, cx| {
1225 workspace.show_toast(
1226 Toast::new(NotificationId::unique::<()>(), message),
1227 cx,
1228 )
1229 })
1230 .ok();
1231 return true;
1232 }
1233 false
1234 })
1235 .unwrap_or(false);
1236
1237 // If we couldn't show a toast (no windows opened successfully),
1238 // we've already logged the errors above, so the user can check logs
1239 if !toast_shown {
1240 log::error!(
1241 "Failed to show notification for window restoration errors, because no workspace windows were available."
1242 );
1243 }
1244 }
1245 } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
1246 cx.update(|cx| show_onboarding_view(app_state, cx))?.await?;
1247 } else {
1248 cx.update(|cx| {
1249 workspace::open_new(
1250 Default::default(),
1251 app_state,
1252 cx,
1253 |workspace, window, cx| {
1254 let restore_on_startup = WorkspaceSettings::get_global(cx).restore_on_startup;
1255 match restore_on_startup {
1256 workspace::RestoreOnStartupBehavior::Launchpad => {}
1257 _ => {
1258 Editor::new_file(workspace, &Default::default(), window, cx);
1259 }
1260 }
1261 },
1262 )
1263 })?
1264 .await?;
1265 }
1266
1267 Ok(())
1268}
1269
1270pub(crate) async fn restorable_workspace_locations(
1271 cx: &mut AsyncApp,
1272 app_state: &Arc<AppState>,
1273) -> Option<Vec<(SerializedWorkspaceLocation, PathList)>> {
1274 let mut restore_behavior = cx
1275 .update(|cx| WorkspaceSettings::get(None, cx).restore_on_startup)
1276 .ok()?;
1277
1278 let session_handle = app_state.session.clone();
1279 let (last_session_id, last_session_window_stack) = cx
1280 .update(|cx| {
1281 let session = session_handle.read(cx);
1282
1283 (
1284 session.last_session_id().map(|id| id.to_string()),
1285 session.last_session_window_stack(),
1286 )
1287 })
1288 .ok()?;
1289
1290 if last_session_id.is_none()
1291 && matches!(
1292 restore_behavior,
1293 workspace::RestoreOnStartupBehavior::LastSession
1294 )
1295 {
1296 restore_behavior = workspace::RestoreOnStartupBehavior::LastWorkspace;
1297 }
1298
1299 match restore_behavior {
1300 workspace::RestoreOnStartupBehavior::LastWorkspace => {
1301 workspace::last_opened_workspace_location()
1302 .await
1303 .map(|location| vec![location])
1304 }
1305 workspace::RestoreOnStartupBehavior::LastSession => {
1306 if let Some(last_session_id) = last_session_id {
1307 let ordered = last_session_window_stack.is_some();
1308
1309 let mut locations = workspace::last_session_workspace_locations(
1310 &last_session_id,
1311 last_session_window_stack,
1312 )
1313 .filter(|locations| !locations.is_empty());
1314
1315 // Since last_session_window_order returns the windows ordered front-to-back
1316 // we need to open the window that was frontmost last.
1317 if ordered && let Some(locations) = locations.as_mut() {
1318 locations.reverse();
1319 }
1320
1321 locations
1322 } else {
1323 None
1324 }
1325 }
1326 _ => None,
1327 }
1328}
1329
1330fn init_paths() -> HashMap<io::ErrorKind, Vec<&'static Path>> {
1331 [
1332 paths::config_dir(),
1333 paths::extensions_dir(),
1334 paths::languages_dir(),
1335 paths::debug_adapters_dir(),
1336 paths::database_dir(),
1337 paths::logs_dir(),
1338 paths::temp_dir(),
1339 paths::hang_traces_dir(),
1340 ]
1341 .into_iter()
1342 .fold(HashMap::default(), |mut errors, path| {
1343 if let Err(e) = std::fs::create_dir_all(path) {
1344 errors.entry(e.kind()).or_insert_with(Vec::new).push(path);
1345 }
1346 errors
1347 })
1348}
1349
1350fn stdout_is_a_pty() -> bool {
1351 std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && io::stdout().is_terminal()
1352}
1353
1354#[derive(Parser, Debug)]
1355#[command(name = "zed", disable_version_flag = true, max_term_width = 100)]
1356struct Args {
1357 /// A sequence of space-separated paths or urls that you want to open.
1358 ///
1359 /// Use `path:line:row` syntax to open a file at a specific location.
1360 /// Non-existing paths and directories will ignore `:line:row` suffix.
1361 ///
1362 /// URLs can either be `file://` or `zed://` scheme, or relative to <https://zed.dev>.
1363 paths_or_urls: Vec<String>,
1364
1365 /// Pairs of file paths to diff. Can be specified multiple times.
1366 #[arg(long, action = clap::ArgAction::Append, num_args = 2, value_names = ["OLD_PATH", "NEW_PATH"])]
1367 diff: Vec<String>,
1368
1369 /// Sets a custom directory for all user data (e.g., database, extensions, logs).
1370 ///
1371 /// This overrides the default platform-specific data directory location.
1372 /// On macOS, the default is `~/Library/Application Support/Zed`.
1373 /// On Linux/FreeBSD, the default is `$XDG_DATA_HOME/zed`.
1374 /// On Windows, the default is `%LOCALAPPDATA%\Zed`.
1375 #[arg(long, value_name = "DIR", verbatim_doc_comment)]
1376 user_data_dir: Option<String>,
1377
1378 /// The username and WSL distribution to use when opening paths. If not specified,
1379 /// Zed will attempt to open the paths directly.
1380 ///
1381 /// The username is optional, and if not specified, the default user for the distribution
1382 /// will be used.
1383 ///
1384 /// Example: `me@Ubuntu` or `Ubuntu`.
1385 ///
1386 /// WARN: You should not fill in this field by hand.
1387 #[cfg(target_os = "windows")]
1388 #[arg(long, value_name = "USER@DISTRO")]
1389 wsl: Option<String>,
1390
1391 /// Instructs zed to run as a dev server on this machine. (not implemented)
1392 #[arg(long)]
1393 dev_server_token: Option<String>,
1394
1395 /// Prints system specs.
1396 ///
1397 /// Useful for submitting issues on GitHub when encountering a bug that
1398 /// prevents Zed from starting, so you can't run `zed: copy system specs to
1399 /// clipboard`
1400 #[arg(long)]
1401 system_specs: bool,
1402
1403 /// Used for the MCP Server, to remove the need for netcat as a dependency,
1404 /// by having Zed act like netcat communicating over a Unix socket.
1405 #[arg(long, hide = true)]
1406 nc: Option<String>,
1407
1408 /// Used for recording minidumps on crashes by having Zed run a separate
1409 /// process communicating over a socket.
1410 #[arg(long, hide = true)]
1411 crash_handler: Option<PathBuf>,
1412
1413 /// Run zed in the foreground, only used on Windows, to match the behavior on macOS.
1414 #[arg(long)]
1415 #[cfg(target_os = "windows")]
1416 #[arg(hide = true)]
1417 foreground: bool,
1418
1419 /// The dock action to perform. This is used on Windows only.
1420 #[arg(long)]
1421 #[cfg(target_os = "windows")]
1422 #[arg(hide = true)]
1423 dock_action: Option<usize>,
1424
1425 /// Used for SSH/Git password authentication, to remove the need for netcat as a dependency,
1426 /// by having Zed act like netcat communicating over a Unix socket.
1427 #[arg(long)]
1428 #[cfg(not(target_os = "windows"))]
1429 #[arg(hide = true)]
1430 askpass: Option<String>,
1431
1432 #[arg(long, hide = true)]
1433 dump_all_actions: bool,
1434
1435 /// Output current environment variables as JSON to stdout
1436 #[arg(long, hide = true)]
1437 printenv: bool,
1438}
1439
1440#[derive(Clone, Debug)]
1441enum IdType {
1442 New(String),
1443 Existing(String),
1444}
1445
1446impl ToString for IdType {
1447 fn to_string(&self) -> String {
1448 match self {
1449 IdType::New(id) | IdType::Existing(id) => id.clone(),
1450 }
1451 }
1452}
1453
1454fn parse_url_arg(arg: &str, cx: &App) -> String {
1455 match std::fs::canonicalize(Path::new(&arg)) {
1456 Ok(path) => format!("file://{}", path.display()),
1457 Err(_) => {
1458 if arg.starts_with("file://")
1459 || arg.starts_with("zed-cli://")
1460 || arg.starts_with("ssh://")
1461 || parse_zed_link(arg, cx).is_some()
1462 {
1463 arg.into()
1464 } else {
1465 format!("file://{arg}")
1466 }
1467 }
1468 }
1469}
1470
1471fn load_embedded_fonts(cx: &App) {
1472 let asset_source = cx.asset_source();
1473 let font_paths = asset_source.list("fonts").unwrap();
1474 let embedded_fonts = Mutex::new(Vec::new());
1475 let executor = cx.background_executor();
1476
1477 executor.block(executor.scoped(|scope| {
1478 for font_path in &font_paths {
1479 if !font_path.ends_with(".ttf") {
1480 continue;
1481 }
1482
1483 scope.spawn(async {
1484 let font_bytes = asset_source.load(font_path).unwrap().unwrap();
1485 embedded_fonts.lock().push(font_bytes);
1486 });
1487 }
1488 }));
1489
1490 cx.text_system()
1491 .add_fonts(embedded_fonts.into_inner())
1492 .unwrap();
1493}
1494
1495/// Spawns a background task to load the user themes from the themes directory.
1496fn load_user_themes_in_background(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1497 cx.spawn({
1498 let fs = fs.clone();
1499 async move |cx| {
1500 if let Some(theme_registry) = cx.update(|cx| ThemeRegistry::global(cx)).log_err() {
1501 let themes_dir = paths::themes_dir().as_ref();
1502 match fs
1503 .metadata(themes_dir)
1504 .await
1505 .ok()
1506 .flatten()
1507 .map(|m| m.is_dir)
1508 {
1509 Some(is_dir) => {
1510 anyhow::ensure!(is_dir, "Themes dir path {themes_dir:?} is not a directory")
1511 }
1512 None => {
1513 fs.create_dir(themes_dir).await.with_context(|| {
1514 format!("Failed to create themes dir at path {themes_dir:?}")
1515 })?;
1516 }
1517 }
1518 theme_registry.load_user_themes(themes_dir, fs).await?;
1519 cx.update(GlobalTheme::reload_theme)?;
1520 }
1521 anyhow::Ok(())
1522 }
1523 })
1524 .detach_and_log_err(cx);
1525}
1526
1527/// Spawns a background task to watch the themes directory for changes.
1528fn watch_themes(fs: Arc<dyn fs::Fs>, cx: &mut App) {
1529 use std::time::Duration;
1530 cx.spawn(async move |cx| {
1531 let (mut events, _) = fs
1532 .watch(paths::themes_dir(), Duration::from_millis(100))
1533 .await;
1534
1535 while let Some(paths) = events.next().await {
1536 for event in paths {
1537 if fs.metadata(&event.path).await.ok().flatten().is_some()
1538 && let Some(theme_registry) =
1539 cx.update(|cx| ThemeRegistry::global(cx)).log_err()
1540 && let Some(()) = theme_registry
1541 .load_user_theme(&event.path, fs.clone())
1542 .await
1543 .log_err()
1544 {
1545 cx.update(GlobalTheme::reload_theme).log_err();
1546 }
1547 }
1548 }
1549 })
1550 .detach()
1551}
1552
1553#[cfg(debug_assertions)]
1554fn watch_languages(fs: Arc<dyn fs::Fs>, languages: Arc<LanguageRegistry>, cx: &mut App) {
1555 use std::time::Duration;
1556
1557 cx.background_spawn(async move {
1558 let languages_src = Path::new("crates/languages/src");
1559 let Some(languages_src) = fs.canonicalize(languages_src).await.log_err() else {
1560 return;
1561 };
1562
1563 let (mut events, watcher) = fs.watch(&languages_src, Duration::from_millis(100)).await;
1564
1565 // add subdirectories since fs.watch is not recursive on Linux
1566 if let Some(mut paths) = fs.read_dir(&languages_src).await.log_err() {
1567 while let Some(path) = paths.next().await {
1568 if let Some(path) = path.log_err()
1569 && fs.is_dir(&path).await
1570 {
1571 watcher.add(&path).log_err();
1572 }
1573 }
1574 }
1575
1576 while let Some(event) = events.next().await {
1577 let has_language_file = event
1578 .iter()
1579 .any(|event| event.path.extension().is_some_and(|ext| ext == "scm"));
1580 if has_language_file {
1581 languages.reload();
1582 }
1583 }
1584 })
1585 .detach();
1586}
1587
1588#[cfg(not(debug_assertions))]
1589fn watch_languages(_fs: Arc<dyn fs::Fs>, _languages: Arc<LanguageRegistry>, _cx: &mut App) {}
1590
1591fn dump_all_gpui_actions() {
1592 #[derive(Debug, serde::Serialize)]
1593 struct ActionDef {
1594 name: &'static str,
1595 human_name: String,
1596 deprecated_aliases: &'static [&'static str],
1597 documentation: Option<&'static str>,
1598 }
1599 let mut actions = gpui::generate_list_of_all_registered_actions()
1600 .map(|action| ActionDef {
1601 name: action.name,
1602 human_name: command_palette::humanize_action_name(action.name),
1603 deprecated_aliases: action.deprecated_aliases,
1604 documentation: action.documentation,
1605 })
1606 .collect::<Vec<ActionDef>>();
1607
1608 actions.sort_by_key(|a| a.name);
1609
1610 io::Write::write(
1611 &mut std::io::stdout(),
1612 serde_json::to_string_pretty(&actions).unwrap().as_bytes(),
1613 )
1614 .unwrap();
1615}
1616
1617#[cfg(target_os = "windows")]
1618fn check_for_conpty_dll() {
1619 use windows::{
1620 Win32::{Foundation::FreeLibrary, System::LibraryLoader::LoadLibraryW},
1621 core::w,
1622 };
1623
1624 if let Ok(hmodule) = unsafe { LoadLibraryW(w!("conpty.dll")) } {
1625 unsafe {
1626 FreeLibrary(hmodule)
1627 .context("Failed to free conpty.dll")
1628 .log_err();
1629 }
1630 } else {
1631 log::warn!("Failed to load conpty.dll. Terminal will work with reduced functionality.");
1632 }
1633}