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