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