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