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, 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        // 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        journal::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".to_string();
391    let key_name = "installation_id".to_string();
392
393    // Migrate legacy key to new key
394    if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&legacy_key_name) {
395        KEY_VALUE_STORE
396            .write_kvp(key_name, installation_id.clone())
397            .await?;
398        KEY_VALUE_STORE.delete_kvp(legacy_key_name).await?;
399        return Ok((installation_id, true));
400    }
401
402    if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(&key_name) {
403        return Ok((installation_id, true));
404    }
405
406    let installation_id = Uuid::new_v4().to_string();
407
408    KEY_VALUE_STORE
409        .write_kvp(key_name, installation_id.clone())
410        .await?;
411
412    Ok((installation_id, false))
413}
414
415async fn restore_or_create_workspace(app_state: &Arc<AppState>, mut cx: AsyncAppContext) {
416    async_maybe!({
417        if let Some(location) = workspace::last_opened_workspace_paths().await {
418            cx.update(|cx| workspace::open_paths(location.paths().as_ref(), app_state, None, cx))?
419                .await
420                .log_err();
421        } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
422            cx.update(|cx| show_welcome_view(app_state, cx)).log_err();
423        } else {
424            cx.update(|cx| {
425                workspace::open_new(app_state, cx, |workspace, cx| {
426                    Editor::new_file(workspace, &Default::default(), cx)
427                })
428                .detach();
429            })?;
430        }
431        anyhow::Ok(())
432    })
433    .await
434    .log_err();
435}
436
437fn init_paths() {
438    std::fs::create_dir_all(&*util::paths::CONFIG_DIR).expect("could not create config path");
439    std::fs::create_dir_all(&*util::paths::LANGUAGES_DIR).expect("could not create languages path");
440    std::fs::create_dir_all(&*util::paths::DB_DIR).expect("could not create database path");
441    std::fs::create_dir_all(&*util::paths::LOGS_DIR).expect("could not create logs path");
442}
443
444fn init_logger() {
445    if stdout_is_a_pty() {
446        env_logger::init();
447    } else {
448        let level = LevelFilter::Info;
449
450        // Prevent log file from becoming too large.
451        const KIB: u64 = 1024;
452        const MIB: u64 = 1024 * KIB;
453        const MAX_LOG_BYTES: u64 = MIB;
454        if std::fs::metadata(&*paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
455        {
456            let _ = std::fs::rename(&*paths::LOG, &*paths::OLD_LOG);
457        }
458
459        let log_file = OpenOptions::new()
460            .create(true)
461            .append(true)
462            .open(&*paths::LOG)
463            .expect("could not open logfile");
464
465        let config = ConfigBuilder::new()
466            .set_time_format_str("%Y-%m-%dT%T") //All timestamps are UTC
467            .build();
468
469        simplelog::WriteLogger::init(level, config, log_file).expect("could not initialize logger");
470    }
471}
472
473#[derive(Serialize, Deserialize)]
474struct LocationData {
475    file: String,
476    line: u32,
477}
478
479#[derive(Serialize, Deserialize)]
480struct Panic {
481    thread: String,
482    payload: String,
483    #[serde(skip_serializing_if = "Option::is_none")]
484    location_data: Option<LocationData>,
485    backtrace: Vec<String>,
486    app_version: String,
487    release_channel: String,
488    os_name: String,
489    os_version: Option<String>,
490    architecture: String,
491    panicked_on: i64,
492    #[serde(skip_serializing_if = "Option::is_none")]
493    installation_id: Option<String>,
494    session_id: String,
495}
496
497#[derive(Serialize)]
498struct PanicRequest {
499    panic: Panic,
500    token: String,
501}
502
503static PANIC_COUNT: AtomicU32 = AtomicU32::new(0);
504
505fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: String) {
506    let is_pty = stdout_is_a_pty();
507    let app_metadata = app.metadata();
508
509    panic::set_hook(Box::new(move |info| {
510        let prior_panic_count = PANIC_COUNT.fetch_add(1, Ordering::SeqCst);
511        if prior_panic_count > 0 {
512            // Give the panic-ing thread time to write the panic file
513            loop {
514                std::thread::yield_now();
515            }
516        }
517
518        let thread = thread::current();
519        let thread_name = thread.name().unwrap_or("<unnamed>");
520
521        let payload = info
522            .payload()
523            .downcast_ref::<&str>()
524            .map(|s| s.to_string())
525            .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
526            .unwrap_or_else(|| "Box<Any>".to_string());
527
528        if *util::channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
529            let location = info.location().unwrap();
530            let backtrace = Backtrace::new();
531            eprintln!(
532                "Thread {:?} panicked with {:?} at {}:{}:{}\n{:?}",
533                thread_name,
534                payload,
535                location.file(),
536                location.line(),
537                location.column(),
538                backtrace,
539            );
540            std::process::exit(-1);
541        }
542
543        let app_version = client::ZED_APP_VERSION
544            .or(app_metadata.app_version)
545            .map_or("dev".to_string(), |v| v.to_string());
546
547        let backtrace = Backtrace::new();
548        let mut backtrace = backtrace
549            .frames()
550            .iter()
551            .filter_map(|frame| Some(format!("{:#}", frame.symbols().first()?.name()?)))
552            .collect::<Vec<_>>();
553
554        // Strip out leading stack frames for rust panic-handling.
555        if let Some(ix) = backtrace
556            .iter()
557            .position(|name| name == "rust_begin_unwind")
558        {
559            backtrace.drain(0..=ix);
560        }
561
562        let panic_data = Panic {
563            thread: thread_name.into(),
564            payload: payload.into(),
565            location_data: info.location().map(|location| LocationData {
566                file: location.file().into(),
567                line: location.line(),
568            }),
569            app_version: app_version.clone(),
570            release_channel: RELEASE_CHANNEL.display_name().into(),
571            os_name: app_metadata.os_name.into(),
572            os_version: app_metadata
573                .os_version
574                .as_ref()
575                .map(SemanticVersion::to_string),
576            architecture: env::consts::ARCH.into(),
577            panicked_on: Utc::now().timestamp_millis(),
578            backtrace,
579            installation_id: installation_id.clone(),
580            session_id: session_id.clone(),
581        };
582
583        if let Some(panic_data_json) = serde_json::to_string_pretty(&panic_data).log_err() {
584            log::error!("{}", panic_data_json);
585        }
586
587        if !is_pty {
588            if let Some(panic_data_json) = serde_json::to_string(&panic_data).log_err() {
589                let timestamp = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
590                let panic_file_path = paths::LOGS_DIR.join(format!("zed-{}.panic", timestamp));
591                let panic_file = std::fs::OpenOptions::new()
592                    .append(true)
593                    .create(true)
594                    .open(&panic_file_path)
595                    .log_err();
596                if let Some(mut panic_file) = panic_file {
597                    writeln!(&mut panic_file, "{}", panic_data_json).log_err();
598                    panic_file.flush().log_err();
599                }
600            }
601        }
602
603        std::process::abort();
604    }));
605}
606
607fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
608    let telemetry_settings = *client::TelemetrySettings::get_global(cx);
609
610    cx.background_executor()
611        .spawn(async move {
612            let panic_report_url = format!("{}/api/panic", &*client::ZED_SERVER_URL);
613            let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
614            while let Some(child) = children.next().await {
615                let child = child?;
616                let child_path = child.path();
617
618                if child_path.extension() != Some(OsStr::new("panic")) {
619                    continue;
620                }
621                let filename = if let Some(filename) = child_path.file_name() {
622                    filename.to_string_lossy()
623                } else {
624                    continue;
625                };
626
627                if !filename.starts_with("zed") {
628                    continue;
629                }
630
631                if telemetry_settings.diagnostics {
632                    let panic_file_content = smol::fs::read_to_string(&child_path)
633                        .await
634                        .context("error reading panic file")?;
635
636                    let panic = serde_json::from_str(&panic_file_content)
637                        .ok()
638                        .or_else(|| {
639                            panic_file_content
640                                .lines()
641                                .next()
642                                .and_then(|line| serde_json::from_str(line).ok())
643                        })
644                        .unwrap_or_else(|| {
645                            log::error!(
646                                "failed to deserialize panic file {:?}",
647                                panic_file_content
648                            );
649                            None
650                        });
651
652                    if let Some(panic) = panic {
653                        let body = serde_json::to_string(&PanicRequest {
654                            panic,
655                            token: client::ZED_SECRET_CLIENT_TOKEN.into(),
656                        })
657                        .unwrap();
658
659                        let request = Request::post(&panic_report_url)
660                            .redirect_policy(isahc::config::RedirectPolicy::Follow)
661                            .header("Content-Type", "application/json")
662                            .body(body.into())?;
663                        let response = http.send(request).await.context("error sending panic")?;
664                        if !response.status().is_success() {
665                            log::error!("Error uploading panic to server: {}", response.status());
666                        }
667                    }
668                }
669
670                // We've done what we can, delete the file
671                std::fs::remove_file(child_path)
672                    .context("error removing panic")
673                    .log_err();
674            }
675            Ok::<_, anyhow::Error>(())
676        })
677        .detach_and_log_err(cx);
678}
679
680async fn load_login_shell_environment() -> Result<()> {
681    let marker = "ZED_LOGIN_SHELL_START";
682    let shell = env::var("SHELL").context(
683        "SHELL environment variable is not assigned so we can't source login environment variables",
684    )?;
685    let output = Command::new(&shell)
686        .args(["-lic", &format!("echo {marker} && /usr/bin/env -0")])
687        .output()
688        .await
689        .context("failed to spawn login shell to source login environment variables")?;
690    if !output.status.success() {
691        Err(anyhow!("login shell exited with error"))?;
692    }
693
694    let stdout = String::from_utf8_lossy(&output.stdout);
695
696    if let Some(env_output_start) = stdout.find(marker) {
697        let env_output = &stdout[env_output_start + marker.len()..];
698        for line in env_output.split_terminator('\0') {
699            if let Some(separator_index) = line.find('=') {
700                let key = &line[..separator_index];
701                let value = &line[separator_index + 1..];
702                env::set_var(key, value);
703            }
704        }
705        log::info!(
706            "set environment variables from shell:{}, path:{}",
707            shell,
708            env::var("PATH").unwrap_or_default(),
709        );
710    }
711
712    Ok(())
713}
714
715fn stdout_is_a_pty() -> bool {
716    std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && std::io::stdout().is_terminal()
717}
718
719fn collect_url_args() -> Vec<String> {
720    env::args()
721        .skip(1)
722        .filter_map(|arg| match std::fs::canonicalize(Path::new(&arg)) {
723            Ok(path) => Some(format!("file://{}", path.to_string_lossy())),
724            Err(error) => {
725                if let Some(_) = parse_zed_link(&arg) {
726                    Some(arg)
727                } else {
728                    log::error!("error parsing path argument: {}", error);
729                    None
730                }
731            }
732        })
733        .collect()
734}
735
736fn load_embedded_fonts(cx: &AppContext) {
737    let asset_source = cx.asset_source();
738    let font_paths = asset_source.list("fonts").unwrap();
739    let embedded_fonts = Mutex::new(Vec::new());
740    let executor = cx.background_executor();
741
742    executor.block(executor.scoped(|scope| {
743        for font_path in &font_paths {
744            if !font_path.ends_with(".ttf") {
745                continue;
746            }
747
748            scope.spawn(async {
749                let font_bytes = asset_source.load(font_path).unwrap().to_vec();
750                embedded_fonts.lock().push(Arc::from(font_bytes));
751            });
752        }
753    }));
754
755    cx.text_system()
756        .add_fonts(&embedded_fonts.into_inner())
757        .unwrap();
758}
759
760#[cfg(debug_assertions)]
761async fn watch_languages(fs: Arc<dyn fs::Fs>, languages: Arc<LanguageRegistry>) -> Option<()> {
762    use std::time::Duration;
763
764    let mut events = fs
765        .watch(
766            "crates/zed2/src/languages".as_ref(),
767            Duration::from_millis(100),
768        )
769        .await;
770    while (events.next().await).is_some() {
771        languages.reload();
772    }
773    Some(())
774}
775
776#[cfg(debug_assertions)]
777fn watch_file_types(fs: Arc<dyn fs::Fs>, cx: &mut AppContext) {
778    use std::time::Duration;
779
780    cx.spawn(|mut cx| async move {
781        let mut events = fs
782            .watch(
783                "assets/icons/file_icons/file_types.json".as_ref(),
784                Duration::from_millis(100),
785            )
786            .await;
787        while (events.next().await).is_some() {
788            cx.update(|cx| {
789                cx.update_global(|file_types, _| {
790                    *file_types = project_panel::file_associations::FileAssociations::new(Assets);
791                });
792            })
793            .ok();
794        }
795    })
796    .detach()
797}
798
799#[cfg(not(debug_assertions))]
800async fn watch_languages(_: Arc<dyn fs::Fs>, _: Arc<LanguageRegistry>) -> Option<()> {
801    None
802}
803
804#[cfg(not(debug_assertions))]
805fn watch_file_types(_fs: Arc<dyn fs::Fs>, _cx: &mut AppContext) {}