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