1// Allow binary to be called Zed for a nice application menu when running executable directly
2#![allow(non_snake_case)]
3
4use anyhow::{anyhow, Context as _, Result};
5use backtrace::Backtrace;
6use chrono::Utc;
7use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
8use client::{Client, UserStore};
9use collab_ui::channel_view::ChannelView;
10use db::kvp::KEY_VALUE_STORE;
11use editor::Editor;
12use fs::RealFs;
13use futures::StreamExt;
14use gpui::{App, AppContext, AsyncAppContext, Context, SemanticVersion, Task};
15use isahc::{prelude::Configurable, Request};
16use language::LanguageRegistry;
17use log::LevelFilter;
18
19use node_runtime::RealNodeRuntime;
20use parking_lot::Mutex;
21use serde::{Deserialize, Serialize};
22use settings::{
23 default_settings, handle_settings_file_changes, watch_config_file, Settings, SettingsStore,
24};
25use simplelog::ConfigBuilder;
26use smol::process::Command;
27use std::{
28 env,
29 ffi::OsStr,
30 fs::OpenOptions,
31 io::{IsTerminal, Write},
32 panic,
33 path::{Path, PathBuf},
34 sync::{
35 atomic::{AtomicU32, Ordering},
36 Arc, Weak,
37 },
38 thread,
39};
40use theme::ActiveTheme;
41use util::{
42 async_maybe,
43 channel::{parse_zed_link, AppCommitSha, ReleaseChannel, RELEASE_CHANNEL},
44 http::{self, HttpClient},
45 paths, ResultExt,
46};
47use uuid::Uuid;
48use welcome::{show_welcome_view, FIRST_OPEN};
49use workspace::{AppState, WorkspaceStore};
50use zed::{
51 app_menus, build_window_options, ensure_only_instance, handle_cli_connection,
52 handle_keymap_file_changes, initialize_workspace, languages, Assets, IsOnlyInstance,
53 OpenListener, OpenRequest,
54};
55
56fn main() {
57 menu::init();
58 zed_actions::init();
59
60 let http = http::client();
61 init_paths();
62 init_logger();
63
64 if ensure_only_instance() != IsOnlyInstance::Yes {
65 return;
66 }
67
68 log::info!("========== starting zed ==========");
69 let app = App::production(Arc::new(Assets));
70
71 let (installation_id, existing_installation_id_found) = app
72 .background_executor()
73 .block(installation_id())
74 .ok()
75 .unzip();
76 let session_id = Uuid::new_v4().to_string();
77 init_panic_hook(&app, installation_id.clone(), session_id.clone());
78
79 let fs = Arc::new(RealFs);
80 let user_settings_file_rx = watch_config_file(
81 &app.background_executor(),
82 fs.clone(),
83 paths::SETTINGS.clone(),
84 );
85 let user_keymap_file_rx = watch_config_file(
86 &app.background_executor(),
87 fs.clone(),
88 paths::KEYMAP.clone(),
89 );
90
91 let login_shell_env_loaded = if stdout_is_a_pty() {
92 Task::ready(())
93 } else {
94 app.background_executor().spawn(async {
95 load_login_shell_environment().await.log_err();
96 })
97 };
98
99 let (listener, mut open_rx) = OpenListener::new();
100 let listener = Arc::new(listener);
101 let open_listener = listener.clone();
102 app.on_open_urls(move |urls, _| open_listener.open_urls(&urls));
103 app.on_reopen(move |cx| {
104 if cx.has_global::<Weak<AppState>>() {
105 if let Some(app_state) = cx.global::<Weak<AppState>>().upgrade() {
106 workspace::open_new(&app_state, cx, |workspace, cx| {
107 Editor::new_file(workspace, &Default::default(), cx)
108 })
109 .detach();
110 }
111 }
112 });
113
114 app.run(move |cx| {
115 cx.set_global(*RELEASE_CHANNEL);
116 if let Some(build_sha) = option_env!("ZED_COMMIT_SHA") {
117 cx.set_global(AppCommitSha(build_sha.into()))
118 }
119
120 cx.set_global(listener.clone());
121
122 load_embedded_fonts(cx);
123
124 let mut store = SettingsStore::default();
125 store
126 .set_default_settings(default_settings().as_ref(), cx)
127 .unwrap();
128 cx.set_global(store);
129 handle_settings_file_changes(user_settings_file_rx, cx);
130 handle_keymap_file_changes(user_keymap_file_rx, cx);
131
132 let client = client::Client::new(http.clone(), cx);
133 let mut languages = LanguageRegistry::new(login_shell_env_loaded);
134 let copilot_language_server_id = languages.next_language_server_id();
135 languages.set_executor(cx.background_executor().clone());
136 languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
137 let languages = Arc::new(languages);
138 let node_runtime = RealNodeRuntime::new(http.clone());
139
140 language::init(cx);
141 languages::init(languages.clone(), node_runtime.clone(), cx);
142 let user_store = cx.new_model(|cx| UserStore::new(client.clone(), cx));
143 let workspace_store = cx.new_model(|cx| WorkspaceStore::new(client.clone(), cx));
144
145 cx.set_global(client.clone());
146
147 theme::init(theme::LoadThemes::All, cx);
148 project::Project::init(&client, cx);
149 client::init(&client, cx);
150 command_palette::init(cx);
151 language::init(cx);
152 editor::init(cx);
153 diagnostics::init(cx);
154 copilot::init(
155 copilot_language_server_id,
156 http.clone(),
157 node_runtime.clone(),
158 cx,
159 );
160 assistant::init(cx);
161 // component_test::init(cx);
162
163 cx.spawn(|_| watch_languages(fs.clone(), languages.clone()))
164 .detach();
165 watch_file_types(fs.clone(), cx);
166
167 languages.set_theme(cx.theme().clone());
168 cx.observe_global::<SettingsStore>({
169 let languages = languages.clone();
170 move |cx| languages.set_theme(cx.theme().clone())
171 })
172 .detach();
173
174 client.telemetry().start(installation_id, session_id, cx);
175 client
176 .telemetry()
177 .report_setting_event("theme", cx.theme().name.to_string(), cx);
178 let event_operation = match existing_installation_id_found {
179 Some(false) => "first open",
180 _ => "open",
181 };
182 client
183 .telemetry()
184 .report_app_event(event_operation, true, cx);
185
186 let app_state = Arc::new(AppState {
187 languages: languages.clone(),
188 client: client.clone(),
189 user_store: user_store.clone(),
190 fs: fs.clone(),
191 build_window_options,
192 workspace_store,
193 node_runtime,
194 });
195 cx.set_global(Arc::downgrade(&app_state));
196
197 audio::init(Assets, cx);
198 auto_update::init(http.clone(), client::ZED_SERVER_URL.clone(), cx);
199
200 workspace::init(app_state.clone(), cx);
201 recent_projects::init(cx);
202
203 go_to_line::init(cx);
204 file_finder::init(cx);
205 outline::init(cx);
206 project_symbols::init(cx);
207 project_panel::init(Assets, cx);
208 channel::init(&client, user_store.clone(), cx);
209 search::init(cx);
210 semantic_index::init(fs.clone(), http.clone(), languages.clone(), cx);
211 vim::init(cx);
212 terminal_view::init(cx);
213
214 journal::init(app_state.clone(), cx);
215 language_selector::init(cx);
216 theme_selector::init(cx);
217 language_tools::init(cx);
218 call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
219 notifications::init(app_state.client.clone(), app_state.user_store.clone(), cx);
220 collab_ui::init(&app_state, cx);
221 feedback::init(cx);
222 welcome::init(cx);
223
224 cx.set_menus(app_menus());
225 initialize_workspace(app_state.clone(), cx);
226
227 if stdout_is_a_pty() {
228 cx.activate(true);
229 let urls = collect_url_args();
230 if !urls.is_empty() {
231 listener.open_urls(&urls)
232 }
233 } else {
234 upload_previous_panics(http.clone(), cx);
235
236 // TODO Development mode that forces the CLI mode usually runs Zed binary as is instead
237 // of an *app, hence gets no specific callbacks run. Emulate them here, if needed.
238 if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some()
239 && !listener.triggered.load(Ordering::Acquire)
240 {
241 listener.open_urls(&collect_url_args())
242 }
243 }
244
245 let mut triggered_authentication = false;
246
247 fn open_paths_and_log_errs(
248 paths: &[PathBuf],
249 app_state: &Arc<AppState>,
250 cx: &mut AppContext,
251 ) {
252 let task = workspace::open_paths(&paths, &app_state, None, cx);
253 cx.spawn(|_| async move {
254 if let Some((_window, results)) = task.await.log_err() {
255 for result in results {
256 if let Some(Err(e)) = result {
257 log::error!("Error opening path: {}", e);
258 }
259 }
260 }
261 })
262 .detach();
263 }
264
265 match open_rx.try_next() {
266 Ok(Some(OpenRequest::Paths { paths })) => {
267 open_paths_and_log_errs(&paths, &app_state, cx)
268 }
269 Ok(Some(OpenRequest::CliConnection { connection })) => {
270 let app_state = app_state.clone();
271 cx.spawn(move |cx| handle_cli_connection(connection, app_state, cx))
272 .detach();
273 }
274 Ok(Some(OpenRequest::JoinChannel { channel_id })) => {
275 triggered_authentication = true;
276 let app_state = app_state.clone();
277 let client = client.clone();
278 cx.spawn(|cx| async move {
279 // ignore errors here, we'll show a generic "not signed in"
280 let _ = authenticate(client, &cx).await;
281 cx.update(|cx| workspace::join_channel(channel_id, app_state, None, cx))?
282 .await?;
283 anyhow::Ok(())
284 })
285 .detach_and_log_err(cx);
286 }
287 Ok(Some(OpenRequest::OpenChannelNotes { channel_id })) => {
288 triggered_authentication = true;
289 let app_state = app_state.clone();
290 let client = client.clone();
291 cx.spawn(|mut cx| async move {
292 // ignore errors here, we'll show a generic "not signed in"
293 let _ = authenticate(client, &cx).await;
294 let workspace_window =
295 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
296 let _ = workspace_window
297 .update(&mut cx, |_, cx| {
298 ChannelView::open(channel_id, cx.view().clone(), cx)
299 })?
300 .await?;
301 anyhow::Ok(())
302 })
303 .detach_and_log_err(cx);
304 }
305 Ok(None) | Err(_) => cx
306 .spawn({
307 let app_state = app_state.clone();
308 |cx| async move { restore_or_create_workspace(&app_state, cx).await }
309 })
310 .detach(),
311 }
312
313 let app_state = app_state.clone();
314 cx.spawn(move |cx| async move {
315 while let Some(request) = open_rx.next().await {
316 match request {
317 OpenRequest::Paths { paths } => {
318 cx.update(|cx| open_paths_and_log_errs(&paths, &app_state, cx))
319 .ok();
320 }
321 OpenRequest::CliConnection { connection } => {
322 let app_state = app_state.clone();
323 cx.spawn(move |cx| {
324 handle_cli_connection(connection, app_state.clone(), cx)
325 })
326 .detach();
327 }
328 OpenRequest::JoinChannel { channel_id } => {
329 let app_state = app_state.clone();
330 cx.update(|mut cx| {
331 cx.spawn(|cx| async move {
332 cx.update(|cx| {
333 workspace::join_channel(channel_id, app_state, None, cx)
334 })?
335 .await?;
336 anyhow::Ok(())
337 })
338 .detach_and_log_err(&mut cx);
339 })
340 .log_err();
341 }
342 OpenRequest::OpenChannelNotes { channel_id } => {
343 let app_state = app_state.clone();
344 let open_notes_task = cx.spawn(|mut cx| async move {
345 let workspace_window =
346 workspace::get_any_active_workspace(app_state, cx.clone()).await?;
347 let _ = workspace_window
348 .update(&mut cx, |_, cx| {
349 ChannelView::open(channel_id, cx.view().clone(), cx)
350 })?
351 .await?;
352 anyhow::Ok(())
353 });
354 cx.update(|cx| open_notes_task.detach_and_log_err(cx))
355 .log_err();
356 }
357 }
358 }
359 })
360 .detach();
361
362 if !triggered_authentication {
363 cx.spawn(|cx| async move { authenticate(client, &cx).await })
364 .detach_and_log_err(cx);
365 }
366 });
367}
368
369async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
370 if stdout_is_a_pty() {
371 if client::IMPERSONATE_LOGIN.is_some() {
372 client.authenticate_and_connect(false, &cx).await?;
373 }
374 } else if client.has_keychain_credentials(&cx) {
375 client.authenticate_and_connect(true, &cx).await?;
376 }
377 Ok::<_, anyhow::Error>(())
378}
379
380async fn installation_id() -> Result<(String, bool)> {
381 let legacy_key_name = "device_id".to_string();
382 let key_name = "installation_id".to_string();
383
384 // Migrate legacy key to new key
385 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&legacy_key_name) {
386 KEY_VALUE_STORE
387 .write_kvp(key_name, installation_id.clone())
388 .await?;
389 KEY_VALUE_STORE.delete_kvp(legacy_key_name).await?;
390 return Ok((installation_id, true));
391 }
392
393 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&key_name) {
394 return Ok((installation_id, true));
395 }
396
397 let installation_id = Uuid::new_v4().to_string();
398
399 KEY_VALUE_STORE
400 .write_kvp(key_name, installation_id.clone())
401 .await?;
402
403 Ok((installation_id, false))
404}
405
406async fn restore_or_create_workspace(app_state: &Arc<AppState>, cx: AsyncAppContext) {
407 async_maybe!({
408 if let Some(location) = workspace::last_opened_workspace_paths().await {
409 cx.update(|cx| workspace::open_paths(location.paths().as_ref(), app_state, None, cx))?
410 .await
411 .log_err();
412 } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
413 cx.update(|cx| show_welcome_view(app_state, cx)).log_err();
414 } else {
415 cx.update(|cx| {
416 workspace::open_new(app_state, cx, |workspace, cx| {
417 Editor::new_file(workspace, &Default::default(), cx)
418 })
419 .detach();
420 })?;
421 }
422 anyhow::Ok(())
423 })
424 .await
425 .log_err();
426}
427
428fn init_paths() {
429 std::fs::create_dir_all(&*util::paths::CONFIG_DIR).expect("could not create config path");
430 std::fs::create_dir_all(&*util::paths::LANGUAGES_DIR).expect("could not create languages path");
431 std::fs::create_dir_all(&*util::paths::DB_DIR).expect("could not create database path");
432 std::fs::create_dir_all(&*util::paths::LOGS_DIR).expect("could not create logs path");
433}
434
435fn init_logger() {
436 if stdout_is_a_pty() {
437 env_logger::init();
438 } else {
439 let level = LevelFilter::Info;
440
441 // Prevent log file from becoming too large.
442 const KIB: u64 = 1024;
443 const MIB: u64 = 1024 * KIB;
444 const MAX_LOG_BYTES: u64 = MIB;
445 if std::fs::metadata(&*paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
446 {
447 let _ = std::fs::rename(&*paths::LOG, &*paths::OLD_LOG);
448 }
449
450 let log_file = OpenOptions::new()
451 .create(true)
452 .append(true)
453 .open(&*paths::LOG)
454 .expect("could not open logfile");
455
456 let config = ConfigBuilder::new()
457 .set_time_format_str("%Y-%m-%dT%T") //All timestamps are UTC
458 .build();
459
460 simplelog::WriteLogger::init(level, config, log_file).expect("could not initialize logger");
461 }
462}
463
464#[derive(Serialize, Deserialize)]
465struct LocationData {
466 file: String,
467 line: u32,
468}
469
470#[derive(Serialize, Deserialize)]
471struct Panic {
472 thread: String,
473 payload: String,
474 #[serde(skip_serializing_if = "Option::is_none")]
475 location_data: Option<LocationData>,
476 backtrace: Vec<String>,
477 app_version: String,
478 release_channel: String,
479 os_name: String,
480 os_version: Option<String>,
481 architecture: String,
482 panicked_on: i64,
483 #[serde(skip_serializing_if = "Option::is_none")]
484 installation_id: Option<String>,
485 session_id: String,
486}
487
488#[derive(Serialize)]
489struct PanicRequest {
490 panic: Panic,
491 token: String,
492}
493
494static PANIC_COUNT: AtomicU32 = AtomicU32::new(0);
495
496fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: String) {
497 let is_pty = stdout_is_a_pty();
498 let app_metadata = app.metadata();
499
500 panic::set_hook(Box::new(move |info| {
501 let prior_panic_count = PANIC_COUNT.fetch_add(1, Ordering::SeqCst);
502 if prior_panic_count > 0 {
503 // Give the panic-ing thread time to write the panic file
504 loop {
505 std::thread::yield_now();
506 }
507 }
508
509 let thread = thread::current();
510 let thread_name = thread.name().unwrap_or("<unnamed>");
511
512 let payload = info
513 .payload()
514 .downcast_ref::<&str>()
515 .map(|s| s.to_string())
516 .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
517 .unwrap_or_else(|| "Box<Any>".to_string());
518
519 if *util::channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
520 let location = info.location().unwrap();
521 let backtrace = Backtrace::new();
522 eprintln!(
523 "Thread {:?} panicked with {:?} at {}:{}:{}\n{:?}",
524 thread_name,
525 payload,
526 location.file(),
527 location.line(),
528 location.column(),
529 backtrace,
530 );
531 std::process::exit(-1);
532 }
533
534 let app_version = client::ZED_APP_VERSION
535 .or(app_metadata.app_version)
536 .map_or("dev".to_string(), |v| v.to_string());
537
538 let backtrace = Backtrace::new();
539 let mut backtrace = backtrace
540 .frames()
541 .iter()
542 .filter_map(|frame| Some(format!("{:#}", frame.symbols().first()?.name()?)))
543 .collect::<Vec<_>>();
544
545 // Strip out leading stack frames for rust panic-handling.
546 if let Some(ix) = backtrace
547 .iter()
548 .position(|name| name == "rust_begin_unwind")
549 {
550 backtrace.drain(0..=ix);
551 }
552
553 let panic_data = Panic {
554 thread: thread_name.into(),
555 payload: payload.into(),
556 location_data: info.location().map(|location| LocationData {
557 file: location.file().into(),
558 line: location.line(),
559 }),
560 app_version: app_version.clone(),
561 release_channel: RELEASE_CHANNEL.display_name().into(),
562 os_name: app_metadata.os_name.into(),
563 os_version: app_metadata
564 .os_version
565 .as_ref()
566 .map(SemanticVersion::to_string),
567 architecture: env::consts::ARCH.into(),
568 panicked_on: Utc::now().timestamp_millis(),
569 backtrace,
570 installation_id: installation_id.clone(),
571 session_id: session_id.clone(),
572 };
573
574 if let Some(panic_data_json) = serde_json::to_string_pretty(&panic_data).log_err() {
575 log::error!("{}", panic_data_json);
576 }
577
578 if !is_pty {
579 if let Some(panic_data_json) = serde_json::to_string(&panic_data).log_err() {
580 let timestamp = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
581 let panic_file_path = paths::LOGS_DIR.join(format!("zed-{}.panic", timestamp));
582 let panic_file = std::fs::OpenOptions::new()
583 .append(true)
584 .create(true)
585 .open(&panic_file_path)
586 .log_err();
587 if let Some(mut panic_file) = panic_file {
588 writeln!(&mut panic_file, "{}", panic_data_json).log_err();
589 panic_file.flush().log_err();
590 }
591 }
592 }
593
594 std::process::abort();
595 }));
596}
597
598fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
599 let telemetry_settings = *client::TelemetrySettings::get_global(cx);
600
601 cx.background_executor()
602 .spawn(async move {
603 let panic_report_url = format!("{}/api/panic", &*client::ZED_SERVER_URL);
604 let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
605 while let Some(child) = children.next().await {
606 let child = child?;
607 let child_path = child.path();
608
609 if child_path.extension() != Some(OsStr::new("panic")) {
610 continue;
611 }
612 let filename = if let Some(filename) = child_path.file_name() {
613 filename.to_string_lossy()
614 } else {
615 continue;
616 };
617
618 if !filename.starts_with("zed") {
619 continue;
620 }
621
622 if telemetry_settings.diagnostics {
623 let panic_file_content = smol::fs::read_to_string(&child_path)
624 .await
625 .context("error reading panic file")?;
626
627 let panic = serde_json::from_str(&panic_file_content)
628 .ok()
629 .or_else(|| {
630 panic_file_content
631 .lines()
632 .next()
633 .and_then(|line| serde_json::from_str(line).ok())
634 })
635 .unwrap_or_else(|| {
636 log::error!(
637 "failed to deserialize panic file {:?}",
638 panic_file_content
639 );
640 None
641 });
642
643 if let Some(panic) = panic {
644 let body = serde_json::to_string(&PanicRequest {
645 panic,
646 token: client::ZED_SECRET_CLIENT_TOKEN.into(),
647 })
648 .unwrap();
649
650 let request = Request::post(&panic_report_url)
651 .redirect_policy(isahc::config::RedirectPolicy::Follow)
652 .header("Content-Type", "application/json")
653 .body(body.into())?;
654 let response = http.send(request).await.context("error sending panic")?;
655 if !response.status().is_success() {
656 log::error!("Error uploading panic to server: {}", response.status());
657 }
658 }
659 }
660
661 // We've done what we can, delete the file
662 std::fs::remove_file(child_path)
663 .context("error removing panic")
664 .log_err();
665 }
666 Ok::<_, anyhow::Error>(())
667 })
668 .detach_and_log_err(cx);
669}
670
671async fn load_login_shell_environment() -> Result<()> {
672 let marker = "ZED_LOGIN_SHELL_START";
673 let shell = env::var("SHELL").context(
674 "SHELL environment variable is not assigned so we can't source login environment variables",
675 )?;
676 let output = Command::new(&shell)
677 .args(["-lic", &format!("echo {marker} && /usr/bin/env -0")])
678 .output()
679 .await
680 .context("failed to spawn login shell to source login environment variables")?;
681 if !output.status.success() {
682 Err(anyhow!("login shell exited with error"))?;
683 }
684
685 let stdout = String::from_utf8_lossy(&output.stdout);
686
687 if let Some(env_output_start) = stdout.find(marker) {
688 let env_output = &stdout[env_output_start + marker.len()..];
689 for line in env_output.split_terminator('\0') {
690 if let Some(separator_index) = line.find('=') {
691 let key = &line[..separator_index];
692 let value = &line[separator_index + 1..];
693 env::set_var(key, value);
694 }
695 }
696 log::info!(
697 "set environment variables from shell:{}, path:{}",
698 shell,
699 env::var("PATH").unwrap_or_default(),
700 );
701 }
702
703 Ok(())
704}
705
706fn stdout_is_a_pty() -> bool {
707 std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && std::io::stdout().is_terminal()
708}
709
710fn collect_url_args() -> Vec<String> {
711 env::args()
712 .skip(1)
713 .filter_map(|arg| match std::fs::canonicalize(Path::new(&arg)) {
714 Ok(path) => Some(format!("file://{}", path.to_string_lossy())),
715 Err(error) => {
716 if let Some(_) = parse_zed_link(&arg) {
717 Some(arg)
718 } else {
719 log::error!("error parsing path argument: {}", error);
720 None
721 }
722 }
723 })
724 .collect()
725}
726
727fn load_embedded_fonts(cx: &AppContext) {
728 let asset_source = cx.asset_source();
729 let font_paths = asset_source.list("fonts").unwrap();
730 let embedded_fonts = Mutex::new(Vec::new());
731 let executor = cx.background_executor();
732
733 executor.block(executor.scoped(|scope| {
734 for font_path in &font_paths {
735 if !font_path.ends_with(".ttf") {
736 continue;
737 }
738
739 scope.spawn(async {
740 let font_bytes = asset_source.load(font_path).unwrap().to_vec();
741 embedded_fonts.lock().push(Arc::from(font_bytes));
742 });
743 }
744 }));
745
746 cx.text_system()
747 .add_fonts(&embedded_fonts.into_inner())
748 .unwrap();
749}
750
751#[cfg(debug_assertions)]
752async fn watch_languages(fs: Arc<dyn fs::Fs>, languages: Arc<LanguageRegistry>) -> Option<()> {
753 use std::time::Duration;
754
755 let mut events = fs
756 .watch(
757 "crates/zed/src/languages".as_ref(),
758 Duration::from_millis(100),
759 )
760 .await;
761 while (events.next().await).is_some() {
762 languages.reload();
763 }
764 Some(())
765}
766
767#[cfg(debug_assertions)]
768fn watch_file_types(fs: Arc<dyn fs::Fs>, cx: &mut AppContext) {
769 use std::time::Duration;
770
771 cx.spawn(|cx| async move {
772 let mut events = fs
773 .watch(
774 "assets/icons/file_icons/file_types.json".as_ref(),
775 Duration::from_millis(100),
776 )
777 .await;
778 while (events.next().await).is_some() {
779 cx.update(|cx| {
780 cx.update_global(|file_types, _| {
781 *file_types = project_panel::file_associations::FileAssociations::new(Assets);
782 });
783 })
784 .ok();
785 }
786 })
787 .detach()
788}
789
790#[cfg(not(debug_assertions))]
791async fn watch_languages(_: Arc<dyn fs::Fs>, _: Arc<LanguageRegistry>) -> Option<()> {
792 None
793}
794
795#[cfg(not(debug_assertions))]
796fn watch_file_types(_fs: Arc<dyn fs::Fs>, _cx: &mut AppContext) {}