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