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