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