-
-
Notifications
You must be signed in to change notification settings - Fork 10k
Expand file tree
/
Copy pathmain.rs
More file actions
2022 lines (1824 loc) · 73.8 KB
/
Copy pathmain.rs
File metadata and controls
2022 lines (1824 loc) · 73.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Disable command line from opening on release mode
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
mod reliability;
mod zed;
// Ensure the binary name stays in sync with APP_NAME so that the paths used
// at runtime (data dir, config dir, etc.) match what the binary is called.
const _: () = assert!(
paths::APP_NAME_LOWERCASE
.as_bytes()
.eq_ignore_ascii_case(env!("CARGO_BIN_NAME").as_bytes()),
"paths::APP_NAME_LOWERCASE must match the binary name. \
Forks: update APP_NAME in crates/paths/src/paths.rs when renaming the binary.",
);
use agent_ui::AgentPanel;
use anyhow::{Context as _, Result};
use clap::Parser;
use cli::FORCE_CLI_MODE_ENV_VAR_NAME;
use client::{Client, ProxySettings, RefreshLlmTokenListener, UserStore, parse_zed_link};
use collab_ui::channel_view::ChannelView;
use collections::HashMap;
use crashes::InitCrashHandler;
use db::kvp::{GlobalKeyValueStore, KeyValueStore};
use editor::Editor;
use extension::ExtensionHostProxy;
use fs::{Fs, RealFs};
use futures::{FutureExt, StreamExt, channel::oneshot, future};
use git::GitHostingProviderRegistry;
use git_ui::clone::clone_and_open;
use gpui::{
App, AppContext, Application, AsyncApp, QuitMode, Task, TaskExt, UpdateGlobal as _, block_on,
};
use gpui_platform;
use gpui_tokio::Tokio;
use language::LanguageRegistry;
use onboarding::{FIRST_OPEN, show_onboarding_view};
use project_panel::ProjectPanel;
use prompt_store::PromptBuilder;
use remote::RemoteConnectionOptions;
use reqwest_client::ReqwestClient;
use assets::Assets;
use node_runtime::{NodeBinaryOptions, NodeRuntime};
use parking_lot::Mutex;
use project::{project_settings::ProjectSettings, trusted_worktrees};
use recent_projects::{RemoteSettings, open_remote_project};
use release_channel::{AppCommitSha, AppVersion, ReleaseChannel};
use session::{AppSession, Session};
use settings::{BaseKeymap, Settings, SettingsStore, watch_config_file};
use smol::future::poll_once;
use std::{
cell::RefCell,
env,
io::{self, IsTerminal},
path::{Path, PathBuf},
process,
rc::Rc,
sync::{Arc, LazyLock, OnceLock},
time::Instant,
};
use theme::{ActiveTheme, GlobalTheme, ThemeRegistry};
use theme_settings::load_user_theme;
use util::{ResultExt, maybe};
use uuid::Uuid;
use workspace::{
AppState, MultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace, Toast,
WorkspaceSettings, WorkspaceStore,
notifications::{NotificationId, NotifyResultExt},
restore_multiworkspace,
};
use zed::{
OpenListener, OpenRequest, RawOpenRequest, app_menus, build_window_options,
derive_paths_with_position, edit_prediction_registry, handle_cli_connection,
handle_keymap_file_changes, initialize_workspace, open_paths_with_positions,
};
use crate::zed::{CrashHandler, OpenRequestKind, eager_load_active_theme_and_icon_theme};
#[cfg(feature = "mimalloc")]
#[global_allocator]
static GLOBAL: mimalloc::MiMalloc = mimalloc::MiMalloc;
fn build_application() -> Application {
let platform = gpui_platform::current_platform(false);
if std::env::var("ZED_EXPERIMENTAL_A11Y").as_deref() == Ok("1") {
Application::with_platform(platform)
} else {
Application::new_inaccessible(platform)
}
}
fn files_not_created_on_launch(errors: HashMap<io::ErrorKind, Vec<&Path>>) {
let message = "Zed failed to launch";
let error_details = errors
.into_iter()
.flat_map(|(kind, paths)| {
#[allow(unused_mut)] // for non-unix platforms
let mut error_kind_details = match paths.len() {
0 => return None,
1 => format!(
"{kind} when creating directory {:?}",
paths.first().expect("match arm checks for a single entry")
),
_many => format!("{kind} when creating directories {paths:?}"),
};
#[cfg(unix)]
{
if kind == io::ErrorKind::PermissionDenied {
error_kind_details.push_str("\n\nConsider using chown and chmod tools for altering the directories permissions if your user has corresponding rights.\
\nFor example, `sudo chown $(whoami):staff ~/.config` and `chmod +uwrx ~/.config`");
}
}
Some(error_kind_details)
})
.collect::<Vec<_>>().join("\n\n");
eprintln!("{message}: {error_details}");
build_application()
.with_quit_mode(QuitMode::Explicit)
.run(move |cx| {
if let Ok(window) = cx.open_window(gpui::WindowOptions::default(), |_, cx| {
cx.new(|_| gpui::Empty)
}) {
window
.update(cx, |_, window, cx| {
let response = window.prompt(
gpui::PromptLevel::Critical,
message,
Some(&error_details),
&["Exit"],
cx,
);
cx.spawn_in(window, async move |_, cx| {
response.await?;
cx.update(|_, cx| cx.quit())
})
.detach_and_log_err(cx);
})
.log_err();
} else {
fail_to_open_window(anyhow::anyhow!("{message}: {error_details}"), cx)
}
})
}
fn fail_to_open_window_async(e: anyhow::Error, cx: &mut AsyncApp) {
cx.update(|cx| fail_to_open_window(e, cx));
}
fn fail_to_open_window(e: anyhow::Error, _cx: &mut App) {
eprintln!(
"Zed failed to open a window: {e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
);
#[cfg(not(any(target_os = "linux", target_os = "freebsd")))]
{
process::exit(1);
}
// Maybe unify this with gpui::platform::linux::platform::ResultExt::notify_err(..)?
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
use ashpd::desktop::notification::{Notification, NotificationProxy, Priority};
_cx.spawn(async move |_cx| {
let Ok(proxy) = NotificationProxy::new().await else {
process::exit(1);
};
let notification_id = "dev.zed.Oops";
proxy
.add_notification(
notification_id,
Notification::new("Zed failed to launch")
.body(Some(
format!(
"{e:?}. See https://zed.dev/docs/linux for troubleshooting steps."
)
.as_str(),
))
.priority(Priority::High)
.icon(ashpd::desktop::Icon::with_names(&[
"dialog-question-symbolic",
])),
)
.await
.ok();
process::exit(1);
})
.detach();
}
}
static STARTUP_TIME: OnceLock<Instant> = OnceLock::new();
fn main() {
STARTUP_TIME.get_or_init(|| Instant::now());
// If this process was re-executed as a Linux sandbox helper, run that mode
// without returning. Must run before argument parsing: the wrapped command's
// args are appended verbatim and would otherwise be misinterpreted as Zed's
// own arguments.
sandbox::run_sandbox_launcher_if_invoked();
#[cfg(unix)]
util::prevent_root_execution();
let args = Args::parse();
// `zed --askpass` Makes zed operate in nc/netcat mode for use with askpass
#[cfg(not(target_os = "windows"))]
if let Some(socket) = &args.askpass {
askpass::main(socket);
return;
}
// `zed --crash-handler` Makes zed operate in minidump crash handler mode
if let Some(socket) = &args.crash_handler {
crashes::crash_server(socket.as_path(), paths::logs_dir().clone());
return;
}
#[cfg(target_os = "windows")]
if args.record_etw_trace {
let zed_pid = args
.etw_zed_pid
.and_then(|pid| if pid >= 0 { Some(pid as u32) } else { None });
let Some(output_path) = args.etw_output else {
eprintln!("--etw-output is required for --record-etw-trace");
process::exit(1);
};
let Some(etw_socket) = args.etw_socket else {
eprintln!("--etw-socket is required for --record-etw-trace");
process::exit(1);
};
if let Err(error) =
etw_tracing::record_etw_trace(zed_pid, &output_path, etw_socket.as_str())
{
eprintln!("ETW trace recording failed: {error:#}");
process::exit(1);
}
return;
}
#[cfg(all(not(debug_assertions), target_os = "windows"))]
unsafe {
use windows::Win32::System::Console::{ATTACH_PARENT_PROCESS, AttachConsole};
if args.foreground {
let _ = AttachConsole(ATTACH_PARENT_PROCESS);
}
}
// `zed --printenv` Outputs environment variables as JSON to stdout
if args.printenv {
util::shell_env::print_env();
return;
}
if args.dump_all_actions {
dump_all_gpui_actions();
return;
}
// Set custom data directory.
if let Some(dir) = &args.user_data_dir {
paths::set_custom_data_dir(dir);
}
#[cfg(target_os = "windows")]
match util::get_zed_cli_path() {
Ok(path) => askpass::set_askpass_program(path),
Err(err) => {
eprintln!("Error: {}", err);
if std::option_env!("ZED_BUNDLE").is_some() {
process::exit(1);
}
}
}
let file_errors = init_paths();
if !file_errors.is_empty() {
files_not_created_on_launch(file_errors);
return;
}
zlog::init();
if stdout_is_a_pty() {
zlog::init_output_stdout();
} else {
let result = zlog::init_output_file(paths::log_file(), Some(paths::old_log_file()));
if let Err(err) = result {
eprintln!("Could not open log file: {}... Defaulting to stdout", err);
zlog::init_output_stdout();
};
}
ztracing::init();
let version = option_env!("ZED_BUILD_ID");
let app_commit_sha =
option_env!("ZED_COMMIT_SHA").map(|commit_sha| AppCommitSha::new(commit_sha.to_string()));
let app_version = AppVersion::load(env!("CARGO_PKG_VERSION"), version, app_commit_sha.clone());
if args.system_specs {
let system_specs = system_specs::SystemSpecs::new_stateless(
app_version,
app_commit_sha,
*release_channel::RELEASE_CHANNEL,
client::telemetry::os_name(),
client::telemetry::os_version(),
);
println!("Zed System Specs (from CLI):\n{}", system_specs);
return;
}
rayon::ThreadPoolBuilder::new()
.num_threads(std::thread::available_parallelism().map_or(1, |n| n.get().div_ceil(2)))
.stack_size(10 * 1024 * 1024)
.thread_name(|ix| format!("RayonWorker{}", ix))
.build_global()
.unwrap();
log::info!(
"========== starting zed version {}, sha {} ==========",
app_version,
app_commit_sha
.as_ref()
.map(|sha| sha.short())
.as_deref()
.unwrap_or("unknown"),
);
#[cfg(windows)]
check_for_conpty_dll();
let app = build_application().with_assets(Assets);
let app_db = db::AppDatabase::new();
let system_id = app.background_executor().spawn(system_id());
let installation_id = app
.background_executor()
.spawn(installation_id(KeyValueStore::from_app_db(&app_db)));
let session_id = Uuid::new_v4().to_string();
let session = app.background_executor().spawn(Session::new(
session_id.clone(),
KeyValueStore::from_app_db(&app_db),
));
let background_executor = app.background_executor();
let (open_listener, mut open_rx) = OpenListener::new();
let failed_single_instance_check = if *zed_env_vars::ZED_STATELESS
|| *release_channel::RELEASE_CHANNEL == ReleaseChannel::Dev
{
false
} else {
#[cfg(any(target_os = "linux", target_os = "freebsd"))]
{
crate::zed::listen_for_cli_connections(open_listener.clone()).is_err()
}
#[cfg(target_os = "windows")]
{
!crate::zed::windows_only_instance::handle_single_instance(open_listener.clone(), &args)
}
#[cfg(target_os = "macos")]
{
use zed::mac_only_instance::*;
ensure_only_instance() != IsOnlyInstance::Yes
}
};
if failed_single_instance_check {
println!("zed is already running");
return;
}
let should_install_crash_handler =
client::telemetry::should_install_crash_handler(*release_channel::RELEASE_CHANNEL);
let crash_handler = if should_install_crash_handler {
Some(
app.background_executor().spawn(crashes::init(
InitCrashHandler {
session_id,
// strip the build and channel information from the version string, we send them separately
zed_version: semver::Version::new(
app_version.major,
app_version.minor,
app_version.patch,
)
.to_string(),
binary: "zed".to_string(),
release_channel: release_channel::RELEASE_CHANNEL_NAME.clone(),
commit_sha: app_commit_sha
.as_ref()
.map(|sha| sha.full())
.unwrap_or_else(|| "no sha".to_owned()),
},
{
let background_executor1 = app.background_executor();
move |task| {
background_executor1.spawn(task).detach();
}
},
|pid| paths::temp_dir().join(format!("zed-crash-handler-{pid}")),
move |duration| background_executor.timer(duration),
)),
)
} else {
crashes::force_backtrace();
None
};
let git_hosting_provider_registry = Arc::new(GitHostingProviderRegistry::new());
let git_binary_path =
if cfg!(target_os = "macos") && option_env!("ZED_BUNDLE").as_deref() == Some("true") {
app.path_for_auxiliary_executable("git")
.context("could not find git binary path")
.log_err()
} else {
None
};
if let Some(git_binary_path) = &git_binary_path {
log::info!("Using git binary path: {:?}", git_binary_path);
}
let fs = Arc::new(RealFs::new(git_binary_path, app.background_executor()));
let (user_keymap_file_rx, user_keymap_watcher) = watch_config_file(
&app.background_executor(),
fs.clone(),
paths::keymap_file().clone(),
);
let (shell_env_loaded_tx, shell_env_loaded_rx) = oneshot::channel();
if !stdout_is_a_pty() {
app.background_executor()
.spawn(async {
#[cfg(unix)]
util::load_login_shell_environment().await.log_err();
shell_env_loaded_tx.send(()).ok();
})
.detach();
} else {
drop(shell_env_loaded_tx)
}
app.on_open_urls({
let open_listener = open_listener.clone();
move |urls| {
open_listener.open(RawOpenRequest {
urls,
diff_paths: Vec::new(),
..Default::default()
})
}
});
app.on_reopen(move |cx| {
if let Some(app_state) = AppState::try_global(cx) {
cx.spawn({
async move |cx| {
if let Err(e) = restore_or_create_workspace(app_state, cx).await {
fail_to_open_window_async(e, cx)
}
}
})
.detach();
}
});
app.run(move |cx| {
cx.set_global(app_db);
let db_trusted_paths = match workspace::WorkspaceDb::global(cx).fetch_trusted_worktrees() {
Ok(trusted_paths) => trusted_paths,
Err(e) => {
log::error!("Failed to do initial trusted worktrees fetch: {e:#}");
HashMap::default()
}
};
trusted_worktrees::init(db_trusted_paths, cx);
menu::init();
zed_actions::init();
release_channel::init(app_version, cx);
gpui_tokio::init(cx);
if let Some(app_commit_sha) = app_commit_sha {
AppCommitSha::set_global(app_commit_sha, cx);
}
settings::init(cx);
zlog_settings::init(cx);
zed::watch_settings_files(fs.clone(), cx);
handle_keymap_file_changes(user_keymap_file_rx, user_keymap_watcher, cx);
let user_agent = format!(
"Zed/{} ({}; {})",
AppVersion::global(cx),
std::env::consts::OS,
std::env::consts::ARCH
);
let proxy_url = ProxySettings::get_global(cx).proxy_url();
let http = {
let _guard = Tokio::handle(cx).enter();
ReqwestClient::proxy_and_user_agent(proxy_url, &user_agent)
.expect("could not start HTTP client")
};
cx.set_http_client(Arc::new(http));
<dyn Fs>::set_global(fs.clone(), cx);
GitHostingProviderRegistry::set_global(git_hosting_provider_registry, cx);
git_hosting_providers::init(cx);
OpenListener::set_global(cx, open_listener.clone());
extension::init(cx);
let extension_host_proxy = ExtensionHostProxy::global(cx);
let client = Client::production(cx);
cx.set_http_client(client.http_client());
let mut languages = LanguageRegistry::new(cx.background_executor().clone());
languages.set_language_server_download_dir(paths::languages_dir().clone());
let languages = Arc::new(languages);
let (mut tx, rx) = watch::channel(None);
cx.observe_global::<SettingsStore>(move |cx| {
let settings = &ProjectSettings::get_global(cx).node;
let options = NodeBinaryOptions {
allow_path_lookup: !settings.ignore_system_version,
// TODO: Expose this setting
allow_binary_download: true,
use_paths: settings.path.as_ref().map(|node_path| {
let node_path = PathBuf::from(shellexpand::tilde(node_path).as_ref());
let npm_path = settings
.npm_path
.as_ref()
.map(|path| PathBuf::from(shellexpand::tilde(&path).as_ref()));
(
node_path.clone(),
npm_path.unwrap_or_else(|| {
let base_path = PathBuf::new();
node_path.parent().unwrap_or(&base_path).join("npm")
}),
)
}),
};
tx.send(Some(options)).log_err();
})
.detach();
ui::on_new_scrollbars::<SettingsStore>(cx);
let node_runtime = NodeRuntime::new(client.http_client(), Some(shell_env_loaded_rx), rx);
debug_adapter_extension::init(extension_host_proxy.clone(), cx);
languages::init(languages.clone(), fs.clone(), node_runtime.clone(), cx);
let user_store = cx.new(|cx| UserStore::new(client.clone(), cx));
let workspace_store = cx.new(|cx| WorkspaceStore::new(client.clone(), cx));
language_extension::init(
language_extension::LspAccess::ViaWorkspaces({
let workspace_store = workspace_store.clone();
Arc::new(move |cx: &mut App| {
workspace_store.update(cx, |workspace_store, cx| {
Ok(workspace_store
.workspaces()
.filter_map(|weak| weak.upgrade())
.map(|workspace: gpui::Entity<workspace::Workspace>| {
workspace.read(cx).project().read(cx).lsp_store()
})
.collect())
})
})
}),
extension_host_proxy.clone(),
languages.clone(),
);
Client::set_global(client.clone(), cx);
zed::init(cx);
#[cfg(target_os = "macos")]
zed::move_to_applications::init(cx);
project::Project::init(&client, cx);
debugger_ui::init(cx);
debugger_tools::init(cx);
client::init(&client, cx);
feature_flags::FeatureFlagStore::init(cx);
let system_id = cx.foreground_executor().block_on(system_id).ok();
let installation_id = cx.foreground_executor().block_on(installation_id).ok();
let session = cx.foreground_executor().block_on(session);
let telemetry = client.telemetry();
telemetry.start(
system_id.as_ref().map(|id| id.to_string()),
installation_id.as_ref().map(|id| id.to_string()),
session.id().to_owned(),
cx,
);
cx.subscribe(&user_store, {
let telemetry = telemetry.clone();
move |_, evt: &client::user::Event, cx| match evt {
client::user::Event::PrivateUserInfoUpdated => {
if let Some(crash_client) = cx.try_global::<CrashHandler>() {
crashes::set_user_info(
&crash_client.0,
crashes::UserInfo {
metrics_id: telemetry.metrics_id().map(|s| s.to_string()),
is_staff: telemetry.is_staff(),
},
);
}
}
_ => {}
}
})
.detach();
let is_new_install = matches!(&installation_id, Some(IdType::New(_)));
// We should rename these in the future to `first app open`, `first app open for release channel`, and `app open`
if let (Some(system_id), Some(installation_id)) = (&system_id, &installation_id) {
match (&system_id, &installation_id) {
(IdType::New(_), IdType::New(_)) => {
telemetry::event!("App First Opened");
telemetry::event!("App First Opened For Release Channel");
}
(IdType::Existing(_), IdType::New(_)) => {
telemetry::event!("App First Opened For Release Channel");
}
(_, IdType::Existing(_)) => {
telemetry::event!("App Opened");
}
}
}
let app_session = cx.new(|cx| AppSession::new(session, cx));
let app_state = Arc::new(AppState {
languages,
client: client.clone(),
user_store,
fs: fs.clone(),
build_window_options,
workspace_store,
node_runtime,
session: app_session,
});
AppState::set_global(app_state.clone(), cx);
auto_update::init(client.clone(), cx);
dap_adapters::init(cx);
auto_update_ui::init(cx);
reliability::init(client.clone(), app_state.workspace_store.clone(), cx);
extension_host::init(
extension_host_proxy.clone(),
app_state.fs.clone(),
app_state.client.clone(),
app_state.node_runtime.clone(),
cx,
);
theme_settings::init(theme::LoadThemes::All(Box::new(Assets)), cx);
eager_load_active_theme_and_icon_theme(fs.clone(), cx);
theme_extension::init(
extension_host_proxy,
ThemeRegistry::global(cx),
cx.background_executor().clone(),
);
command_palette::init(cx);
let copilot_chat_configuration = copilot_chat::CopilotChatConfiguration {
enterprise_uri: language::language_settings::all_language_settings(None, cx)
.edit_predictions
.copilot
.enterprise_uri
.clone(),
};
let credentials_provider = zed_credentials_provider::global(cx);
copilot_chat::init(
app_state.client.http_client(),
credentials_provider,
copilot_chat_configuration,
cx,
);
copilot_ui::init(&app_state, cx);
language_model::init(cx);
RefreshLlmTokenListener::register(
app_state.client.clone(),
app_state.user_store.clone(),
cx,
);
language_models::init(app_state.user_store.clone(), app_state.client.clone(), cx);
acp_tools::init(cx);
zed::telemetry_log::init(cx);
zed::remote_debug::init(cx);
edit_prediction_ui::init(cx);
web_search::init(cx);
web_search_providers::init(app_state.client.clone(), app_state.user_store.clone(), cx);
snippet_provider::init(cx);
edit_prediction_registry::init(app_state.client.clone(), app_state.user_store.clone(), cx);
let prompt_builder = PromptBuilder::load(app_state.fs.clone(), stdout_is_a_pty(), cx);
project::AgentRegistryStore::init_global(
cx,
app_state.fs.clone(),
app_state.client.http_client(),
);
agent_ui::init(
app_state.fs.clone(),
prompt_builder,
app_state.languages.clone(),
is_new_install,
false,
cx,
);
zed::watch_user_agents_md(app_state.fs.clone(), cx);
repl::init(app_state.fs.clone(), cx);
recent_projects::init(cx);
dev_container::init(cx);
load_embedded_fonts(cx);
editor::init(cx);
image_viewer::init(cx);
repl::notebook::init(cx);
diagnostics::init(cx);
audio::init(cx);
workspace::init(app_state.clone(), cx);
ui_prompt::init(cx);
go_to_line::init(cx);
file_finder::init(cx);
tab_switcher::init(cx);
outline::init(cx);
project_symbols::init(cx);
project_panel::init(cx);
outline_panel::init(cx);
tasks_ui::init(cx);
snippets_ui::init(cx);
channel::init(&app_state.client.clone(), app_state.user_store.clone(), cx);
search::init(cx);
lsp_locations::init(cx);
cx.set_global(workspace::PaneSearchBarCallbacks {
setup_search_bar: |languages, toolbar, window, cx| {
let search_bar = cx.new(|cx| search::BufferSearchBar::new(languages, window, cx));
toolbar.update(cx, |toolbar, cx| {
toolbar.add_item(search_bar, window, cx);
});
},
wrap_div_with_search_actions: search::buffer_search::register_pane_search_actions,
});
vim::init(cx);
terminal_view::init(cx);
journal::init(app_state.clone(), cx);
encoding_selector::init(cx);
language_selector::init(cx);
line_ending_selector::init(cx);
toolchain_selector::init(cx);
theme_selector::init(cx);
settings_profile_selector::init(cx);
language_tools::init(cx);
call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
notifications::init(app_state.client.clone(), app_state.user_store.clone(), cx);
collab_ui::init(&app_state, cx);
git_ui::init(cx);
feedback::init(cx);
markdown_preview::init(cx);
csv_preview::init(cx);
svg_preview::init(cx);
onboarding::init(cx);
settings_ui::init(cx);
keymap_editor::init(cx);
extensions_ui::init(cx);
edit_prediction::init(cx);
inspector_ui::init(app_state.clone(), cx);
json_schema_store::init(cx);
miniprofiler_ui::init(*STARTUP_TIME.get().unwrap(), cx);
which_key::init(cx);
#[cfg(target_os = "windows")]
etw_tracing::init(cx);
cx.observe_global::<SettingsStore>({
let http = app_state.client.http_client();
let client = app_state.client.clone();
move |cx| {
for &mut window in cx.windows().iter_mut() {
let background_appearance = cx.theme().window_background_appearance();
window
.update(cx, |_, window, _| {
window.set_background_appearance(background_appearance)
})
.ok();
}
cx.set_text_rendering_mode(
match WorkspaceSettings::get_global(cx).text_rendering_mode {
settings::TextRenderingMode::PlatformDefault => {
gpui::TextRenderingMode::PlatformDefault
}
settings::TextRenderingMode::Subpixel => gpui::TextRenderingMode::Subpixel,
settings::TextRenderingMode::Grayscale => {
gpui::TextRenderingMode::Grayscale
}
},
);
let new_host = &client::ClientSettings::get_global(cx).server_url;
if &http.base_url() != new_host {
http.set_base_url(new_host);
if client.status().borrow().is_connected() {
client.reconnect(&cx.to_async());
}
}
}
})
.detach();
app_state.languages.set_theme(cx.theme().clone());
cx.observe_global::<GlobalTheme>({
let languages = app_state.languages.clone();
move |cx| {
languages.set_theme(cx.theme().clone());
}
})
.detach();
telemetry::event!(
"Settings Changed",
setting = "theme",
value = cx.theme().name.to_string()
);
telemetry::event!(
"Settings Changed",
setting = "keymap",
value = BaseKeymap::get_global(cx).to_string()
);
telemetry.flush_events().detach();
let fs = app_state.fs.clone();
load_user_themes_in_background(fs.clone(), cx);
watch_themes(fs.clone(), cx);
#[cfg(debug_assertions)]
watch_languages(fs.clone(), app_state.languages.clone(), cx);
let menus = app_menus(cx);
cx.set_menus(menus);
if let Some(mut crash_handler) = crash_handler {
let crash_handler2 = block_on(poll_once(&mut crash_handler));
match crash_handler2 {
Some(crash_handler) => {
cx.set_global(CrashHandler(crash_handler));
}
None => {
cx.spawn(async move |cx| {
let client1 = crash_handler.await;
cx.update(|cx| {
cx.set_global(CrashHandler(client1));
});
})
.detach();
}
}
}
initialize_workspace(app_state.clone(), cx);
cx.activate(true);
cx.spawn({
let client = app_state.client.clone();
async move |cx| authenticate(client, cx).await
})
.detach_and_log_err(cx);
let urls: Vec<_> = args
.paths_or_urls
.iter()
.map(|arg| parse_url_arg(arg, cx))
.collect();
// Check if any diff paths are directories to determine diff_all mode
let diff_all_mode = args
.diff
.chunks(2)
.any(|pair| Path::new(&pair[0]).is_dir() || Path::new(&pair[1]).is_dir());
let diff_paths: Vec<[String; 2]> = args
.diff
.chunks(2)
.map(|chunk| [chunk[0].clone(), chunk[1].clone()])
.collect();
#[cfg(target_os = "windows")]
let wsl = args.wsl;
#[cfg(not(target_os = "windows"))]
let wsl = None;
if !urls.is_empty() || !diff_paths.is_empty() {
open_listener.open(RawOpenRequest {
urls,
diff_paths,
wsl,
diff_all: diff_all_mode,
dev_container: args.dev_container,
..Default::default()
})
}
let (current_session_id, last_session_id) = {
let session = app_state.session.read(cx);
(
session.id().to_owned(),
session.last_session_id().map(|id| id.to_owned()),
)
};
let restore_task = match open_rx
.try_recv()
.ok()
.and_then(|request| OpenRequest::parse(request, cx).log_err())
{
Some(request) if request.is_focus_app_only() => cx.spawn({
let app_state = app_state.clone();
async move |cx| {
if let Err(e) = restore_or_create_workspace(app_state, cx).await {
fail_to_open_window_async(e, cx)
}
}
}),
Some(request) => {
handle_open_request(request, app_state.clone(), cx);
Task::ready(())
}
None => cx.spawn({
let app_state = app_state.clone();
async move |cx| {
if let Err(e) = restore_or_create_workspace(app_state, cx).await {
fail_to_open_window_async(e, cx)
}
}
}),
};
let (first_window_tx, first_window_rx) = oneshot::channel::<()>();
let first_window_tx = Rc::new(RefCell::new(Some(first_window_tx)));
let _first_window_subscription = cx.observe_new::<MultiWorkspace>(move |_, _, _| {
if let Some(tx) = first_window_tx.borrow_mut().take() {
tx.send(()).ok();
}
});
let restore_finished = cx.background_spawn(restore_task).shared();
cx.spawn({
let db = workspace::WorkspaceDb::global(cx);
let fs = app_state.fs.clone();
let restore_finished = restore_finished.clone();
async move |_cx| {
restore_finished.await;
db.garbage_collect_workspaces(
fs.as_ref(),
¤t_session_id,
last_session_id.as_deref(),
)
.await
}
})
.detach_and_log_err(cx);
let app_state = app_state.clone();
component_preview::init(app_state.clone(), cx);
cx.spawn(async move |cx| {
let _first_window_subscription = _first_window_subscription;
let first_window_placed = first_window_rx.shared();
while let Some(urls) = open_rx.next().await {
// On a macOS cold launch, `zed <path>` arrives here after startup already
// began restoring the session, so wait for a restored window to exist before
// matching. Otherwise this open sees no windows and spawns a redundant one (#61346).
futures::select_biased! {
_ = restore_finished.clone() => {}
_ = first_window_placed.clone() => {}
}
cx.update(|cx| {
if let Some(request) = OpenRequest::parse(urls, cx).log_err() {
handle_open_request(request, app_state.clone(), cx);
}
});
}
})
.detach();
});
}