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 crate::open_listener::{OpenListener, OpenRequest};
  5use anyhow::{anyhow, Context as _, Result};
  6use backtrace::Backtrace;
  7use cli::{
  8    ipc::{self, IpcSender},
  9    CliRequest, CliResponse, IpcHandshake, FORCE_CLI_MODE_ENV_VAR_NAME,
 10};
 11use client2::UserStore;
 12use db2::kvp::KEY_VALUE_STORE;
 13use fs2::RealFs;
 14use futures::{channel::mpsc, SinkExt, StreamExt};
 15use gpui2::{Action, App, AppContext, AsyncAppContext, Context, MainThread, SemanticVersion, Task};
 16use isahc::{prelude::Configurable, Request};
 17use language2::LanguageRegistry;
 18use log::LevelFilter;
 19
 20use node_runtime::RealNodeRuntime;
 21use parking_lot::Mutex;
 22use serde::{Deserialize, Serialize};
 23use settings2::{
 24    default_settings, handle_settings_file_changes, watch_config_file, Settings, SettingsStore,
 25};
 26use simplelog::ConfigBuilder;
 27use smol::{future::FutureExt, process::Command};
 28use std::{
 29    env,
 30    ffi::OsStr,
 31    fs::OpenOptions,
 32    io::{IsTerminal, Write},
 33    panic,
 34    path::Path,
 35    sync::{
 36        atomic::{AtomicU32, Ordering},
 37        Arc,
 38    },
 39    thread,
 40    time::{SystemTime, UNIX_EPOCH},
 41};
 42use util::{
 43    async_maybe,
 44    channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
 45    http::{self, HttpClient},
 46    paths, ResultExt,
 47};
 48use uuid::Uuid;
 49use workspace2::{AppState, WorkspaceStore};
 50use zed2::{build_window_options, initialize_workspace, languages};
 51use zed2::{ensure_only_instance, Assets, IsOnlyInstance};
 52
 53mod open_listener;
 54
 55fn main() {
 56    let http = http::client();
 57    init_paths();
 58    init_logger();
 59
 60    if ensure_only_instance() != IsOnlyInstance::Yes {
 61        return;
 62    }
 63
 64    log::info!("========== starting zed ==========");
 65    let app = App::production(Arc::new(Assets));
 66
 67    let installation_id = app.background_executor().block(installation_id()).ok();
 68    let session_id = Uuid::new_v4().to_string();
 69    init_panic_hook(&app, installation_id.clone(), session_id.clone());
 70
 71    let fs = Arc::new(RealFs);
 72    let user_settings_file_rx = watch_config_file(
 73        &app.background_executor(),
 74        fs.clone(),
 75        paths::SETTINGS.clone(),
 76    );
 77    let _user_keymap_file_rx = watch_config_file(
 78        &app.background_executor(),
 79        fs.clone(),
 80        paths::KEYMAP.clone(),
 81    );
 82
 83    let login_shell_env_loaded = if stdout_is_a_pty() {
 84        Task::ready(())
 85    } else {
 86        app.background_executor().spawn(async {
 87            load_login_shell_environment().await.log_err();
 88        })
 89    };
 90
 91    let (listener, mut open_rx) = OpenListener::new();
 92    let listener = Arc::new(listener);
 93    let open_listener = listener.clone();
 94    app.on_open_urls(move |urls, _| open_listener.open_urls(urls));
 95    app.on_reopen(move |_cx| {
 96        // todo!("workspace")
 97        // if cx.has_global::<Weak<AppState>>() {
 98        // if let Some(app_state) = cx.global::<Weak<AppState>>().upgrade() {
 99        // workspace::open_new(&app_state, cx, |workspace, cx| {
100        //     Editor::new_file(workspace, &Default::default(), cx)
101        // })
102        // .detach();
103        // }
104        // }
105    });
106
107    app.run(move |cx| {
108        cx.set_global(*RELEASE_CHANNEL);
109        load_embedded_fonts(cx);
110
111        let mut store = SettingsStore::default();
112        store
113            .set_default_settings(default_settings().as_ref(), cx)
114            .unwrap();
115        cx.set_global(store);
116        handle_settings_file_changes(user_settings_file_rx, cx);
117        // handle_keymap_file_changes(user_keymap_file_rx, cx);
118
119        let client = client2::Client::new(http.clone(), cx);
120        let mut languages = LanguageRegistry::new(login_shell_env_loaded);
121        let copilot_language_server_id = languages.next_language_server_id();
122        languages.set_executor(cx.background_executor().clone());
123        languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
124        let languages = Arc::new(languages);
125        let node_runtime = RealNodeRuntime::new(http.clone());
126
127        language2::init(cx);
128        languages::init(languages.clone(), node_runtime.clone(), cx);
129        let user_store = cx.build_model(|cx| UserStore::new(client.clone(), http.clone(), cx));
130        let workspace_store = cx.build_model(|cx| WorkspaceStore::new(client.clone(), cx));
131
132        cx.set_global(client.clone());
133
134        theme2::init(cx);
135        // context_menu::init(cx);
136        project2::Project::init(&client, cx);
137        client2::init(&client, cx);
138        // command_palette::init(cx);
139        language2::init(cx);
140        // editor::init(cx);
141        // go_to_line::init(cx);
142        // file_finder::init(cx);
143        // outline::init(cx);
144        // project_symbols::init(cx);
145        // project_panel::init(Assets, cx);
146        // channel::init(&client, user_store.clone(), cx);
147        // diagnostics::init(cx);
148        // search::init(cx);
149        // semantic_index::init(fs.clone(), http.clone(), languages.clone(), cx);
150        // vim::init(cx);
151        // terminal_view::init(cx);
152        copilot2::init(
153            copilot_language_server_id,
154            http.clone(),
155            node_runtime.clone(),
156            cx,
157        );
158        // assistant::init(cx);
159        // component_test::init(cx);
160
161        // cx.spawn(|cx| watch_themes(fs.clone(), cx)).detach();
162        // cx.spawn(|_| watch_languages(fs.clone(), languages.clone()))
163        //     .detach();
164        // watch_file_types(fs.clone(), cx);
165
166        // languages.set_theme(theme::current(cx).clone());
167        // cx.observe_global::<SettingsStore, _>({
168        //     let languages = languages.clone();
169        //     move |cx| languages.set_theme(theme::current(cx).clone())
170        // })
171        // .detach();
172
173        // client.telemetry().start(installation_id, session_id, cx);
174
175        let app_state = Arc::new(AppState {
176            languages,
177            client: client.clone(),
178            user_store,
179            fs,
180            build_window_options,
181            initialize_workspace,
182            // background_actions: todo!("ask Mikayla"),
183            workspace_store,
184            node_runtime,
185        });
186        cx.set_global(Arc::downgrade(&app_state));
187
188        // audio::init(Assets, cx);
189        // auto_update::init(http.clone(), client::ZED_SERVER_URL.clone(), cx);
190
191        // todo!("workspace")
192        // workspace::init(app_state.clone(), cx);
193        // recent_projects::init(cx);
194
195        // journal2::init(app_state.clone(), cx);
196        // language_selector::init(cx);
197        // theme_selector::init(cx);
198        // activity_indicator::init(cx);
199        // language_tools::init(cx);
200        call2::init(app_state.client.clone(), app_state.user_store.clone(), cx);
201        // collab_ui::init(&app_state, cx);
202        // feedback::init(cx);
203        // welcome::init(cx);
204        // zed::init(&app_state, cx);
205
206        // cx.set_menus(menus::menus());
207
208        if stdout_is_a_pty() {
209            cx.activate(true);
210            let urls = collect_url_args();
211            if !urls.is_empty() {
212                listener.open_urls(urls)
213            }
214        } else {
215            upload_previous_panics(http.clone(), cx);
216
217            // TODO Development mode that forces the CLI mode usually runs Zed binary as is instead
218            // of an *app, hence gets no specific callbacks run. Emulate them here, if needed.
219            if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some()
220                && !listener.triggered.load(Ordering::Acquire)
221            {
222                listener.open_urls(collect_url_args())
223            }
224        }
225
226        let mut _triggered_authentication = false;
227
228        match open_rx.try_next() {
229            Ok(Some(OpenRequest::Paths { paths: _ })) => {
230                // todo!("workspace")
231                // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
232                //     .detach();
233            }
234            Ok(Some(OpenRequest::CliConnection { connection })) => {
235                let app_state = app_state.clone();
236                cx.spawn(move |cx| handle_cli_connection(connection, app_state, cx))
237                    .detach();
238            }
239            Ok(Some(OpenRequest::JoinChannel { channel_id: _ })) => {
240                // triggered_authentication = true;
241                // let app_state = app_state.clone();
242                // let client = client.clone();
243                // cx.spawn(|mut cx| async move {
244                //     // ignore errors here, we'll show a generic "not signed in"
245                //     let _ = authenticate(client, &cx).await;
246                //     cx.update(|cx| workspace::join_channel(channel_id, app_state, None, cx))
247                //         .await
248                // })
249                // .detach_and_log_err(cx)
250            }
251            Ok(None) | Err(_) => cx
252                .spawn_on_main({
253                    let app_state = app_state.clone();
254                    |cx| async move { restore_or_create_workspace(&app_state, cx).await }
255                })
256                .detach(),
257        }
258
259        let app_state = app_state.clone();
260        cx.spawn(|cx| {
261            async move {
262                while let Some(request) = open_rx.next().await {
263                    match request {
264                        OpenRequest::Paths { paths: _ } => {
265                            // todo!("workspace")
266                            // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
267                            //     .detach();
268                        }
269                        OpenRequest::CliConnection { connection } => {
270                            let app_state = app_state.clone();
271                            cx.spawn(move |cx| {
272                                handle_cli_connection(connection, app_state.clone(), cx)
273                            })
274                            .detach();
275                        }
276                        OpenRequest::JoinChannel { channel_id: _ } => {
277                            // cx
278                            // .update(|cx| {
279                            //     workspace::join_channel(channel_id, app_state.clone(), None, cx)
280                            // })
281                            // .detach()
282                        }
283                    }
284                }
285            }
286        })
287        .detach();
288
289        // if !triggered_authentication {
290        //     cx.spawn(|cx| async move { authenticate(client, &cx).await })
291        //         .detach_and_log_err(cx);
292        // }
293    });
294}
295
296// async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
297//     if stdout_is_a_pty() {
298//         if client::IMPERSONATE_LOGIN.is_some() {
299//             client.authenticate_and_connect(false, &cx).await?;
300//         }
301//     } else if client.has_keychain_credentials(&cx) {
302//         client.authenticate_and_connect(true, &cx).await?;
303//     }
304//     Ok::<_, anyhow::Error>(())
305// }
306
307async fn installation_id() -> Result<String> {
308    let legacy_key_name = "device_id";
309
310    if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(legacy_key_name) {
311        Ok(installation_id)
312    } else {
313        let installation_id = Uuid::new_v4().to_string();
314
315        KEY_VALUE_STORE
316            .write_kvp(legacy_key_name.to_string(), installation_id.clone())
317            .await?;
318
319        Ok(installation_id)
320    }
321}
322
323async fn restore_or_create_workspace(
324    app_state: &Arc<AppState>,
325    mut cx: MainThread<AsyncAppContext>,
326) {
327    async_maybe!({
328        if let Some(location) = workspace2::last_opened_workspace_paths().await {
329            cx.update(|cx| workspace2::open_paths(location.paths().as_ref(), app_state, None, cx))?
330                .await
331                .log_err();
332        } else if matches!(KEY_VALUE_STORE.read_kvp("******* THIS IS A BAD KEY PLEASE UNCOMMENT BELOW TO FIX THIS VERY LONG LINE *******"), Ok(None)) {
333            // todo!(welcome)
334            //} else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
335            //todo!()
336            // cx.update(|cx| show_welcome_experience(app_state, cx));
337        } else {
338            cx.update(|cx| {
339                workspace2::open_new(app_state, cx, |workspace, cx| {
340                    // todo!(editor)
341                    // Editor::new_file(workspace, &Default::default(), cx)
342                })
343                .detach();
344            })?;
345        }
346        anyhow::Ok(())
347    })
348    .await
349    .log_err();
350}
351
352fn init_paths() {
353    std::fs::create_dir_all(&*util::paths::CONFIG_DIR).expect("could not create config path");
354    std::fs::create_dir_all(&*util::paths::LANGUAGES_DIR).expect("could not create languages path");
355    std::fs::create_dir_all(&*util::paths::DB_DIR).expect("could not create database path");
356    std::fs::create_dir_all(&*util::paths::LOGS_DIR).expect("could not create logs path");
357}
358
359fn init_logger() {
360    if stdout_is_a_pty() {
361        env_logger::init();
362    } else {
363        let level = LevelFilter::Info;
364
365        // Prevent log file from becoming too large.
366        const KIB: u64 = 1024;
367        const MIB: u64 = 1024 * KIB;
368        const MAX_LOG_BYTES: u64 = MIB;
369        if std::fs::metadata(&*paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
370        {
371            let _ = std::fs::rename(&*paths::LOG, &*paths::OLD_LOG);
372        }
373
374        let log_file = OpenOptions::new()
375            .create(true)
376            .append(true)
377            .open(&*paths::LOG)
378            .expect("could not open logfile");
379
380        let config = ConfigBuilder::new()
381            .set_time_format_str("%Y-%m-%dT%T") //All timestamps are UTC
382            .build();
383
384        simplelog::WriteLogger::init(level, config, log_file).expect("could not initialize logger");
385    }
386}
387
388#[derive(Serialize, Deserialize)]
389struct LocationData {
390    file: String,
391    line: u32,
392}
393
394#[derive(Serialize, Deserialize)]
395struct Panic {
396    thread: String,
397    payload: String,
398    #[serde(skip_serializing_if = "Option::is_none")]
399    location_data: Option<LocationData>,
400    backtrace: Vec<String>,
401    app_version: String,
402    release_channel: String,
403    os_name: String,
404    os_version: Option<String>,
405    architecture: String,
406    panicked_on: u128,
407    #[serde(skip_serializing_if = "Option::is_none")]
408    installation_id: Option<String>,
409    session_id: String,
410}
411
412#[derive(Serialize)]
413struct PanicRequest {
414    panic: Panic,
415    token: String,
416}
417
418static PANIC_COUNT: AtomicU32 = AtomicU32::new(0);
419
420fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: String) {
421    let is_pty = stdout_is_a_pty();
422    let app_metadata = app.metadata();
423
424    panic::set_hook(Box::new(move |info| {
425        let prior_panic_count = PANIC_COUNT.fetch_add(1, Ordering::SeqCst);
426        if prior_panic_count > 0 {
427            // Give the panic-ing thread time to write the panic file
428            loop {
429                std::thread::yield_now();
430            }
431        }
432
433        let thread = thread::current();
434        let thread_name = thread.name().unwrap_or("<unnamed>");
435
436        let payload = info
437            .payload()
438            .downcast_ref::<&str>()
439            .map(|s| s.to_string())
440            .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
441            .unwrap_or_else(|| "Box<Any>".to_string());
442
443        if *util::channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
444            let location = info.location().unwrap();
445            let backtrace = Backtrace::new();
446            eprintln!(
447                "Thread {:?} panicked with {:?} at {}:{}:{}\n{:?}",
448                thread_name,
449                payload,
450                location.file(),
451                location.line(),
452                location.column(),
453                backtrace,
454            );
455            std::process::exit(-1);
456        }
457
458        let app_version = client2::ZED_APP_VERSION
459            .or(app_metadata.app_version)
460            .map_or("dev".to_string(), |v| v.to_string());
461
462        let backtrace = Backtrace::new();
463        let mut backtrace = backtrace
464            .frames()
465            .iter()
466            .filter_map(|frame| Some(format!("{:#}", frame.symbols().first()?.name()?)))
467            .collect::<Vec<_>>();
468
469        // Strip out leading stack frames for rust panic-handling.
470        if let Some(ix) = backtrace
471            .iter()
472            .position(|name| name == "rust_begin_unwind")
473        {
474            backtrace.drain(0..=ix);
475        }
476
477        let panic_data = Panic {
478            thread: thread_name.into(),
479            payload: payload.into(),
480            location_data: info.location().map(|location| LocationData {
481                file: location.file().into(),
482                line: location.line(),
483            }),
484            app_version: app_version.clone(),
485            release_channel: RELEASE_CHANNEL.display_name().into(),
486            os_name: app_metadata.os_name.into(),
487            os_version: app_metadata
488                .os_version
489                .as_ref()
490                .map(SemanticVersion::to_string),
491            architecture: env::consts::ARCH.into(),
492            panicked_on: SystemTime::now()
493                .duration_since(UNIX_EPOCH)
494                .unwrap()
495                .as_millis(),
496            backtrace,
497            installation_id: installation_id.clone(),
498            session_id: session_id.clone(),
499        };
500
501        if let Some(panic_data_json) = serde_json::to_string_pretty(&panic_data).log_err() {
502            log::error!("{}", panic_data_json);
503        }
504
505        if !is_pty {
506            if let Some(panic_data_json) = serde_json::to_string(&panic_data).log_err() {
507                let timestamp = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
508                let panic_file_path = paths::LOGS_DIR.join(format!("zed-{}.panic", timestamp));
509                let panic_file = std::fs::OpenOptions::new()
510                    .append(true)
511                    .create(true)
512                    .open(&panic_file_path)
513                    .log_err();
514                if let Some(mut panic_file) = panic_file {
515                    writeln!(&mut panic_file, "{}", panic_data_json).log_err();
516                    panic_file.flush().log_err();
517                }
518            }
519        }
520
521        std::process::abort();
522    }));
523}
524
525fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
526    let telemetry_settings = *client2::TelemetrySettings::get_global(cx);
527
528    cx.background_executor()
529        .spawn(async move {
530            let panic_report_url = format!("{}/api/panic", &*client2::ZED_SERVER_URL);
531            let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
532            while let Some(child) = children.next().await {
533                let child = child?;
534                let child_path = child.path();
535
536                if child_path.extension() != Some(OsStr::new("panic")) {
537                    continue;
538                }
539                let filename = if let Some(filename) = child_path.file_name() {
540                    filename.to_string_lossy()
541                } else {
542                    continue;
543                };
544
545                if !filename.starts_with("zed") {
546                    continue;
547                }
548
549                if telemetry_settings.diagnostics {
550                    let panic_file_content = smol::fs::read_to_string(&child_path)
551                        .await
552                        .context("error reading panic file")?;
553
554                    let panic = serde_json::from_str(&panic_file_content)
555                        .ok()
556                        .or_else(|| {
557                            panic_file_content
558                                .lines()
559                                .next()
560                                .and_then(|line| serde_json::from_str(line).ok())
561                        })
562                        .unwrap_or_else(|| {
563                            log::error!(
564                                "failed to deserialize panic file {:?}",
565                                panic_file_content
566                            );
567                            None
568                        });
569
570                    if let Some(panic) = panic {
571                        let body = serde_json::to_string(&PanicRequest {
572                            panic,
573                            token: client2::ZED_SECRET_CLIENT_TOKEN.into(),
574                        })
575                        .unwrap();
576
577                        let request = Request::post(&panic_report_url)
578                            .redirect_policy(isahc::config::RedirectPolicy::Follow)
579                            .header("Content-Type", "application/json")
580                            .body(body.into())?;
581                        let response = http.send(request).await.context("error sending panic")?;
582                        if !response.status().is_success() {
583                            log::error!("Error uploading panic to server: {}", response.status());
584                        }
585                    }
586                }
587
588                // We've done what we can, delete the file
589                std::fs::remove_file(child_path)
590                    .context("error removing panic")
591                    .log_err();
592            }
593            Ok::<_, anyhow::Error>(())
594        })
595        .detach_and_log_err(cx);
596}
597
598async fn load_login_shell_environment() -> Result<()> {
599    let marker = "ZED_LOGIN_SHELL_START";
600    let shell = env::var("SHELL").context(
601        "SHELL environment variable is not assigned so we can't source login environment variables",
602    )?;
603    let output = Command::new(&shell)
604        .args(["-lic", &format!("echo {marker} && /usr/bin/env -0")])
605        .output()
606        .await
607        .context("failed to spawn login shell to source login environment variables")?;
608    if !output.status.success() {
609        Err(anyhow!("login shell exited with error"))?;
610    }
611
612    let stdout = String::from_utf8_lossy(&output.stdout);
613
614    if let Some(env_output_start) = stdout.find(marker) {
615        let env_output = &stdout[env_output_start + marker.len()..];
616        for line in env_output.split_terminator('\0') {
617            if let Some(separator_index) = line.find('=') {
618                let key = &line[..separator_index];
619                let value = &line[separator_index + 1..];
620                env::set_var(key, value);
621            }
622        }
623        log::info!(
624            "set environment variables from shell:{}, path:{}",
625            shell,
626            env::var("PATH").unwrap_or_default(),
627        );
628    }
629
630    Ok(())
631}
632
633fn stdout_is_a_pty() -> bool {
634    std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && std::io::stdout().is_terminal()
635}
636
637fn collect_url_args() -> Vec<String> {
638    env::args()
639        .skip(1)
640        .filter_map(|arg| match std::fs::canonicalize(Path::new(&arg)) {
641            Ok(path) => Some(format!("file://{}", path.to_string_lossy())),
642            Err(error) => {
643                if let Some(_) = parse_zed_link(&arg) {
644                    Some(arg)
645                } else {
646                    log::error!("error parsing path argument: {}", error);
647                    None
648                }
649            }
650        })
651        .collect()
652}
653
654fn load_embedded_fonts(cx: &AppContext) {
655    let asset_source = cx.asset_source();
656    let font_paths = asset_source.list("fonts").unwrap();
657    let embedded_fonts = Mutex::new(Vec::new());
658    let executor = cx.background_executor();
659
660    executor.block(executor.scoped(|scope| {
661        for font_path in &font_paths {
662            if !font_path.ends_with(".ttf") {
663                continue;
664            }
665
666            scope.spawn(async {
667                let font_bytes = asset_source.load(font_path).unwrap().to_vec();
668                embedded_fonts.lock().push(Arc::from(font_bytes));
669            });
670        }
671    }));
672
673    cx.text_system()
674        .add_fonts(&embedded_fonts.into_inner())
675        .unwrap();
676}
677
678// #[cfg(debug_assertions)]
679// async fn watch_themes(fs: Arc<dyn Fs>, mut cx: AsyncAppContext) -> Option<()> {
680//     let mut events = fs
681//         .watch("styles/src".as_ref(), Duration::from_millis(100))
682//         .await;
683//     while (events.next().await).is_some() {
684//         let output = Command::new("npm")
685//             .current_dir("styles")
686//             .args(["run", "build"])
687//             .output()
688//             .await
689//             .log_err()?;
690//         if output.status.success() {
691//             cx.update(|cx| theme_selector::reload(cx))
692//         } else {
693//             eprintln!(
694//                 "build script failed {}",
695//                 String::from_utf8_lossy(&output.stderr)
696//             );
697//         }
698//     }
699//     Some(())
700// }
701
702// #[cfg(debug_assertions)]
703// async fn watch_languages(fs: Arc<dyn Fs>, languages: Arc<LanguageRegistry>) -> Option<()> {
704//     let mut events = fs
705//         .watch(
706//             "crates/zed/src/languages".as_ref(),
707//             Duration::from_millis(100),
708//         )
709//         .await;
710//     while (events.next().await).is_some() {
711//         languages.reload();
712//     }
713//     Some(())
714// }
715
716// #[cfg(debug_assertions)]
717// fn watch_file_types(fs: Arc<dyn Fs>, cx: &mut AppContext) {
718//     cx.spawn(|mut cx| async move {
719//         let mut events = fs
720//             .watch(
721//                 "assets/icons/file_icons/file_types.json".as_ref(),
722//                 Duration::from_millis(100),
723//             )
724//             .await;
725//         while (events.next().await).is_some() {
726//             cx.update(|cx| {
727//                 cx.update_global(|file_types, _| {
728//                     *file_types = project_panel::file_associations::FileAssociations::new(Assets);
729//                 });
730//             })
731//         }
732//     })
733//     .detach()
734// }
735
736// #[cfg(not(debug_assertions))]
737// async fn watch_themes(_fs: Arc<dyn Fs>, _cx: AsyncAppContext) -> Option<()> {
738//     None
739// }
740
741// #[cfg(not(debug_assertions))]
742// async fn watch_languages(_: Arc<dyn Fs>, _: Arc<LanguageRegistry>) -> Option<()> {
743//     None
744// }
745
746// #[cfg(not(debug_assertions))]
747// fn watch_file_types(_fs: Arc<dyn Fs>, _cx: &mut AppContext) {}
748
749fn connect_to_cli(
750    server_name: &str,
751) -> Result<(mpsc::Receiver<CliRequest>, IpcSender<CliResponse>)> {
752    let handshake_tx = cli::ipc::IpcSender::<IpcHandshake>::connect(server_name.to_string())
753        .context("error connecting to cli")?;
754    let (request_tx, request_rx) = ipc::channel::<CliRequest>()?;
755    let (response_tx, response_rx) = ipc::channel::<CliResponse>()?;
756
757    handshake_tx
758        .send(IpcHandshake {
759            requests: request_tx,
760            responses: response_rx,
761        })
762        .context("error sending ipc handshake")?;
763
764    let (mut async_request_tx, async_request_rx) =
765        futures::channel::mpsc::channel::<CliRequest>(16);
766    thread::spawn(move || {
767        while let Ok(cli_request) = request_rx.recv() {
768            if smol::block_on(async_request_tx.send(cli_request)).is_err() {
769                break;
770            }
771        }
772        Ok::<_, anyhow::Error>(())
773    });
774
775    Ok((async_request_rx, response_tx))
776}
777
778async fn handle_cli_connection(
779    (mut requests, _responses): (mpsc::Receiver<CliRequest>, IpcSender<CliResponse>),
780    _app_state: Arc<AppState>,
781    mut _cx: AsyncAppContext,
782) {
783    if let Some(request) = requests.next().await {
784        match request {
785            CliRequest::Open { paths: _, wait: _ } => {
786                // let mut caret_positions = HashMap::new();
787
788                // todo!("workspace")
789                // let paths = if paths.is_empty() {
790                // workspace::last_opened_workspace_paths()
791                //     .await
792                //     .map(|location| location.paths().to_vec())
793                //     .unwrap_or_default()
794                // } else {
795                //     paths
796                //         .into_iter()
797                //         .filter_map(|path_with_position_string| {
798                //             let path_with_position = PathLikeWithPosition::parse_str(
799                //                 &path_with_position_string,
800                //                 |path_str| {
801                //                     Ok::<_, std::convert::Infallible>(
802                //                         Path::new(path_str).to_path_buf(),
803                //                     )
804                //                 },
805                //             )
806                //             .expect("Infallible");
807                //             let path = path_with_position.path_like;
808                //             if let Some(row) = path_with_position.row {
809                //                 if path.is_file() {
810                //                     let row = row.saturating_sub(1);
811                //                     let col =
812                //                         path_with_position.column.unwrap_or(0).saturating_sub(1);
813                //                     caret_positions.insert(path.clone(), Point::new(row, col));
814                //                 }
815                //             }
816                //             Some(path)
817                //         })
818                //         .collect()
819                // };
820
821                // let mut errored = false;
822                // match cx
823                //     .update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
824                //     .await
825                // {
826                //     Ok((workspace, items)) => {
827                //         let mut item_release_futures = Vec::new();
828
829                //         for (item, path) in items.into_iter().zip(&paths) {
830                //             match item {
831                //                 Some(Ok(item)) => {
832                //                     if let Some(point) = caret_positions.remove(path) {
833                //                         if let Some(active_editor) = item.downcast::<Editor>() {
834                //                             active_editor
835                //                                 .downgrade()
836                //                                 .update(&mut cx, |editor, cx| {
837                //                                     let snapshot =
838                //                                         editor.snapshot(cx).display_snapshot;
839                //                                     let point = snapshot
840                //                                         .buffer_snapshot
841                //                                         .clip_point(point, Bias::Left);
842                //                                     editor.change_selections(
843                //                                         Some(Autoscroll::center()),
844                //                                         cx,
845                //                                         |s| s.select_ranges([point..point]),
846                //                                     );
847                //                                 })
848                //                                 .log_err();
849                //                         }
850                //                     }
851
852                //                     let released = oneshot::channel();
853                //                     cx.update(|cx| {
854                //                         item.on_release(
855                //                             cx,
856                //                             Box::new(move |_| {
857                //                                 let _ = released.0.send(());
858                //                             }),
859                //                         )
860                //                         .detach();
861                //                     });
862                //                     item_release_futures.push(released.1);
863                //                 }
864                //                 Some(Err(err)) => {
865                //                     responses
866                //                         .send(CliResponse::Stderr {
867                //                             message: format!("error opening {:?}: {}", path, err),
868                //                         })
869                //                         .log_err();
870                //                     errored = true;
871                //                 }
872                //                 None => {}
873                //             }
874                //         }
875
876                //         if wait {
877                //             let background = cx.background();
878                //             let wait = async move {
879                //                 if paths.is_empty() {
880                //                     let (done_tx, done_rx) = oneshot::channel();
881                //                     if let Some(workspace) = workspace.upgrade(&cx) {
882                //                         let _subscription = cx.update(|cx| {
883                //                             cx.observe_release(&workspace, move |_, _| {
884                //                                 let _ = done_tx.send(());
885                //                             })
886                //                         });
887                //                         drop(workspace);
888                //                         let _ = done_rx.await;
889                //                     }
890                //                 } else {
891                //                     let _ =
892                //                         futures::future::try_join_all(item_release_futures).await;
893                //                 };
894                //             }
895                //             .fuse();
896                //             futures::pin_mut!(wait);
897
898                //             loop {
899                //                 // Repeatedly check if CLI is still open to avoid wasting resources
900                //                 // waiting for files or workspaces to close.
901                //                 let mut timer = background.timer(Duration::from_secs(1)).fuse();
902                //                 futures::select_biased! {
903                //                     _ = wait => break,
904                //                     _ = timer => {
905                //                         if responses.send(CliResponse::Ping).is_err() {
906                //                             break;
907                //                         }
908                //                     }
909                //                 }
910                //             }
911                //         }
912                //     }
913                //     Err(error) => {
914                //         errored = true;
915                //         responses
916                //             .send(CliResponse::Stderr {
917                //                 message: format!("error opening {:?}: {}", paths, error),
918                //             })
919                //             .log_err();
920                //     }
921                // }
922
923                // responses
924                //     .send(CliResponse::Exit {
925                //         status: i32::from(errored),
926                //     })
927                //     .log_err();
928            }
929        }
930    }
931}
932
933pub fn background_actions() -> &'static [(&'static str, &'static dyn Action)] {
934    // &[
935    //     ("Go to file", &file_finder::Toggle),
936    //     ("Open command palette", &command_palette::Toggle),
937    //     ("Open recent projects", &recent_projects::OpenRecent),
938    //     ("Change your settings", &zed_actions::OpenSettings),
939    // ]
940    // todo!()
941    &[]
942}