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