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