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