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