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