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