onboarding.rs

  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    Divider, KeyBinding, ParentElement as _, StatefulInteractiveElement, Vector, VectorName,
 18    WithScrollbar as _, prelude::*, rems_from_px,
 19};
 20use workspace::{
 21    AppState, Workspace, WorkspaceId,
 22    dock::DockPosition,
 23    item::{Item, ItemEvent},
 24    notifications::NotifyResultExt as _,
 25    open_new, register_serializable_item, with_active_or_new_workspace,
 26};
 27
 28mod base_keymap_picker;
 29mod basics_page;
 30pub mod multibuffer_hint;
 31mod theme_preview;
 32mod welcome;
 33
 34/// Imports settings from Visual Studio Code.
 35#[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
 36#[action(namespace = zed)]
 37#[serde(deny_unknown_fields)]
 38pub struct ImportVsCodeSettings {
 39    #[serde(default)]
 40    pub skip_prompt: bool,
 41}
 42
 43/// Imports settings from Cursor editor.
 44#[derive(Copy, Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)]
 45#[action(namespace = zed)]
 46#[serde(deny_unknown_fields)]
 47pub struct ImportCursorSettings {
 48    #[serde(default)]
 49    pub skip_prompt: bool,
 50}
 51
 52pub const FIRST_OPEN: &str = "first_open";
 53pub const DOCS_URL: &str = "https://zed.dev/docs/";
 54
 55actions!(
 56    zed,
 57    [
 58        /// Opens the onboarding view.
 59        OpenOnboarding
 60    ]
 61);
 62
 63actions!(
 64    onboarding,
 65    [
 66        /// Finish the onboarding process.
 67        Finish,
 68        /// Sign in while in the onboarding flow.
 69        SignIn,
 70        /// Open the user account in zed.dev while in the onboarding flow.
 71        OpenAccount,
 72        /// Resets the welcome screen hints to their initial state.
 73        ResetHints
 74    ]
 75);
 76
 77pub fn init(cx: &mut App) {
 78    cx.observe_new(|workspace: &mut Workspace, _, _cx| {
 79        workspace
 80            .register_action(|_workspace, _: &ResetHints, _, cx| MultibufferHint::set_count(0, cx));
 81    })
 82    .detach();
 83
 84    cx.on_action(|_: &OpenOnboarding, cx| {
 85        with_active_or_new_workspace(cx, |workspace, window, cx| {
 86            workspace
 87                .with_local_workspace(window, cx, |workspace, window, cx| {
 88                    let existing = workspace
 89                        .active_pane()
 90                        .read(cx)
 91                        .items()
 92                        .find_map(|item| item.downcast::<Onboarding>());
 93
 94                    if let Some(existing) = existing {
 95                        workspace.activate_item(&existing, true, true, window, cx);
 96                    } else {
 97                        let settings_page = Onboarding::new(workspace, cx);
 98                        workspace.add_item_to_active_pane(
 99                            Box::new(settings_page),
100                            None,
101                            true,
102                            window,
103                            cx,
104                        )
105                    }
106                })
107                .detach();
108        });
109    });
110
111    cx.on_action(|_: &ShowWelcome, cx| {
112        with_active_or_new_workspace(cx, |workspace, window, cx| {
113            workspace
114                .with_local_workspace(window, cx, |workspace, window, cx| {
115                    let existing = workspace
116                        .active_pane()
117                        .read(cx)
118                        .items()
119                        .find_map(|item| item.downcast::<WelcomePage>());
120
121                    if let Some(existing) = existing {
122                        workspace.activate_item(&existing, true, true, window, cx);
123                    } else {
124                        let settings_page = WelcomePage::new(window, cx);
125                        workspace.add_item_to_active_pane(
126                            Box::new(settings_page),
127                            None,
128                            true,
129                            window,
130                            cx,
131                        )
132                    }
133                })
134                .detach();
135        });
136    });
137
138    cx.observe_new(|workspace: &mut Workspace, _window, _cx| {
139        workspace.register_action(|_workspace, action: &ImportVsCodeSettings, window, cx| {
140            let fs = <dyn Fs>::global(cx);
141            let action = *action;
142
143            let workspace = cx.weak_entity();
144
145            window
146                .spawn(cx, async move |cx: &mut AsyncWindowContext| {
147                    handle_import_vscode_settings(
148                        workspace,
149                        VsCodeSettingsSource::VsCode,
150                        action.skip_prompt,
151                        fs,
152                        cx,
153                    )
154                    .await
155                })
156                .detach();
157        });
158
159        workspace.register_action(|_workspace, action: &ImportCursorSettings, window, cx| {
160            let fs = <dyn Fs>::global(cx);
161            let action = *action;
162
163            let workspace = cx.weak_entity();
164
165            window
166                .spawn(cx, async move |cx: &mut AsyncWindowContext| {
167                    handle_import_vscode_settings(
168                        workspace,
169                        VsCodeSettingsSource::Cursor,
170                        action.skip_prompt,
171                        fs,
172                        cx,
173                    )
174                    .await
175                })
176                .detach();
177        });
178    })
179    .detach();
180
181    base_keymap_picker::init(cx);
182
183    register_serializable_item::<Onboarding>(cx);
184    register_serializable_item::<WelcomePage>(cx);
185}
186
187pub fn show_onboarding_view(app_state: Arc<AppState>, cx: &mut App) -> Task<anyhow::Result<()>> {
188    telemetry::event!("Onboarding Page Opened");
189    open_new(
190        Default::default(),
191        app_state,
192        cx,
193        |workspace, window, cx| {
194            {
195                workspace.toggle_dock(DockPosition::Left, window, cx);
196                let onboarding_page = Onboarding::new(workspace, cx);
197                workspace.add_item_to_center(Box::new(onboarding_page.clone()), window, cx);
198
199                window.focus(&onboarding_page.focus_handle(cx));
200
201                cx.notify();
202            };
203            db::write_and_log(cx, || {
204                KEY_VALUE_STORE.write_kvp(FIRST_OPEN.to_string(), "false".to_string())
205            });
206        },
207    )
208}
209
210struct Onboarding {
211    workspace: WeakEntity<Workspace>,
212    focus_handle: FocusHandle,
213    user_store: Entity<UserStore>,
214    scroll_handle: ScrollHandle,
215    _settings_subscription: Subscription,
216}
217
218impl Onboarding {
219    fn new(workspace: &Workspace, cx: &mut App) -> Entity<Self> {
220        let font_family_cache = theme::FontFamilyCache::global(cx);
221
222        cx.new(|cx| {
223            cx.spawn(async move |this, cx| {
224                font_family_cache.prefetch(cx).await;
225                this.update(cx, |_, cx| {
226                    cx.notify();
227                })
228            })
229            .detach();
230
231            Self {
232                workspace: workspace.weak_handle(),
233                focus_handle: cx.focus_handle(),
234                scroll_handle: ScrollHandle::new(),
235                user_store: workspace.user_store().clone(),
236                _settings_subscription: cx
237                    .observe_global::<SettingsStore>(move |_, cx| cx.notify()),
238            }
239        })
240    }
241
242    fn on_finish(_: &Finish, _: &mut Window, cx: &mut App) {
243        telemetry::event!("Finish Setup");
244        go_to_welcome_page(cx);
245    }
246
247    fn handle_sign_in(_: &SignIn, window: &mut Window, cx: &mut App) {
248        let client = Client::global(cx);
249
250        window
251            .spawn(cx, async move |cx| {
252                client
253                    .sign_in_with_optional_connect(true, cx)
254                    .await
255                    .notify_async_err(cx);
256            })
257            .detach();
258    }
259
260    fn handle_open_account(_: &OpenAccount, _: &mut Window, cx: &mut App) {
261        cx.open_url(&zed_urls::account_url(cx))
262    }
263
264    fn render_page(&mut self, cx: &mut Context<Self>) -> AnyElement {
265        crate::basics_page::render_basics_page(cx).into_any_element()
266    }
267}
268
269impl Render for Onboarding {
270    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
271        div()
272            .image_cache(gpui::retain_all("onboarding-page"))
273            .key_context({
274                let mut ctx = KeyContext::new_with_defaults();
275                ctx.add("Onboarding");
276                ctx.add("menu");
277                ctx
278            })
279            .track_focus(&self.focus_handle)
280            .size_full()
281            .bg(cx.theme().colors().editor_background)
282            .on_action(Self::on_finish)
283            .on_action(Self::handle_sign_in)
284            .on_action(Self::handle_open_account)
285            .on_action(cx.listener(|_, _: &menu::SelectNext, window, cx| {
286                window.focus_next();
287                cx.notify();
288            }))
289            .on_action(cx.listener(|_, _: &menu::SelectPrevious, window, cx| {
290                window.focus_prev();
291                cx.notify();
292            }))
293            .child(
294                div()
295                    .max_w(Rems(48.0))
296                    .size_full()
297                    .mx_auto()
298                    .child(
299                        v_flex()
300                            .id("page-content")
301                            .m_auto()
302                            .p_12()
303                            .size_full()
304                            .max_w_full()
305                            .min_w_0()
306                            .gap_6()
307                            .overflow_y_scroll()
308                            .child(
309                                h_flex()
310                                    .w_full()
311                                    .gap_4()
312                                    .justify_between()
313                                    .child(
314                                        h_flex()
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                                    )
331                                    .child({
332                                        Button::new("finish_setup", "Finish Setup")
333                                            .style(ButtonStyle::Filled)
334                                            .size(ButtonSize::Medium)
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                            )
350                            .child(Divider::horizontal().color(ui::DividerColor::BorderVariant))
351                            .child(self.render_page(cx))
352                            .track_scroll(&self.scroll_handle),
353                    )
354                    .vertical_scrollbar_for(self.scroll_handle.clone(), window, cx),
355            )
356    }
357}
358
359impl EventEmitter<ItemEvent> for Onboarding {}
360
361impl Focusable for Onboarding {
362    fn focus_handle(&self, _: &App) -> gpui::FocusHandle {
363        self.focus_handle.clone()
364    }
365}
366
367impl Item for Onboarding {
368    type Event = ItemEvent;
369
370    fn tab_content_text(&self, _detail: usize, _cx: &App) -> SharedString {
371        "Onboarding".into()
372    }
373
374    fn telemetry_event_text(&self) -> Option<&'static str> {
375        Some("Onboarding Page Opened")
376    }
377
378    fn show_toolbar(&self) -> bool {
379        false
380    }
381
382    fn clone_on_split(
383        &self,
384        _workspace_id: Option<WorkspaceId>,
385        _: &mut Window,
386        cx: &mut Context<Self>,
387    ) -> Option<Entity<Self>> {
388        Some(cx.new(|cx| Onboarding {
389            workspace: self.workspace.clone(),
390            user_store: self.user_store.clone(),
391            scroll_handle: ScrollHandle::new(),
392            focus_handle: cx.focus_handle(),
393            _settings_subscription: cx.observe_global::<SettingsStore>(move |_, cx| cx.notify()),
394        }))
395    }
396
397    fn to_item_events(event: &Self::Event, mut f: impl FnMut(workspace::item::ItemEvent)) {
398        f(*event)
399    }
400}
401
402fn go_to_welcome_page(cx: &mut App) {
403    with_active_or_new_workspace(cx, |workspace, window, cx| {
404        let Some((onboarding_id, onboarding_idx)) = workspace
405            .active_pane()
406            .read(cx)
407            .items()
408            .enumerate()
409            .find_map(|(idx, item)| {
410                let _ = item.downcast::<Onboarding>()?;
411                Some((item.item_id(), idx))
412            })
413        else {
414            return;
415        };
416
417        workspace.active_pane().update(cx, |pane, cx| {
418            // Get the index here to get around the borrow checker
419            let idx = pane.items().enumerate().find_map(|(idx, item)| {
420                let _ = item.downcast::<WelcomePage>()?;
421                Some(idx)
422            });
423
424            if let Some(idx) = idx {
425                pane.activate_item(idx, true, true, window, cx);
426            } else {
427                let item = Box::new(WelcomePage::new(window, cx));
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}