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