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