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, Result};
6use backtrace::Backtrace;
7use cli::{
8 ipc::{self, IpcSender},
9 CliRequest, CliResponse, IpcHandshake, FORCE_CLI_MODE_ENV_VAR_NAME,
10};
11use fs::RealFs;
12use futures::{channel::mpsc, SinkExt, StreamExt};
13use gpui2::{App, AppContext, AssetSource, AsyncAppContext, SemanticVersion, Task};
14use isahc::{prelude::Configurable, Request};
15use log::LevelFilter;
16
17use parking_lot::Mutex;
18use serde::{Deserialize, Serialize};
19use settings2::{default_settings, handle_settings_file_changes, watch_config_file, SettingsStore};
20use simplelog::ConfigBuilder;
21use smol::process::Command;
22use std::{
23 env,
24 ffi::OsStr,
25 fs::OpenOptions,
26 io::{IsTerminal, Write},
27 panic,
28 path::Path,
29 sync::{
30 atomic::{AtomicU32, Ordering},
31 Arc,
32 },
33 thread,
34 time::{SystemTime, UNIX_EPOCH},
35};
36use util::{
37 channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
38 http::HttpClient,
39 paths, ResultExt,
40};
41use zed2::{ensure_only_instance, AppState, Assets, IsOnlyInstance};
42// use zed2::{
43// assets::Assets,
44// build_window_options, handle_keymap_file_changes, initialize_workspace, languages, menus,
45// only_instance::{ensure_only_instance, IsOnlyInstance},
46// };
47
48mod open_listener;
49
50fn main() {
51 // let http = http::client();
52 init_paths();
53 init_logger();
54
55 if ensure_only_instance() != IsOnlyInstance::Yes {
56 return;
57 }
58
59 log::info!("========== starting zed ==========");
60 let app = App::production(Arc::new(Assets));
61
62 // let installation_id = app.background().block(installation_id()).ok();
63 // let session_id = Uuid::new_v4().to_string();
64 // init_panic_hook(&app, installation_id.clone(), session_id.clone());
65
66 load_embedded_fonts(&app);
67
68 let fs = Arc::new(RealFs);
69 let user_settings_file_rx =
70 watch_config_file(&app.executor(), fs.clone(), paths::SETTINGS.clone());
71 let _user_keymap_file_rx =
72 watch_config_file(&app.executor(), fs.clone(), paths::KEYMAP.clone());
73
74 let _login_shell_env_loaded = if stdout_is_a_pty() {
75 Task::ready(())
76 } else {
77 app.executor().spawn(async {
78 load_login_shell_environment().await.log_err();
79 })
80 };
81
82 let (listener, mut open_rx) = OpenListener::new();
83 let listener = Arc::new(listener);
84 let open_listener = listener.clone();
85 app.on_open_urls(move |urls, _| open_listener.open_urls(urls));
86 app.on_reopen(move |_cx| {
87 // todo!("workspace")
88 // if cx.has_global::<Weak<AppState>>() {
89 // if let Some(app_state) = cx.global::<Weak<AppState>>().upgrade() {
90 // workspace::open_new(&app_state, cx, |workspace, cx| {
91 // Editor::new_file(workspace, &Default::default(), cx)
92 // })
93 // .detach();
94 // }
95 // }
96 });
97
98 app.run(move |cx| {
99 cx.set_global(*RELEASE_CHANNEL);
100
101 let mut store = SettingsStore::default();
102 store
103 .set_default_settings(default_settings().as_ref(), cx)
104 .unwrap();
105 cx.set_global(store);
106 handle_settings_file_changes(user_settings_file_rx, cx);
107 // handle_keymap_file_changes(user_keymap_file_rx, cx);
108
109 // let client = client::Client::new(http.clone(), cx);
110 // let mut languages = LanguageRegistry::new(login_shell_env_loaded);
111 // let copilot_language_server_id = languages.next_language_server_id();
112 // languages.set_executor(cx.background().clone());
113 // languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
114 // let languages = Arc::new(languages);
115 // let node_runtime = RealNodeRuntime::new(http.clone());
116
117 // languages::init(languages.clone(), node_runtime.clone(), cx);
118 // let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http.clone(), cx));
119 // let workspace_store = cx.add_model(|cx| WorkspaceStore::new(client.clone(), cx));
120
121 // cx.set_global(client.clone());
122
123 // theme::init(Assets, cx);
124 // context_menu::init(cx);
125 // project::Project::init(&client, cx);
126 // client::init(&client, cx);
127 // command_palette::init(cx);
128 // language::init(cx);
129 // editor::init(cx);
130 // go_to_line::init(cx);
131 // file_finder::init(cx);
132 // outline::init(cx);
133 // project_symbols::init(cx);
134 // project_panel::init(Assets, cx);
135 // channel::init(&client, user_store.clone(), cx);
136 // diagnostics::init(cx);
137 // search::init(cx);
138 // semantic_index::init(fs.clone(), http.clone(), languages.clone(), cx);
139 // vim::init(cx);
140 // terminal_view::init(cx);
141 // copilot::init(
142 // copilot_language_server_id,
143 // http.clone(),
144 // node_runtime.clone(),
145 // cx,
146 // );
147 // assistant::init(cx);
148 // component_test::init(cx);
149
150 // cx.spawn(|cx| watch_themes(fs.clone(), cx)).detach();
151 // cx.spawn(|_| watch_languages(fs.clone(), languages.clone()))
152 // .detach();
153 // watch_file_types(fs.clone(), cx);
154
155 // languages.set_theme(theme::current(cx).clone());
156 // cx.observe_global::<SettingsStore, _>({
157 // let languages = languages.clone();
158 // move |cx| languages.set_theme(theme::current(cx).clone())
159 // })
160 // .detach();
161
162 // client.telemetry().start(installation_id, session_id, cx);
163
164 // todo!("app_state")
165 let app_state = Arc::new(AppState);
166 // let app_state = Arc::new(AppState {
167 // languages,
168 // client: client.clone(),
169 // user_store,
170 // fs,
171 // build_window_options,
172 // initialize_workspace,
173 // background_actions,
174 // workspace_store,
175 // node_runtime,
176 // });
177 // cx.set_global(Arc::downgrade(&app_state));
178
179 // audio::init(Assets, cx);
180 // auto_update::init(http.clone(), client::ZED_SERVER_URL.clone(), cx);
181
182 // todo!("workspace")
183 // workspace::init(app_state.clone(), cx);
184 // recent_projects::init(cx);
185
186 // journal::init(app_state.clone(), cx);
187 // language_selector::init(cx);
188 // theme_selector::init(cx);
189 // activity_indicator::init(cx);
190 // language_tools::init(cx);
191 // call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
192 // collab_ui::init(&app_state, cx);
193 // feedback::init(cx);
194 // welcome::init(cx);
195 // zed::init(&app_state, cx);
196
197 // cx.set_menus(menus::menus());
198
199 if stdout_is_a_pty() {
200 cx.activate(true);
201 let urls = collect_url_args();
202 if !urls.is_empty() {
203 listener.open_urls(urls)
204 }
205 } else {
206 // upload_previous_panics(http.clone(), cx);
207
208 // TODO Development mode that forces the CLI mode usually runs Zed binary as is instead
209 // of an *app, hence gets no specific callbacks run. Emulate them here, if needed.
210 if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some()
211 && !listener.triggered.load(Ordering::Acquire)
212 {
213 listener.open_urls(collect_url_args())
214 }
215 }
216
217 let mut _triggered_authentication = false;
218
219 match open_rx.try_next() {
220 Ok(Some(OpenRequest::Paths { paths: _ })) => {
221 // todo!("workspace")
222 // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
223 // .detach();
224 }
225 Ok(Some(OpenRequest::CliConnection { connection })) => {
226 let app_state = app_state.clone();
227 cx.spawn(move |cx| handle_cli_connection(connection, app_state, cx))
228 .detach();
229 }
230 Ok(Some(OpenRequest::JoinChannel { channel_id: _ })) => {
231 // triggered_authentication = true;
232 // let app_state = app_state.clone();
233 // let client = client.clone();
234 // cx.spawn(|mut cx| async move {
235 // // ignore errors here, we'll show a generic "not signed in"
236 // let _ = authenticate(client, &cx).await;
237 // cx.update(|cx| workspace::join_channel(channel_id, app_state, None, cx))
238 // .await
239 // })
240 // .detach_and_log_err(cx)
241 }
242 Ok(None) | Err(_) => cx
243 .spawn({
244 let app_state = app_state.clone();
245 |cx| async move { restore_or_create_workspace(&app_state, cx).await }
246 })
247 .detach(),
248 }
249
250 let app_state = app_state.clone();
251 cx.spawn(|cx| {
252 async move {
253 while let Some(request) = open_rx.next().await {
254 match request {
255 OpenRequest::Paths { paths: _ } => {
256 // todo!("workspace")
257 // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
258 // .detach();
259 }
260 OpenRequest::CliConnection { connection } => {
261 let app_state = app_state.clone();
262 if cx
263 .spawn(move |cx| {
264 handle_cli_connection(connection, app_state.clone(), cx)
265 })
266 .map(Task::detach)
267 .is_err()
268 {
269 break;
270 }
271 }
272 OpenRequest::JoinChannel { channel_id: _ } => {
273 // cx
274 // .update(|cx| {
275 // workspace::join_channel(channel_id, app_state.clone(), None, cx)
276 // })
277 // .detach()
278 }
279 }
280 }
281 }
282 })
283 .detach();
284
285 // if !triggered_authentication {
286 // cx.spawn(|cx| async move { authenticate(client, &cx).await })
287 // .detach_and_log_err(cx);
288 // }
289 });
290}
291
292// async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
293// if stdout_is_a_pty() {
294// if client::IMPERSONATE_LOGIN.is_some() {
295// client.authenticate_and_connect(false, &cx).await?;
296// }
297// } else if client.has_keychain_credentials(&cx) {
298// client.authenticate_and_connect(true, &cx).await?;
299// }
300// Ok::<_, anyhow::Error>(())
301// }
302
303// async fn installation_id() -> Result<String> {
304// let legacy_key_name = "device_id";
305
306// if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(legacy_key_name) {
307// Ok(installation_id)
308// } else {
309// let installation_id = Uuid::new_v4().to_string();
310
311// KEY_VALUE_STORE
312// .write_kvp(legacy_key_name.to_string(), installation_id.clone())
313// .await?;
314
315// Ok(installation_id)
316// }
317// }
318
319async fn restore_or_create_workspace(_app_state: &Arc<AppState>, mut _cx: AsyncAppContext) {
320 todo!("workspace")
321 // if let Some(location) = workspace::last_opened_workspace_paths().await {
322 // cx.update(|cx| workspace::open_paths(location.paths().as_ref(), app_state, None, cx))
323 // .await
324 // .log_err();
325 // } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
326 // cx.update(|cx| show_welcome_experience(app_state, cx));
327 // } else {
328 // cx.update(|cx| {
329 // workspace::open_new(app_state, cx, |workspace, cx| {
330 // Editor::new_file(workspace, &Default::default(), cx)
331 // })
332 // .detach();
333 // });
334 // }
335}
336
337fn init_paths() {
338 std::fs::create_dir_all(&*util::paths::CONFIG_DIR).expect("could not create config path");
339 std::fs::create_dir_all(&*util::paths::LANGUAGES_DIR).expect("could not create languages path");
340 std::fs::create_dir_all(&*util::paths::DB_DIR).expect("could not create database path");
341 std::fs::create_dir_all(&*util::paths::LOGS_DIR).expect("could not create logs path");
342}
343
344fn init_logger() {
345 if stdout_is_a_pty() {
346 env_logger::init();
347 } else {
348 let level = LevelFilter::Info;
349
350 // Prevent log file from becoming too large.
351 const KIB: u64 = 1024;
352 const MIB: u64 = 1024 * KIB;
353 const MAX_LOG_BYTES: u64 = MIB;
354 if std::fs::metadata(&*paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
355 {
356 let _ = std::fs::rename(&*paths::LOG, &*paths::OLD_LOG);
357 }
358
359 let log_file = OpenOptions::new()
360 .create(true)
361 .append(true)
362 .open(&*paths::LOG)
363 .expect("could not open logfile");
364
365 let config = ConfigBuilder::new()
366 .set_time_format_str("%Y-%m-%dT%T") //All timestamps are UTC
367 .build();
368
369 simplelog::WriteLogger::init(level, config, log_file).expect("could not initialize logger");
370 }
371}
372
373#[derive(Serialize, Deserialize)]
374struct LocationData {
375 file: String,
376 line: u32,
377}
378
379#[derive(Serialize, Deserialize)]
380struct Panic {
381 thread: String,
382 payload: String,
383 #[serde(skip_serializing_if = "Option::is_none")]
384 location_data: Option<LocationData>,
385 backtrace: Vec<String>,
386 app_version: String,
387 release_channel: String,
388 os_name: String,
389 os_version: Option<String>,
390 architecture: String,
391 panicked_on: u128,
392 #[serde(skip_serializing_if = "Option::is_none")]
393 installation_id: Option<String>,
394 session_id: String,
395}
396
397#[derive(Serialize)]
398struct PanicRequest {
399 panic: Panic,
400 token: String,
401}
402
403static PANIC_COUNT: AtomicU32 = AtomicU32::new(0);
404
405fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: String) {
406 let is_pty = stdout_is_a_pty();
407 let app_version = app.app_version().ok();
408 let os_name = app.os_name();
409 let os_version = app.os_version().ok();
410
411 panic::set_hook(Box::new(move |info| {
412 let prior_panic_count = PANIC_COUNT.fetch_add(1, Ordering::SeqCst);
413 if prior_panic_count > 0 {
414 // Give the panic-ing thread time to write the panic file
415 loop {
416 std::thread::yield_now();
417 }
418 }
419
420 let thread = thread::current();
421 let thread_name = thread.name().unwrap_or("<unnamed>");
422
423 let payload = info
424 .payload()
425 .downcast_ref::<&str>()
426 .map(|s| s.to_string())
427 .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
428 .unwrap_or_else(|| "Box<Any>".to_string());
429
430 if *util::channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
431 let location = info.location().unwrap();
432 let backtrace = Backtrace::new();
433 eprintln!(
434 "Thread {:?} panicked with {:?} at {}:{}:{}\n{:?}",
435 thread_name,
436 payload,
437 location.file(),
438 location.line(),
439 location.column(),
440 backtrace,
441 );
442 std::process::exit(-1);
443 }
444
445 let app_version = client::ZED_APP_VERSION
446 .or(app_version)
447 .map_or("dev".to_string(), |v| v.to_string());
448
449 let backtrace = Backtrace::new();
450 let mut backtrace = backtrace
451 .frames()
452 .iter()
453 .filter_map(|frame| Some(format!("{:#}", frame.symbols().first()?.name()?)))
454 .collect::<Vec<_>>();
455
456 // Strip out leading stack frames for rust panic-handling.
457 if let Some(ix) = backtrace
458 .iter()
459 .position(|name| name == "rust_begin_unwind")
460 {
461 backtrace.drain(0..=ix);
462 }
463
464 let panic_data = Panic {
465 thread: thread_name.into(),
466 payload: payload.into(),
467 location_data: info.location().map(|location| LocationData {
468 file: location.file().into(),
469 line: location.line(),
470 }),
471 app_version: app_version.clone(),
472 release_channel: RELEASE_CHANNEL.display_name().into(),
473 os_name: os_name.into(),
474 os_version: os_version.as_ref().map(SemanticVersion::to_string),
475 architecture: env::consts::ARCH.into(),
476 panicked_on: SystemTime::now()
477 .duration_since(UNIX_EPOCH)
478 .unwrap()
479 .as_millis(),
480 backtrace,
481 installation_id: installation_id.clone(),
482 session_id: session_id.clone(),
483 };
484
485 if let Some(panic_data_json) = serde_json::to_string_pretty(&panic_data).log_err() {
486 log::error!("{}", panic_data_json);
487 }
488
489 if !is_pty {
490 if let Some(panic_data_json) = serde_json::to_string(&panic_data).log_err() {
491 let timestamp = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
492 let panic_file_path = paths::LOGS_DIR.join(format!("zed-{}.panic", timestamp));
493 let panic_file = std::fs::OpenOptions::new()
494 .append(true)
495 .create(true)
496 .open(&panic_file_path)
497 .log_err();
498 if let Some(mut panic_file) = panic_file {
499 writeln!(&mut panic_file, "{}", panic_data_json).log_err();
500 panic_file.flush().log_err();
501 }
502 }
503 }
504
505 std::process::abort();
506 }));
507}
508
509fn upload_previous_panics(http: Arc<dyn HttpClient>, cx: &mut AppContext) {
510 let telemetry_settings = *settings2::get::<client::TelemetrySettings>(cx);
511
512 cx.executor()
513 .spawn(async move {
514 let panic_report_url = format!("{}/api/panic", &*client::ZED_SERVER_URL);
515 let mut children = smol::fs::read_dir(&*paths::LOGS_DIR).await?;
516 while let Some(child) = children.next().await {
517 let child = child?;
518 let child_path = child.path();
519
520 if child_path.extension() != Some(OsStr::new("panic")) {
521 continue;
522 }
523 let filename = if let Some(filename) = child_path.file_name() {
524 filename.to_string_lossy()
525 } else {
526 continue;
527 };
528
529 if !filename.starts_with("zed") {
530 continue;
531 }
532
533 if telemetry_settings.diagnostics {
534 let panic_file_content = smol::fs::read_to_string(&child_path)
535 .await
536 .context("error reading panic file")?;
537
538 let panic = serde_json::from_str(&panic_file_content)
539 .ok()
540 .or_else(|| {
541 panic_file_content
542 .lines()
543 .next()
544 .and_then(|line| serde_json::from_str(line).ok())
545 })
546 .unwrap_or_else(|| {
547 log::error!(
548 "failed to deserialize panic file {:?}",
549 panic_file_content
550 );
551 None
552 });
553
554 if let Some(panic) = panic {
555 let body = serde_json::to_string(&PanicRequest {
556 panic,
557 token: client::ZED_SECRET_CLIENT_TOKEN.into(),
558 })
559 .unwrap();
560
561 let request = Request::post(&panic_report_url)
562 .redirect_policy(isahc::config::RedirectPolicy::Follow)
563 .header("Content-Type", "application/json")
564 .body(body.into())?;
565 let response = http.send(request).await.context("error sending panic")?;
566 if !response.status().is_success() {
567 log::error!("Error uploading panic to server: {}", response.status());
568 }
569 }
570 }
571
572 // We've done what we can, delete the file
573 std::fs::remove_file(child_path)
574 .context("error removing panic")
575 .log_err();
576 }
577 Ok::<_, anyhow::Error>(())
578 })
579 .detach_and_log_err(cx);
580}
581
582async fn load_login_shell_environment() -> Result<()> {
583 let marker = "ZED_LOGIN_SHELL_START";
584 let shell = env::var("SHELL").context(
585 "SHELL environment variable is not assigned so we can't source login environment variables",
586 )?;
587 let output = Command::new(&shell)
588 .args(["-lic", &format!("echo {marker} && /usr/bin/env -0")])
589 .output()
590 .await
591 .context("failed to spawn login shell to source login environment variables")?;
592 if !output.status.success() {
593 Err(anyhow!("login shell exited with error"))?;
594 }
595
596 let stdout = String::from_utf8_lossy(&output.stdout);
597
598 if let Some(env_output_start) = stdout.find(marker) {
599 let env_output = &stdout[env_output_start + marker.len()..];
600 for line in env_output.split_terminator('\0') {
601 if let Some(separator_index) = line.find('=') {
602 let key = &line[..separator_index];
603 let value = &line[separator_index + 1..];
604 env::set_var(key, value);
605 }
606 }
607 log::info!(
608 "set environment variables from shell:{}, path:{}",
609 shell,
610 env::var("PATH").unwrap_or_default(),
611 );
612 }
613
614 Ok(())
615}
616
617fn stdout_is_a_pty() -> bool {
618 std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_none() && std::io::stdout().is_terminal()
619}
620
621fn collect_url_args() -> Vec<String> {
622 env::args()
623 .skip(1)
624 .filter_map(|arg| match std::fs::canonicalize(Path::new(&arg)) {
625 Ok(path) => Some(format!("file://{}", path.to_string_lossy())),
626 Err(error) => {
627 if let Some(_) = parse_zed_link(&arg) {
628 Some(arg)
629 } else {
630 log::error!("error parsing path argument: {}", error);
631 None
632 }
633 }
634 })
635 .collect()
636}
637
638fn load_embedded_fonts(app: &App) {
639 let font_paths = Assets.list(&"fonts".into()).unwrap();
640 let embedded_fonts = Mutex::new(Vec::new());
641 let executor = app.executor();
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_path = &*font_path;
650 let font_bytes = Assets.load(font_path).unwrap().to_vec();
651 embedded_fonts.lock().push(Arc::from(font_bytes));
652 });
653 }
654 }));
655 app.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
915// pub 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// }