main.rs

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