1use crate::multibuffer_hint::MultibufferHint;
2use client::{Client, UserStore, zed_urls};
3use db::kvp::KEY_VALUE_STORE;
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};
19pub use workspace::welcome::ShowWelcome;
20use workspace::welcome::WelcomePage;
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};
28use zed_actions::OpenOnboarding;
29
30mod base_keymap_picker;
31mod basics_page;
32pub mod multibuffer_hint;
33mod theme_preview;
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 onboarding,
58 [
59 /// Finish the onboarding process.
60 Finish,
61 /// Sign in while in the onboarding flow.
62 SignIn,
63 /// Open the user account in zed.dev while in the onboarding flow.
64 OpenAccount,
65 /// Resets the welcome screen hints to their initial state.
66 ResetHints
67 ]
68);
69
70pub fn init(cx: &mut App) {
71 cx.observe_new(|workspace: &mut Workspace, _, _cx| {
72 workspace
73 .register_action(|_workspace, _: &ResetHints, _, cx| MultibufferHint::set_count(0, cx));
74 })
75 .detach();
76
77 cx.on_action(|_: &OpenOnboarding, cx| {
78 with_active_or_new_workspace(cx, |workspace, window, cx| {
79 workspace
80 .with_local_workspace(window, cx, |workspace, window, cx| {
81 let existing = workspace
82 .active_pane()
83 .read(cx)
84 .items()
85 .find_map(|item| item.downcast::<Onboarding>());
86
87 if let Some(existing) = existing {
88 workspace.activate_item(&existing, true, true, window, cx);
89 } else {
90 let settings_page = Onboarding::new(workspace, cx);
91 workspace.add_item_to_active_pane(
92 Box::new(settings_page),
93 None,
94 true,
95 window,
96 cx,
97 )
98 }
99 })
100 .detach();
101 });
102 });
103
104 cx.on_action(|_: &ShowWelcome, cx| {
105 with_active_or_new_workspace(cx, |workspace, window, cx| {
106 workspace
107 .with_local_workspace(window, cx, |workspace, window, cx| {
108 let existing = workspace
109 .active_pane()
110 .read(cx)
111 .items()
112 .find_map(|item| item.downcast::<WelcomePage>());
113
114 if let Some(existing) = existing {
115 workspace.activate_item(&existing, true, true, window, cx);
116 } else {
117 let settings_page = cx
118 .new(|cx| WelcomePage::new(workspace.weak_handle(), false, window, cx));
119 workspace.add_item_to_active_pane(
120 Box::new(settings_page),
121 None,
122 true,
123 window,
124 cx,
125 )
126 }
127 })
128 .detach();
129 });
130 });
131
132 cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
133 workspace.register_action(|_workspace, action: &ImportVsCodeSettings, window, cx| {
134 let fs = <dyn Fs>::global(cx);
135 let action = *action;
136
137 let workspace = cx.weak_entity();
138
139 window
140 .spawn(cx, async move |cx: &mut AsyncWindowContext| {
141 handle_import_vscode_settings(
142 workspace,
143 VsCodeSettingsSource::VsCode,
144 action.skip_prompt,
145 fs,
146 cx,
147 )
148 .await
149 })
150 .detach();
151 });
152
153 workspace.register_action(|_workspace, action: &ImportCursorSettings, window, cx| {
154 let fs = <dyn Fs>::global(cx);
155 let action = *action;
156
157 let workspace = cx.weak_entity();
158
159 window
160 .spawn(cx, async move |cx: &mut AsyncWindowContext| {
161 handle_import_vscode_settings(
162 workspace,
163 VsCodeSettingsSource::Cursor,
164 action.skip_prompt,
165 fs,
166 cx,
167 )
168 .await
169 })
170 .detach();
171 });
172 })
173 .detach();
174
175 base_keymap_picker::init(cx);
176
177 register_serializable_item::<Onboarding>(cx);
178 register_serializable_item::<WelcomePage>(cx);
179}
180
181pub fn show_onboarding_view(app_state: Arc<AppState>, cx: &mut App) -> Task<anyhow::Result<()>> {
182 telemetry::event!("Onboarding Page Opened");
183 open_new(
184 Default::default(),
185 app_state,
186 cx,
187 |workspace, window, cx| {
188 {
189 workspace.toggle_dock(DockPosition::Left, window, cx);
190 let onboarding_page = Onboarding::new(workspace, cx);
191 workspace.add_item_to_center(Box::new(onboarding_page.clone()), window, cx);
192
193 window.focus(&onboarding_page.focus_handle(cx), cx);
194
195 cx.notify();
196 };
197 db::write_and_log(cx, || {
198 KEY_VALUE_STORE.write_kvp(FIRST_OPEN.to_string(), "false".to_string())
199 });
200 },
201 )
202}
203
204struct Onboarding {
205 workspace: WeakEntity<Workspace>,
206 focus_handle: FocusHandle,
207 user_store: Entity<UserStore>,
208 scroll_handle: ScrollHandle,
209 _settings_subscription: Subscription,
210}
211
212impl Onboarding {
213 fn new(workspace: &Workspace, cx: &mut App) -> Entity<Self> {
214 let font_family_cache = theme::FontFamilyCache::global(cx);
215
216 cx.new(|cx| {
217 cx.spawn(async move |this, cx| {
218 font_family_cache.prefetch(cx).await;
219 this.update(cx, |_, cx| {
220 cx.notify();
221 })
222 })
223 .detach();
224
225 Self {
226 workspace: workspace.weak_handle(),
227 focus_handle: cx.focus_handle(),
228 scroll_handle: ScrollHandle::new(),
229 user_store: workspace.user_store().clone(),
230 _settings_subscription: cx
231 .observe_global::<SettingsStore>(move |_, cx| cx.notify()),
232 }
233 })
234 }
235
236 fn on_finish(_: &Finish, _: &mut Window, cx: &mut App) {
237 telemetry::event!("Finish Setup");
238 go_to_welcome_page(cx);
239 }
240
241 fn handle_sign_in(&mut self, _: &SignIn, window: &mut Window, cx: &mut Context<Self>) {
242 let client = Client::global(cx);
243 let workspace = self.workspace.clone();
244
245 window
246 .spawn(cx, async move |mut cx| {
247 client
248 .sign_in_with_optional_connect(true, &cx)
249 .await
250 .notify_workspace_async_err(workspace, &mut cx);
251 })
252 .detach();
253 }
254
255 fn handle_open_account(_: &OpenAccount, _: &mut Window, cx: &mut App) {
256 cx.open_url(&zed_urls::account_url(cx))
257 }
258
259 fn render_page(&mut self, cx: &mut Context<Self>) -> AnyElement {
260 crate::basics_page::render_basics_page(cx).into_any_element()
261 }
262}
263
264impl Render for Onboarding {
265 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
266 div()
267 .image_cache(gpui::retain_all("onboarding-page"))
268 .key_context({
269 let mut ctx = KeyContext::new_with_defaults();
270 ctx.add("Onboarding");
271 ctx.add("menu");
272 ctx
273 })
274 .track_focus(&self.focus_handle)
275 .size_full()
276 .bg(cx.theme().colors().editor_background)
277 .on_action(Self::on_finish)
278 .on_action(cx.listener(Self::handle_sign_in))
279 .on_action(Self::handle_open_account)
280 .on_action(cx.listener(|_, _: &menu::SelectNext, window, cx| {
281 window.focus_next(cx);
282 cx.notify();
283 }))
284 .on_action(cx.listener(|_, _: &menu::SelectPrevious, window, cx| {
285 window.focus_prev(cx);
286 cx.notify();
287 }))
288 .child(
289 div()
290 .max_w(Rems(48.0))
291 .size_full()
292 .mx_auto()
293 .child(
294 v_flex()
295 .id("page-content")
296 .m_auto()
297 .p_12()
298 .size_full()
299 .max_w_full()
300 .min_w_0()
301 .gap_6()
302 .overflow_y_scroll()
303 .child(
304 h_flex()
305 .w_full()
306 .gap_4()
307 .justify_between()
308 .child(
309 h_flex()
310 .gap_4()
311 .child(Vector::square(VectorName::ZedLogo, rems(2.5)))
312 .child(
313 v_flex()
314 .child(
315 Headline::new("Welcome to Zed")
316 .size(HeadlineSize::Small),
317 )
318 .child(
319 Label::new("The editor for what's next")
320 .color(Color::Muted)
321 .size(LabelSize::Small)
322 .italic(),
323 ),
324 ),
325 )
326 .child({
327 Button::new("finish_setup", "Finish Setup")
328 .style(ButtonStyle::Filled)
329 .size(ButtonSize::Medium)
330 .width(Rems(12.0))
331 .key_binding(
332 KeyBinding::for_action_in(
333 &Finish,
334 &self.focus_handle,
335 cx,
336 )
337 .size(rems_from_px(12.)),
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::ONBOARDING_PAGES,
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 window.spawn(cx, async move |cx| {
576 if let Some(_) =
577 persistence::ONBOARDING_PAGES.get_onboarding_page(item_id, workspace_id)?
578 {
579 workspace.update(cx, |workspace, cx| Onboarding::new(workspace, cx))
580 } else {
581 Err(anyhow::anyhow!("No onboarding page to deserialize"))
582 }
583 })
584 }
585
586 fn serialize(
587 &mut self,
588 workspace: &mut Workspace,
589 item_id: workspace::ItemId,
590 _closing: bool,
591 _window: &mut Window,
592 cx: &mut ui::Context<Self>,
593 ) -> Option<gpui::Task<gpui::Result<()>>> {
594 let workspace_id = workspace.database_id()?;
595
596 Some(cx.background_spawn(async move {
597 persistence::ONBOARDING_PAGES
598 .save_onboarding_page(item_id, workspace_id)
599 .await
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!(ONBOARDING_PAGES, 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}