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