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