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 node_runtime::RealNodeRuntime;
20use parking_lot::Mutex;
21use serde::{Deserialize, Serialize};
22use settings2::{default_settings, handle_settings_file_changes, watch_config_file, SettingsStore};
23use simplelog::ConfigBuilder;
24use smol::process::Command;
25use std::{
26 env,
27 ffi::OsStr,
28 fs::OpenOptions,
29 io::{IsTerminal, Write},
30 panic,
31 path::Path,
32 sync::{
33 atomic::{AtomicU32, Ordering},
34 Arc,
35 },
36 thread,
37 time::{SystemTime, UNIX_EPOCH},
38};
39use util::{
40 channel::{parse_zed_link, ReleaseChannel, RELEASE_CHANNEL},
41 http::{self, HttpClient},
42 paths, ResultExt,
43};
44use uuid::Uuid;
45use zed2::{ensure_only_instance, AppState, Assets, IsOnlyInstance};
46// use zed2::{
47// assets::Assets,
48// build_window_options, handle_keymap_file_changes, initialize_workspace, languages, menus,
49// only_instance::{ensure_only_instance, IsOnlyInstance},
50// };
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 load_embedded_fonts(&app);
71
72 let fs = Arc::new(RealFs);
73 let user_settings_file_rx =
74 watch_config_file(&app.executor(), fs.clone(), paths::SETTINGS.clone());
75 let _user_keymap_file_rx =
76 watch_config_file(&app.executor(), fs.clone(), paths::KEYMAP.clone());
77
78 let login_shell_env_loaded = if stdout_is_a_pty() {
79 Task::ready(())
80 } else {
81 app.executor().spawn(async {
82 load_login_shell_environment().await.log_err();
83 })
84 };
85
86 let (listener, mut open_rx) = OpenListener::new();
87 let listener = Arc::new(listener);
88 let open_listener = listener.clone();
89 app.on_open_urls(move |urls, _| open_listener.open_urls(urls));
90 app.on_reopen(move |_cx| {
91 // todo!("workspace")
92 // if cx.has_global::<Weak<AppState>>() {
93 // if let Some(app_state) = cx.global::<Weak<AppState>>().upgrade() {
94 // workspace::open_new(&app_state, cx, |workspace, cx| {
95 // Editor::new_file(workspace, &Default::default(), cx)
96 // })
97 // .detach();
98 // }
99 // }
100 });
101
102 app.run(move |cx| {
103 cx.set_global(*RELEASE_CHANNEL);
104
105 let mut store = SettingsStore::default();
106 store
107 .set_default_settings(default_settings().as_ref(), cx)
108 .unwrap();
109 cx.set_global(store);
110 handle_settings_file_changes(user_settings_file_rx, cx);
111 // handle_keymap_file_changes(user_keymap_file_rx, cx);
112
113 // let client = client2::Client::new(http.clone(), cx);
114 let mut languages = LanguageRegistry::new(login_shell_env_loaded);
115 let copilot_language_server_id = languages.next_language_server_id();
116 // languages.set_executor(cx.background().clone());
117 // languages.set_language_server_download_dir(paths::LANGUAGES_DIR.clone());
118 // let languages = Arc::new(languages);
119 let node_runtime = RealNodeRuntime::new(http.clone());
120
121 // languages::init(languages.clone(), node_runtime.clone(), cx);
122 // let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http.clone(), cx));
123 // let workspace_store = cx.add_model(|cx| WorkspaceStore::new(client.clone(), cx));
124
125 // cx.set_global(client.clone());
126
127 // theme::init(Assets, cx);
128 // context_menu::init(cx);
129 // project::Project::init(&client, cx);
130 // client::init(&client, cx);
131 // command_palette::init(cx);
132 // language::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 // todo!("app_state")
169 let app_state = Arc::new(AppState);
170 // let app_state = Arc::new(AppState {
171 // languages,
172 // client: client.clone(),
173 // user_store,
174 // fs,
175 // build_window_options,
176 // initialize_workspace,
177 // background_actions,
178 // workspace_store,
179 // node_runtime,
180 // });
181 // cx.set_global(Arc::downgrade(&app_state));
182
183 // audio::init(Assets, cx);
184 // auto_update::init(http.clone(), client::ZED_SERVER_URL.clone(), cx);
185
186 // todo!("workspace")
187 // workspace::init(app_state.clone(), cx);
188 // recent_projects::init(cx);
189
190 // journal::init(app_state.clone(), cx);
191 // language_selector::init(cx);
192 // theme_selector::init(cx);
193 // activity_indicator::init(cx);
194 // language_tools::init(cx);
195 // call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
196 // collab_ui::init(&app_state, cx);
197 // feedback::init(cx);
198 // welcome::init(cx);
199 // zed::init(&app_state, cx);
200
201 // cx.set_menus(menus::menus());
202
203 if stdout_is_a_pty() {
204 cx.activate(true);
205 let urls = collect_url_args();
206 if !urls.is_empty() {
207 listener.open_urls(urls)
208 }
209 } else {
210 upload_previous_panics(http.clone(), cx);
211
212 // TODO Development mode that forces the CLI mode usually runs Zed binary as is instead
213 // of an *app, hence gets no specific callbacks run. Emulate them here, if needed.
214 if std::env::var(FORCE_CLI_MODE_ENV_VAR_NAME).ok().is_some()
215 && !listener.triggered.load(Ordering::Acquire)
216 {
217 listener.open_urls(collect_url_args())
218 }
219 }
220
221 let mut _triggered_authentication = false;
222
223 match open_rx.try_next() {
224 Ok(Some(OpenRequest::Paths { paths: _ })) => {
225 // todo!("workspace")
226 // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
227 // .detach();
228 }
229 Ok(Some(OpenRequest::CliConnection { connection })) => {
230 let app_state = app_state.clone();
231 cx.spawn(move |cx| handle_cli_connection(connection, app_state, cx))
232 .detach();
233 }
234 Ok(Some(OpenRequest::JoinChannel { channel_id: _ })) => {
235 // triggered_authentication = true;
236 // let app_state = app_state.clone();
237 // let client = client.clone();
238 // cx.spawn(|mut cx| async move {
239 // // ignore errors here, we'll show a generic "not signed in"
240 // let _ = authenticate(client, &cx).await;
241 // cx.update(|cx| workspace::join_channel(channel_id, app_state, None, cx))
242 // .await
243 // })
244 // .detach_and_log_err(cx)
245 }
246 Ok(None) | Err(_) => cx
247 .spawn({
248 let app_state = app_state.clone();
249 |cx| async move { restore_or_create_workspace(&app_state, cx).await }
250 })
251 .detach(),
252 }
253
254 let app_state = app_state.clone();
255 cx.spawn(|cx| {
256 async move {
257 while let Some(request) = open_rx.next().await {
258 match request {
259 OpenRequest::Paths { paths: _ } => {
260 // todo!("workspace")
261 // cx.update(|cx| workspace::open_paths(&paths, &app_state, None, cx))
262 // .detach();
263 }
264 OpenRequest::CliConnection { connection } => {
265 let app_state = app_state.clone();
266 cx.spawn(move |cx| {
267 handle_cli_connection(connection, app_state.clone(), cx)
268 })
269 .detach();
270 }
271 OpenRequest::JoinChannel { channel_id: _ } => {
272 // cx
273 // .update(|cx| {
274 // workspace::join_channel(channel_id, app_state.clone(), None, cx)
275 // })
276 // .detach()
277 }
278 }
279 }
280 }
281 })
282 .detach();
283
284 // if !triggered_authentication {
285 // cx.spawn(|cx| async move { authenticate(client, &cx).await })
286 // .detach_and_log_err(cx);
287 // }
288 });
289}
290
291// async fn authenticate(client: Arc<Client>, cx: &AsyncAppContext) -> Result<()> {
292// if stdout_is_a_pty() {
293// if client::IMPERSONATE_LOGIN.is_some() {
294// client.authenticate_and_connect(false, &cx).await?;
295// }
296// } else if client.has_keychain_credentials(&cx) {
297// client.authenticate_and_connect(true, &cx).await?;
298// }
299// Ok::<_, anyhow::Error>(())
300// }
301
302async fn installation_id() -> Result<String> {
303 let legacy_key_name = "device_id";
304
305 if let Ok(Some(installation_id)) = KEY_VALUE_STORE.read_kvp(legacy_key_name) {
306 Ok(installation_id)
307 } else {
308 let installation_id = Uuid::new_v4().to_string();
309
310 KEY_VALUE_STORE
311 .write_kvp(legacy_key_name.to_string(), installation_id.clone())
312 .await?;
313
314 Ok(installation_id)
315 }
316}
317
318async fn restore_or_create_workspace(_app_state: &Arc<AppState>, mut _cx: AsyncAppContext) {
319 todo!("workspace")
320 // if let Some(location) = workspace::last_opened_workspace_paths().await {
321 // cx.update(|cx| workspace::open_paths(location.paths().as_ref(), app_state, None, cx))
322 // .await
323 // .log_err();
324 // } else if matches!(KEY_VALUE_STORE.read_kvp(FIRST_OPEN), Ok(None)) {
325 // cx.update(|cx| show_welcome_experience(app_state, cx));
326 // } else {
327 // cx.update(|cx| {
328 // workspace::open_new(app_state, cx, |workspace, cx| {
329 // Editor::new_file(workspace, &Default::default(), cx)
330 // })
331 // .detach();
332 // });
333 // }
334}
335
336fn init_paths() {
337 std::fs::create_dir_all(&*util::paths::CONFIG_DIR).expect("could not create config path");
338 std::fs::create_dir_all(&*util::paths::LANGUAGES_DIR).expect("could not create languages path");
339 std::fs::create_dir_all(&*util::paths::DB_DIR).expect("could not create database path");
340 std::fs::create_dir_all(&*util::paths::LOGS_DIR).expect("could not create logs path");
341}
342
343fn init_logger() {
344 if stdout_is_a_pty() {
345 env_logger::init();
346 } else {
347 let level = LevelFilter::Info;
348
349 // Prevent log file from becoming too large.
350 const KIB: u64 = 1024;
351 const MIB: u64 = 1024 * KIB;
352 const MAX_LOG_BYTES: u64 = MIB;
353 if std::fs::metadata(&*paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
354 {
355 let _ = std::fs::rename(&*paths::LOG, &*paths::OLD_LOG);
356 }
357
358 let log_file = OpenOptions::new()
359 .create(true)
360 .append(true)
361 .open(&*paths::LOG)
362 .expect("could not open logfile");
363
364 let config = ConfigBuilder::new()
365 .set_time_format_str("%Y-%m-%dT%T") //All timestamps are UTC
366 .build();
367
368 simplelog::WriteLogger::init(level, config, log_file).expect("could not initialize logger");
369 }
370}
371
372#[derive(Serialize, Deserialize)]
373struct LocationData {
374 file: String,
375 line: u32,
376}
377
378#[derive(Serialize, Deserialize)]
379struct Panic {
380 thread: String,
381 payload: String,
382 #[serde(skip_serializing_if = "Option::is_none")]
383 location_data: Option<LocationData>,
384 backtrace: Vec<String>,
385 app_version: String,
386 release_channel: String,
387 os_name: String,
388 os_version: Option<String>,
389 architecture: String,
390 panicked_on: u128,
391 #[serde(skip_serializing_if = "Option::is_none")]
392 installation_id: Option<String>,
393 session_id: String,
394}
395
396#[derive(Serialize)]
397struct PanicRequest {
398 panic: Panic,
399 token: String,
400}
401
402static PANIC_COUNT: AtomicU32 = AtomicU32::new(0);
403
404fn init_panic_hook(app: &App, installation_id: Option<String>, session_id: String) {
405 let is_pty = stdout_is_a_pty();
406 let app_metadata = app.metadata();
407
408 panic::set_hook(Box::new(move |info| {
409 let prior_panic_count = PANIC_COUNT.fetch_add(1, Ordering::SeqCst);
410 if prior_panic_count > 0 {
411 // Give the panic-ing thread time to write the panic file
412 loop {
413 std::thread::yield_now();
414 }
415 }
416
417 let thread = thread::current();
418 let thread_name = thread.name().unwrap_or("<unnamed>");
419
420 let payload = info
421 .payload()
422 .downcast_ref::<&str>()
423 .map(|s| s.to_string())
424 .or_else(|| info.payload().downcast_ref::<String>().map(|s| s.clone()))
425 .unwrap_or_else(|| "Box<Any>".to_string());
426
427 if *util::channel::RELEASE_CHANNEL == ReleaseChannel::Dev {
428 let location = info.location().unwrap();
429 let backtrace = Backtrace::new();
430 eprintln!(
431 "Thread {:?} panicked with {:?} at {}:{}:{}\n{:?}",
432 thread_name,
433 payload,
434 location.file(),
435 location.line(),
436 location.column(),
437 backtrace,
438 );
439 std::process::exit(-1);
440 }
441
442 let app_version = client2::ZED_APP_VERSION
443 .or(app_metadata.app_version)
444 .map_or("dev".to_string(), |v| v.to_string());
445
446 let backtrace = Backtrace::new();
447 let mut backtrace = backtrace
448 .frames()
449 .iter()
450 .filter_map(|frame| Some(format!("{:#}", frame.symbols().first()?.name()?)))
451 .collect::<Vec<_>>();
452
453 // Strip out leading stack frames for rust panic-handling.
454 if let Some(ix) = backtrace
455 .iter()
456 .position(|name| name == "rust_begin_unwind")
457 {
458 backtrace.drain(0..=ix);
459 }
460
461 let panic_data = Panic {
462 thread: thread_name.into(),
463 payload: payload.into(),
464 location_data: info.location().map(|location| LocationData {
465 file: location.file().into(),
466 line: location.line(),
467 }),
468 app_version: app_version.clone(),
469 release_channel: RELEASE_CHANNEL.display_name().into(),
470 os_name: app_metadata.os_name.into(),
471 os_version: app_metadata
472 .os_version
473 .as_ref()
474 .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::<client2::TelemetrySettings>(cx);
511
512 cx.executor()
513 .spawn(async move {
514 let panic_report_url = format!("{}/api/panic", &*client2::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: client2::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// }