main.rs

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