1pub use crate::welcome::ShowWelcome;
2use crate::{multibuffer_hint::MultibufferHint, welcome::WelcomePage};
3use client::{Client, UserStore, zed_urls};
4use db::kvp::KEY_VALUE_STORE;
5use fs::Fs;
6use gpui::{
7 Action, AnyElement, App, AppContext, AsyncWindowContext, Context, Entity, EventEmitter,
8 FocusHandle, Focusable, Global, IntoElement, KeyContext, Render, ScrollHandle, SharedString,
9 Subscription, Task, WeakEntity, Window, actions,
10};
11use notifications::status_toast::{StatusToast, ToastIcon};
12use schemars::JsonSchema;
13use serde::Deserialize;
14use settings::{SettingsStore, VsCodeSettingsSource};
15use std::sync::Arc;
16use ui::{
17 KeyBinding, ParentElement as _, StatefulInteractiveElement, Vector, VectorName,
18 WithScrollbar as _, prelude::*, rems_from_px,
19};
20pub use ui_input::font_picker;
21use workspace::{
22 AppState, Workspace, WorkspaceId,
23 dock::DockPosition,
24 item::{Item, ItemEvent},
25 notifications::NotifyResultExt as _,
26 open_new, register_serializable_item, with_active_or_new_workspace,
27};
28
29mod base_keymap_picker;
30mod basics_page;
31pub mod multibuffer_hint;
32mod theme_preview;
33mod welcome;
34
35/// Imports settings from Visual Studio Code.
36#[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
37#[action(namespace = zed)]
38#[serde(deny_unknown_fields)]
39pub struct ImportVsCodeSettings {
40 #[serde(default)]
41 pub skip_prompt: bool,
42}
43
44/// Imports settings from Cursor editor.
45#[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
46#[action(namespace = zed)]
47#[serde(deny_unknown_fields)]
48pub struct ImportCursorSettings {
49 #[serde(default)]
50 pub skip_prompt: bool,
51}
52
53pub const FIRST_OPEN: &str = "first_open";
54pub const DOCS_URL: &str = "https://zed.dev/docs/";
55
56actions!(
57 zed,
58 [
59 /// Opens the onboarding view.
60 OpenOnboarding
61 ]
62);
63
64actions!(
65 onboarding,
66 [
67 /// Finish the onboarding process.
68 Finish,
69 /// Sign in while in the onboarding flow.
70 SignIn,
71 /// Open the user account in zed.dev while in the onboarding flow.
72 OpenAccount,
73 /// Resets the welcome screen hints to their initial state.
74 ResetHints
75 ]
76);
77
78pub fn init(cx: &mut App) {
79 cx.observe_new(|workspace: &mut Workspace, _, _cx| {
80 workspace
81 .register_action(|_workspace, _: &ResetHints, _, cx| MultibufferHint::set_count(0, cx));
82 })
83 .detach();
84
85 cx.on_action(|_: &OpenOnboarding, cx| {
86 with_active_or_new_workspace(cx, |workspace, window, cx| {
87 workspace
88 .with_local_workspace(window, cx, |workspace, window, cx| {
89 let existing = workspace
90 .active_pane()
91 .read(cx)
92 .items()
93 .find_map(|item| item.downcast::<Onboarding>());
94
95 if let Some(existing) = existing {
96 workspace.activate_item(&existing, true, true, window, cx);
97 } else {
98 let settings_page = Onboarding::new(workspace, cx);
99 workspace.add_item_to_active_pane(
100 Box::new(settings_page),
101 None,
102 true,
103 window,
104 cx,
105 )
106 }
107 })
108 .detach();
109 });
110 });
111
112 cx.on_action(|_: &ShowWelcome, cx| {
113 with_active_or_new_workspace(cx, |workspace, window, cx| {
114 workspace
115 .with_local_workspace(window, cx, |workspace, window, cx| {
116 let existing = workspace
117 .active_pane()
118 .read(cx)
119 .items()
120 .find_map(|item| item.downcast::<WelcomePage>());
121
122 if let Some(existing) = existing {
123 workspace.activate_item(&existing, true, true, window, cx);
124 } else {
125 let settings_page = WelcomePage::new(window, cx);
126 workspace.add_item_to_active_pane(
127 Box::new(settings_page),
128 None,
129 true,
130 window,
131 cx,
132 )
133 }
134 })
135 .detach();
136 });
137 });
138
139 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
140 workspace.register_action(|_workspace, action: &ImportVsCodeSettings, window, cx| {
141 let fs = <dyn Fs>::global(cx);
142 let action = *action;
143
144 let workspace = cx.weak_entity();
145
146 window
147 .spawn(cx, async move |cx: &mut AsyncWindowContext| {
148 handle_import_vscode_settings(
149 workspace,
150 VsCodeSettingsSource::VsCode,
151 action.skip_prompt,
152 fs,
153 cx,
154 )
155 .await
156 })
157 .detach();
158 });
159
160 workspace.register_action(|_workspace, action: &ImportCursorSettings, window, cx| {
161 let fs = <dyn Fs>::global(cx);
162 let action = *action;
163
164 let workspace = cx.weak_entity();
165
166 window
167 .spawn(cx, async move |cx: &mut AsyncWindowContext| {
168 handle_import_vscode_settings(
169 workspace,
170 VsCodeSettingsSource::Cursor,
171 action.skip_prompt,
172 fs,
173 cx,
174 )
175 .await
176 })
177 .detach();
178 });
179 })
180 .detach();
181
182 base_keymap_picker::init(cx);
183
184 register_serializable_item::<Onboarding>(cx);
185 register_serializable_item::<WelcomePage>(cx);
186}
187
188pub fn show_onboarding_view(app_state: Arc<AppState>, cx: &mut App) -> Task<anyhow::Result<()>> {
189 telemetry::event!("Onboarding Page Opened");
190 open_new(
191 Default::default(),
192 app_state,
193 cx,
194 |workspace, window, cx| {
195 {
196 workspace.toggle_dock(DockPosition::Left, window, cx);
197 let onboarding_page = Onboarding::new(workspace, cx);
198 workspace.add_item_to_center(Box::new(onboarding_page.clone()), window, cx);
199
200 window.focus(&onboarding_page.focus_handle(cx));
201
202 cx.notify();
203 };
204 db::write_and_log(cx, || {
205 KEY_VALUE_STORE.write_kvp(FIRST_OPEN.to_string(), "false".to_string())
206 });
207 },
208 )
209}
210
211struct Onboarding {
212 workspace: WeakEntity<Workspace>,
213 focus_handle: FocusHandle,
214 user_store: Entity<UserStore>,
215 scroll_handle: ScrollHandle,
216 _settings_subscription: Subscription,
217}
218
219impl Onboarding {
220 fn new(workspace: &Workspace, cx: &mut App) -> Entity<Self> {
221 let font_family_cache = theme::FontFamilyCache::global(cx);
222
223 cx.new(|cx| {
224 cx.spawn(async move |this, cx| {
225 font_family_cache.prefetch(cx).await;
226 this.update(cx, |_, cx| {
227 cx.notify();
228 })
229 })
230 .detach();
231
232 Self {
233 workspace: workspace.weak_handle(),
234 focus_handle: cx.focus_handle(),
235 scroll_handle: ScrollHandle::new(),
236 user_store: workspace.user_store().clone(),
237 _settings_subscription: cx
238 .observe_global::<SettingsStore>(move |_, cx| cx.notify()),
239 }
240 })
241 }
242
243 fn on_finish(_: &Finish, _: &mut Window, cx: &mut App) {
244 telemetry::event!("Finish Setup");
245 go_to_welcome_page(cx);
246 }
247
248 fn handle_sign_in(_: &SignIn, window: &mut Window, cx: &mut App) {
249 let client = Client::global(cx);
250
251 window
252 .spawn(cx, async move |cx| {
253 client
254 .sign_in_with_optional_connect(true, cx)
255 .await
256 .notify_async_err(cx);
257 })
258 .detach();
259 }
260
261 fn handle_open_account(_: &OpenAccount, _: &mut Window, cx: &mut App) {
262 cx.open_url(&zed_urls::account_url(cx))
263 }
264
265 fn render_page(&mut self, cx: &mut Context<Self>) -> AnyElement {
266 crate::basics_page::render_basics_page(cx).into_any_element()
267 }
268}
269
270impl Render for Onboarding {
271 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
272 div()
273 .image_cache(gpui::retain_all("onboarding-page"))
274 .key_context({
275 let mut ctx = KeyContext::new_with_defaults();
276 ctx.add("Onboarding");
277 ctx.add("menu");
278 ctx
279 })
280 .track_focus(&self.focus_handle)
281 .size_full()
282 .bg(cx.theme().colors().editor_background)
283 .on_action(Self::on_finish)
284 .on_action(Self::handle_sign_in)
285 .on_action(Self::handle_open_account)
286 .on_action(cx.listener(|_, _: &menu::SelectNext, window, cx| {
287 window.focus_next();
288 cx.notify();
289 }))
290 .on_action(cx.listener(|_, _: &menu::SelectPrevious, window, cx| {
291 window.focus_prev();
292 cx.notify();
293 }))
294 .child(
295 div()
296 .max_w(Rems(48.0))
297 .w_full()
298 .mx_auto()
299 .size_full()
300 .gap_6()
301 .child(
302 v_flex()
303 .m_auto()
304 .id("page-content")
305 .gap_6()
306 .size_full()
307 .max_w_full()
308 .min_w_0()
309 .p_12()
310 .border_color(cx.theme().colors().border_variant.opacity(0.5))
311 .overflow_y_scroll()
312 .child(
313 h_flex()
314 .w_full()
315 .gap_4()
316 .child(Vector::square(VectorName::ZedLogo, rems(2.5)))
317 .child(
318 v_flex()
319 .child(
320 Headline::new("Welcome to Zed")
321 .size(HeadlineSize::Small),
322 )
323 .child(
324 Label::new("The editor for what's next")
325 .color(Color::Muted)
326 .size(LabelSize::Small)
327 .italic(),
328 ),
329 )
330 .child(div().w_full())
331 .child({
332 Button::new("finish_setup", "Finish Setup")
333 .style(ButtonStyle::Filled)
334 .size(ButtonSize::Large)
335 .width(Rems(12.0))
336 .key_binding(
337 KeyBinding::for_action_in(
338 &Finish,
339 &self.focus_handle,
340 window,
341 cx,
342 )
343 .map(|kb| kb.size(rems_from_px(12.))),
344 )
345 .on_click(|_, window, cx| {
346 window.dispatch_action(Finish.boxed_clone(), cx);
347 })
348 })
349 .pb_6()
350 .border_b_1()
351 .border_color(cx.theme().colors().border_variant.opacity(0.5)),
352 )
353 .child(self.render_page(cx))
354 .track_scroll(&self.scroll_handle),
355 )
356 .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
357 )
358 }
359}
360
361impl EventEmitter<ItemEvent> for Onboarding {}
362
363impl Focusable for Onboarding {
364 fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
365 self.focus_handle.clone()
366 }
367}
368
369impl Item for Onboarding {
370 type Event = ItemEvent;
371
372 fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
373 "Onboarding".into()
374 }
375
376 fn telemetry_event_text(&self) -> Option<&'static str> {
377 Some("Onboarding Page Opened")
378 }
379
380 fn show_toolbar(&self) -> bool {
381 false
382 }
383
384 fn clone_on_split(
385 &self,
386 _workspace_id: Option<WorkspaceId>,
387 _: &mut Window,
388 cx: &mut Context<Self>,
389 ) -> Option<Entity<Self>> {
390 Some(cx.new(|cx| Onboarding {
391 workspace: self.workspace.clone(),
392 user_store: self.user_store.clone(),
393 scroll_handle: ScrollHandle::new(),
394 focus_handle: cx.focus_handle(),
395 _settings_subscription: cx.observe_global::<SettingsStore>(move |_, cx| cx.notify()),
396 }))
397 }
398
399 fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
400 f(*event)
401 }
402}
403
404fn go_to_welcome_page(cx: &mut App) {
405 with_active_or_new_workspace(cx, |workspace, window, cx| {
406 let Some((onboarding_id, onboarding_idx)) = workspace
407 .active_pane()
408 .read(cx)
409 .items()
410 .enumerate()
411 .find_map(|(idx, item)| {
412 let _ = item.downcast::<Onboarding>()?;
413 Some((item.item_id(), idx))
414 })
415 else {
416 return;
417 };
418
419 workspace.active_pane().update(cx, |pane, cx| {
420 // Get the index here to get around the borrow checker
421 let idx = pane.items().enumerate().find_map(|(idx, item)| {
422 let _ = item.downcast::<WelcomePage>()?;
423 Some(idx)
424 });
425
426 if let Some(idx) = idx {
427 pane.activate_item(idx, true, true, window, cx);
428 } else {
429 let item = Box::new(WelcomePage::new(window, cx));
430 pane.add_item(item, true, true, Some(onboarding_idx), window, cx);
431 }
432
433 pane.remove_item(onboarding_id, false, false, window, cx);
434 });
435 });
436}
437
438pub async fn handle_import_vscode_settings(
439 workspace: WeakEntity<Workspace>,
440 source: VsCodeSettingsSource,
441 skip_prompt: bool,
442 fs: Arc<dyn Fs>,
443 cx: &mut AsyncWindowContext,
444) {
445 use util::truncate_and_remove_front;
446
447 let vscode_settings =
448 match settings::VsCodeSettings::load_user_settings(source, fs.clone()).await {
449 Ok(vscode_settings) => vscode_settings,
450 Err(err) => {
451 zlog::error!("{err}");
452 let _ = cx.prompt(
453 gpui::PromptLevel::Info,
454 &format!("Could not find or load a {source} settings file"),
455 None,
456 &["Ok"],
457 );
458 return;
459 }
460 };
461
462 if !skip_prompt {
463 let prompt = cx.prompt(
464 gpui::PromptLevel::Warning,
465 &format!(
466 "Importing {} settings may overwrite your existing settings. \
467 Will import settings from {}",
468 vscode_settings.source,
469 truncate_and_remove_front(&vscode_settings.path.to_string_lossy(), 128),
470 ),
471 None,
472 &["Ok", "Cancel"],
473 );
474 let result = cx.spawn(async move |_| prompt.await.ok()).await;
475 if result != Some(0) {
476 return;
477 }
478 };
479
480 let Ok(result_channel) = cx.update(|_, cx| {
481 let source = vscode_settings.source;
482 let path = vscode_settings.path.clone();
483 let result_channel = cx
484 .global::<SettingsStore>()
485 .import_vscode_settings(fs, vscode_settings);
486 zlog::info!("Imported {source} settings from {}", path.display());
487 result_channel
488 }) else {
489 return;
490 };
491
492 let result = result_channel.await;
493 workspace
494 .update_in(cx, |workspace, _, cx| match result {
495 Ok(_) => {
496 let confirmation_toast = StatusToast::new(
497 format!("Your {} settings were successfully imported.", source),
498 cx,
499 |this, _| {
500 this.icon(ToastIcon::new(IconName::Check).color(Color::Success))
501 .dismiss_button(true)
502 },
503 );
504 SettingsImportState::update(cx, |state, _| match source {
505 VsCodeSettingsSource::VsCode => {
506 state.vscode = true;
507 }
508 VsCodeSettingsSource::Cursor => {
509 state.cursor = true;
510 }
511 });
512 workspace.toggle_status_toast(confirmation_toast, cx);
513 }
514 Err(_) => {
515 let error_toast = StatusToast::new(
516 "Failed to import settings. See log for details",
517 cx,
518 |this, _| {
519 this.icon(ToastIcon::new(IconName::Close).color(Color::Error))
520 .action("Open Log", |window, cx| {
521 window.dispatch_action(workspace::OpenLog.boxed_clone(), cx)
522 })
523 .dismiss_button(true)
524 },
525 );
526 workspace.toggle_status_toast(error_toast, cx);
527 }
528 })
529 .ok();
530}
531
532#[derive(Default, Copy, Clone)]
533pub struct SettingsImportState {
534 pub cursor: bool,
535 pub vscode: bool,
536}
537
538impl Global for SettingsImportState {}
539
540impl SettingsImportState {
541 pub fn global(cx: &App) -> Self {
542 cx.try_global().cloned().unwrap_or_default()
543 }
544 pub fn update<R>(cx: &mut App, f: impl FnOnce(&mut Self, &mut App) -> R) -> R {
545 cx.update_default_global(f)
546 }
547}
548
549impl workspace::SerializableItem for Onboarding {
550 fn serialized_item_kind() -> &'static str {
551 "OnboardingPage"
552 }
553
554 fn cleanup(
555 workspace_id: workspace::WorkspaceId,
556 alive_items: Vec<workspace::ItemId>,
557 _window: &mut Window,
558 cx: &mut App,
559 ) -> gpui::Task<gpui::Result<()>> {
560 workspace::delete_unloaded_items(
561 alive_items,
562 workspace_id,
563 "onboarding_pages",
564 &persistence::ONBOARDING_PAGES,
565 cx,
566 )
567 }
568
569 fn deserialize(
570 _project: Entity<project::Project>,
571 workspace: WeakEntity<Workspace>,
572 workspace_id: workspace::WorkspaceId,
573 item_id: workspace::ItemId,
574 window: &mut Window,
575 cx: &mut App,
576 ) -> gpui::Task<gpui::Result<Entity<Self>>> {
577 window.spawn(cx, async move |cx| {
578 if let Some(_) =
579 persistence::ONBOARDING_PAGES.get_onboarding_page(item_id, workspace_id)?
580 {
581 workspace.update(cx, |workspace, cx| Onboarding::new(workspace, cx))
582 } else {
583 Err(anyhow::anyhow!("No onboarding page to deserialize"))
584 }
585 })
586 }
587
588 fn serialize(
589 &mut self,
590 workspace: &mut Workspace,
591 item_id: workspace::ItemId,
592 _closing: bool,
593 _window: &mut Window,
594 cx: &mut ui::Context<Self>,
595 ) -> Option<gpui::Task<gpui::Result<()>>> {
596 let workspace_id = workspace.database_id()?;
597
598 Some(cx.background_spawn(async move {
599 persistence::ONBOARDING_PAGES
600 .save_onboarding_page(item_id, workspace_id)
601 .await
602 }))
603 }
604
605 fn should_serialize(&self, event: &Self::Event) -> bool {
606 event == &ItemEvent::UpdateTab
607 }
608}
609
610mod persistence {
611 use db::{
612 query,
613 sqlez::{domain::Domain, thread_safe_connection::ThreadSafeConnection},
614 sqlez_macros::sql,
615 };
616 use workspace::WorkspaceDb;
617
618 pub struct OnboardingPagesDb(ThreadSafeConnection);
619
620 impl Domain for OnboardingPagesDb {
621 const NAME: &str = stringify!(OnboardingPagesDb);
622
623 const MIGRATIONS: &[&str] = &[
624 sql!(
625 CREATE TABLE onboarding_pages (
626 workspace_id INTEGER,
627 item_id INTEGER UNIQUE,
628 page_number INTEGER,
629
630 PRIMARY KEY(workspace_id, item_id),
631 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
632 ON DELETE CASCADE
633 ) STRICT;
634 ),
635 sql!(
636 CREATE TABLE onboarding_pages_2 (
637 workspace_id INTEGER,
638 item_id INTEGER UNIQUE,
639
640 PRIMARY KEY(workspace_id, item_id),
641 FOREIGN KEY(workspace_id) REFERENCES workspaces(workspace_id)
642 ON DELETE CASCADE
643 ) STRICT;
644 INSERT INTO onboarding_pages_2 SELECT workspace_id, item_id FROM onboarding_pages;
645 DROP TABLE onboarding_pages;
646 ALTER TABLE onboarding_pages_2 RENAME TO onboarding_pages;
647 ),
648 ];
649 }
650
651 db::static_connection!(ONBOARDING_PAGES, OnboardingPagesDb, [WorkspaceDb]);
652
653 impl OnboardingPagesDb {
654 query! {
655 pub async fn save_onboarding_page(
656 item_id: workspace::ItemId,
657 workspace_id: workspace::WorkspaceId
658 ) -> Result<()> {
659 INSERT OR REPLACE INTO onboarding_pages(item_id, workspace_id)
660 VALUES (?, ?)
661 }
662 }
663
664 query! {
665 pub fn get_onboarding_page(
666 item_id: workspace::ItemId,
667 workspace_id: workspace::WorkspaceId
668 ) -> Result<Option<workspace::ItemId>> {
669 SELECT item_id
670 FROM onboarding_pages
671 WHERE item_id = ? AND workspace_id = ?
672 }
673 }
674 }
675}