main.rs

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